blob: 3cab3d8b1d45c51f2862b0d0a64b40eecd28c83b [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<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100376 /** All processes we currently have running mapped by pid and uid */
377 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
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) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100916 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900917 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);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003375 } else if (stack.getParent().inFreeformWindowingMode()) {
3376 // If the window is on a freeform display, set it to undefined. It will be
3377 // resolved to freeform and it can adjust windowing mode when the display mode
3378 // changes in runtime.
3379 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003380 } else {
3381 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3382 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003383 } finally {
3384 Binder.restoreCallingIdentity(ident);
3385 }
3386 }
3387 }
3388
3389 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3390 @Override
3391 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003392 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003393 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003394 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 }
3396
3397 /** Unregister a task stack listener so that it stops receiving callbacks. */
3398 @Override
3399 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003402 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003403 }
3404
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003405 @Override
3406 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3407 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3408 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3409 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3410 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3411 }
3412
3413 @Override
3414 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3415 IBinder activityToken, int flags) {
3416 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3417 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3418 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3419 }
3420
3421 @Override
3422 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3423 Bundle args) {
3424 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3425 true /* focused */, true /* newSessionId */, userHandle, args,
3426 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3427 }
3428
3429 @Override
3430 public Bundle getAssistContextExtras(int requestType) {
3431 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3432 null, null, true /* focused */, true /* newSessionId */,
3433 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3434 if (pae == null) {
3435 return null;
3436 }
3437 synchronized (pae) {
3438 while (!pae.haveResult) {
3439 try {
3440 pae.wait();
3441 } catch (InterruptedException e) {
3442 }
3443 }
3444 }
3445 synchronized (mGlobalLock) {
3446 buildAssistBundleLocked(pae, pae.result);
3447 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003448 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003449 }
3450 return pae.extras;
3451 }
3452
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003453 /**
3454 * Binder IPC calls go through the public entry point.
3455 * This can be called with or without the global lock held.
3456 */
3457 private static int checkCallingPermission(String permission) {
3458 return checkPermission(
3459 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3460 }
3461
3462 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003463 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003464 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3465 mAmInternal.enforceCallingPermission(permission, func);
3466 }
3467 }
3468
3469 @VisibleForTesting
3470 int checkGetTasksPermission(String permission, int pid, int uid) {
3471 return checkPermission(permission, pid, uid);
3472 }
3473
3474 static int checkPermission(String permission, int pid, int uid) {
3475 if (permission == null) {
3476 return PackageManager.PERMISSION_DENIED;
3477 }
3478 return checkComponentPermission(permission, pid, uid, -1, true);
3479 }
3480
Wale Ogunwale214f3482018-10-04 11:00:47 -07003481 public static int checkComponentPermission(String permission, int pid, int uid,
3482 int owningUid, boolean exported) {
3483 return ActivityManagerService.checkComponentPermission(
3484 permission, pid, uid, owningUid, exported);
3485 }
3486
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003487 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3488 if (getRecentTasks().isCallerRecents(callingUid)) {
3489 // Always allow the recents component to get tasks
3490 return true;
3491 }
3492
3493 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3494 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3495 if (!allowed) {
3496 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3497 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3498 // Temporary compatibility: some existing apps on the system image may
3499 // still be requesting the old permission and not switched to the new
3500 // one; if so, we'll still allow them full access. This means we need
3501 // to see if they are holding the old permission and are a system app.
3502 try {
3503 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3504 allowed = true;
3505 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3506 + " is using old GET_TASKS but privileged; allowing");
3507 }
3508 } catch (RemoteException e) {
3509 }
3510 }
3511 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3512 + " does not hold REAL_GET_TASKS; limiting output");
3513 }
3514 return allowed;
3515 }
3516
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3518 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3519 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3520 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003521 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003522 "enqueueAssistContext()");
3523
3524 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003525 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003526 if (activity == null) {
3527 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3528 return null;
3529 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003530 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003531 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3532 return null;
3533 }
3534 if (focused) {
3535 if (activityToken != null) {
3536 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3537 if (activity != caller) {
3538 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3539 + " is not current top " + activity);
3540 return null;
3541 }
3542 }
3543 } else {
3544 activity = ActivityRecord.forTokenLocked(activityToken);
3545 if (activity == null) {
3546 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3547 + " couldn't be found");
3548 return null;
3549 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003550 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003551 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3552 return null;
3553 }
3554 }
3555
3556 PendingAssistExtras pae;
3557 Bundle extras = new Bundle();
3558 if (args != null) {
3559 extras.putAll(args);
3560 }
3561 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003562 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003563
3564 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3565 userHandle);
3566 pae.isHome = activity.isActivityTypeHome();
3567
3568 // Increment the sessionId if necessary
3569 if (newSessionId) {
3570 mViSessionId++;
3571 }
3572 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003573 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3574 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003575 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003576 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003577 } catch (RemoteException e) {
3578 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3579 return null;
3580 }
3581 return pae;
3582 }
3583 }
3584
3585 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3586 if (result != null) {
3587 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3588 }
3589 if (pae.hint != null) {
3590 pae.extras.putBoolean(pae.hint, true);
3591 }
3592 }
3593
3594 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3595 IAssistDataReceiver receiver;
3596 synchronized (mGlobalLock) {
3597 mPendingAssistExtras.remove(pae);
3598 receiver = pae.receiver;
3599 }
3600 if (receiver != null) {
3601 // Caller wants result sent back to them.
3602 Bundle sendBundle = new Bundle();
3603 // At least return the receiver extras
3604 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3605 try {
3606 pae.receiver.onHandleAssistData(sendBundle);
3607 } catch (RemoteException e) {
3608 }
3609 }
3610 }
3611
3612 public class PendingAssistExtras extends Binder implements Runnable {
3613 public final ActivityRecord activity;
3614 public boolean isHome;
3615 public final Bundle extras;
3616 public final Intent intent;
3617 public final String hint;
3618 public final IAssistDataReceiver receiver;
3619 public final int userHandle;
3620 public boolean haveResult = false;
3621 public Bundle result = null;
3622 public AssistStructure structure = null;
3623 public AssistContent content = null;
3624 public Bundle receiverExtras;
3625
3626 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3627 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3628 int _userHandle) {
3629 activity = _activity;
3630 extras = _extras;
3631 intent = _intent;
3632 hint = _hint;
3633 receiver = _receiver;
3634 receiverExtras = _receiverExtras;
3635 userHandle = _userHandle;
3636 }
3637
3638 @Override
3639 public void run() {
3640 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3641 synchronized (this) {
3642 haveResult = true;
3643 notifyAll();
3644 }
3645 pendingAssistExtrasTimedOut(this);
3646 }
3647 }
3648
3649 @Override
3650 public boolean isAssistDataAllowedOnCurrentActivity() {
3651 int userId;
3652 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003653 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003654 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3655 return false;
3656 }
3657
3658 final ActivityRecord activity = focusedStack.getTopActivity();
3659 if (activity == null) {
3660 return false;
3661 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003662 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 }
3664 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3665 }
3666
3667 @Override
3668 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3669 long ident = Binder.clearCallingIdentity();
3670 try {
3671 synchronized (mGlobalLock) {
3672 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003673 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003674 if (top != caller) {
3675 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3676 + " is not current top " + top);
3677 return false;
3678 }
3679 if (!top.nowVisible) {
3680 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3681 + " is not visible");
3682 return false;
3683 }
3684 }
3685 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3686 token);
3687 } finally {
3688 Binder.restoreCallingIdentity(ident);
3689 }
3690 }
3691
3692 @Override
3693 public boolean isRootVoiceInteraction(IBinder token) {
3694 synchronized (mGlobalLock) {
3695 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3696 if (r == null) {
3697 return false;
3698 }
3699 return r.rootVoiceInteraction;
3700 }
3701 }
3702
Wale Ogunwalef6733932018-06-27 05:14:34 -07003703 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3704 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3705 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3706 if (activityToCallback == null) return;
3707 activityToCallback.setVoiceSessionLocked(voiceSession);
3708
3709 // Inform the activity
3710 try {
3711 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3712 voiceInteractor);
3713 long token = Binder.clearCallingIdentity();
3714 try {
3715 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3716 } finally {
3717 Binder.restoreCallingIdentity(token);
3718 }
3719 // TODO: VI Should we cache the activity so that it's easier to find later
3720 // rather than scan through all the stacks and activities?
3721 } catch (RemoteException re) {
3722 activityToCallback.clearVoiceSessionLocked();
3723 // TODO: VI Should this terminate the voice session?
3724 }
3725 }
3726
3727 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3728 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3729 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3730 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3731 boolean wasRunningVoice = mRunningVoice != null;
3732 mRunningVoice = session;
3733 if (!wasRunningVoice) {
3734 mVoiceWakeLock.acquire();
3735 updateSleepIfNeededLocked();
3736 }
3737 }
3738 }
3739
3740 void finishRunningVoiceLocked() {
3741 if (mRunningVoice != null) {
3742 mRunningVoice = null;
3743 mVoiceWakeLock.release();
3744 updateSleepIfNeededLocked();
3745 }
3746 }
3747
3748 @Override
3749 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3750 synchronized (mGlobalLock) {
3751 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3752 if (keepAwake) {
3753 mVoiceWakeLock.acquire();
3754 } else {
3755 mVoiceWakeLock.release();
3756 }
3757 }
3758 }
3759 }
3760
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003761 @Override
3762 public ComponentName getActivityClassForToken(IBinder token) {
3763 synchronized (mGlobalLock) {
3764 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3765 if (r == null) {
3766 return null;
3767 }
3768 return r.intent.getComponent();
3769 }
3770 }
3771
3772 @Override
3773 public String getPackageForToken(IBinder token) {
3774 synchronized (mGlobalLock) {
3775 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3776 if (r == null) {
3777 return null;
3778 }
3779 return r.packageName;
3780 }
3781 }
3782
3783 @Override
3784 public void showLockTaskEscapeMessage(IBinder token) {
3785 synchronized (mGlobalLock) {
3786 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3787 if (r == null) {
3788 return;
3789 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003790 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003791 }
3792 }
3793
3794 @Override
3795 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003796 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003797 final long token = Binder.clearCallingIdentity();
3798 try {
3799 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003800 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003801 }
3802 } finally {
3803 Binder.restoreCallingIdentity(token);
3804 }
3805 }
3806
3807 /**
3808 * Try to place task to provided position. The final position might be different depending on
3809 * current user and stacks state. The task will be moved to target stack if it's currently in
3810 * different stack.
3811 */
3812 @Override
3813 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003814 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003815 synchronized (mGlobalLock) {
3816 long ident = Binder.clearCallingIdentity();
3817 try {
3818 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3819 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003820 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003821 if (task == null) {
3822 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3823 + taskId);
3824 }
3825
Wale Ogunwaled32da472018-11-16 07:19:28 -08003826 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003827
3828 if (stack == null) {
3829 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3830 + stackId);
3831 }
3832 if (!stack.isActivityTypeStandardOrUndefined()) {
3833 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3834 + " the position of task " + taskId + " in/to non-standard stack");
3835 }
3836
3837 // TODO: Have the callers of this API call a separate reparent method if that is
3838 // what they intended to do vs. having this method also do reparenting.
3839 if (task.getStack() == stack) {
3840 // Change position in current stack.
3841 stack.positionChildAt(task, position);
3842 } else {
3843 // Reparent to new stack.
3844 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3845 !DEFER_RESUME, "positionTaskInStack");
3846 }
3847 } finally {
3848 Binder.restoreCallingIdentity(ident);
3849 }
3850 }
3851 }
3852
3853 @Override
3854 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3855 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3856 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3857 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3858 synchronized (mGlobalLock) {
3859 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3860 if (record == null) {
3861 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3862 + "found for: " + token);
3863 }
3864 record.setSizeConfigurations(horizontalSizeConfiguration,
3865 verticalSizeConfigurations, smallestSizeConfigurations);
3866 }
3867 }
3868
3869 /**
3870 * Dismisses split-screen multi-window mode.
3871 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3872 */
3873 @Override
3874 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003875 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003876 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3877 final long ident = Binder.clearCallingIdentity();
3878 try {
3879 synchronized (mGlobalLock) {
3880 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003881 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 if (stack == null) {
3883 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3884 return;
3885 }
3886
3887 if (toTop) {
3888 // Caller wants the current split-screen primary stack to be the top stack after
3889 // it goes fullscreen, so move it to the front.
3890 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003891 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003892 // In this case the current split-screen primary stack shouldn't be the top
3893 // stack after it goes fullscreen, but it current has focus, so we move the
3894 // focus to the top-most split-screen secondary stack next to it.
3895 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3896 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3897 if (otherStack != null) {
3898 otherStack.moveToFront("dismissSplitScreenMode_other");
3899 }
3900 }
3901
Evan Rosky10475742018-09-05 19:02:48 -07003902 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003903 }
3904 } finally {
3905 Binder.restoreCallingIdentity(ident);
3906 }
3907 }
3908
3909 /**
3910 * Dismisses Pip
3911 * @param animate True if the dismissal should be animated.
3912 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3913 * default animation duration should be used.
3914 */
3915 @Override
3916 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003917 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 final long ident = Binder.clearCallingIdentity();
3919 try {
3920 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003921 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003922 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003923 if (stack == null) {
3924 Slog.w(TAG, "dismissPip: pinned stack not found.");
3925 return;
3926 }
3927 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3928 throw new IllegalArgumentException("Stack: " + stack
3929 + " doesn't support animated resize.");
3930 }
3931 if (animate) {
3932 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3933 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3934 } else {
3935 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3936 }
3937 }
3938 } finally {
3939 Binder.restoreCallingIdentity(ident);
3940 }
3941 }
3942
3943 @Override
3944 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003945 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003946 synchronized (mGlobalLock) {
3947 mSuppressResizeConfigChanges = suppress;
3948 }
3949 }
3950
3951 /**
3952 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3953 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3954 * activity and clearing the task at the same time.
3955 */
3956 @Override
3957 // TODO: API should just be about changing windowing modes...
3958 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003959 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 "moveTasksToFullscreenStack()");
3961 synchronized (mGlobalLock) {
3962 final long origId = Binder.clearCallingIdentity();
3963 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003964 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003965 if (stack != null){
3966 if (!stack.isActivityTypeStandardOrUndefined()) {
3967 throw new IllegalArgumentException(
3968 "You can't move tasks from non-standard stacks.");
3969 }
3970 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3971 }
3972 } finally {
3973 Binder.restoreCallingIdentity(origId);
3974 }
3975 }
3976 }
3977
3978 /**
3979 * Moves the top activity in the input stackId to the pinned stack.
3980 *
3981 * @param stackId Id of stack to move the top activity to pinned stack.
3982 * @param bounds Bounds to use for pinned stack.
3983 *
3984 * @return True if the top activity of the input stack was successfully moved to the pinned
3985 * stack.
3986 */
3987 @Override
3988 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003989 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 "moveTopActivityToPinnedStack()");
3991 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3994 + "Device doesn't support picture-in-picture mode");
3995 }
3996
3997 long ident = Binder.clearCallingIdentity();
3998 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003999 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 } finally {
4001 Binder.restoreCallingIdentity(ident);
4002 }
4003 }
4004 }
4005
4006 @Override
4007 public boolean isInMultiWindowMode(IBinder token) {
4008 final long origId = Binder.clearCallingIdentity();
4009 try {
4010 synchronized (mGlobalLock) {
4011 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4012 if (r == null) {
4013 return false;
4014 }
4015 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4016 return r.inMultiWindowMode();
4017 }
4018 } finally {
4019 Binder.restoreCallingIdentity(origId);
4020 }
4021 }
4022
4023 @Override
4024 public boolean isInPictureInPictureMode(IBinder token) {
4025 final long origId = Binder.clearCallingIdentity();
4026 try {
4027 synchronized (mGlobalLock) {
4028 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4029 }
4030 } finally {
4031 Binder.restoreCallingIdentity(origId);
4032 }
4033 }
4034
4035 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004036 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4037 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004038 return false;
4039 }
4040
4041 // If we are animating to fullscreen then we have already dispatched the PIP mode
4042 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004043 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4044 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 }
4046
4047 @Override
4048 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4049 final long origId = Binder.clearCallingIdentity();
4050 try {
4051 synchronized (mGlobalLock) {
4052 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4053 "enterPictureInPictureMode", token, params);
4054
4055 // If the activity is already in picture in picture mode, then just return early
4056 if (isInPictureInPictureMode(r)) {
4057 return true;
4058 }
4059
4060 // Activity supports picture-in-picture, now check that we can enter PiP at this
4061 // point, if it is
4062 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4063 false /* beforeStopping */)) {
4064 return false;
4065 }
4066
4067 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004068 synchronized (mGlobalLock) {
4069 // Only update the saved args from the args that are set
4070 r.pictureInPictureArgs.copyOnlySet(params);
4071 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4072 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4073 // Adjust the source bounds by the insets for the transition down
4074 final Rect sourceBounds = new Rect(
4075 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004076 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004077 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004078 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004079 stack.setPictureInPictureAspectRatio(aspectRatio);
4080 stack.setPictureInPictureActions(actions);
4081 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4082 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4083 logPictureInPictureArgs(params);
4084 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004085 };
4086
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004087 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004088 // If the keyguard is showing or occluded, then try and dismiss it before
4089 // entering picture-in-picture (this will prompt the user to authenticate if the
4090 // device is currently locked).
4091 dismissKeyguard(token, new KeyguardDismissCallback() {
4092 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004093 public void onDismissSucceeded() {
4094 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004095 }
4096 }, null /* message */);
4097 } else {
4098 // Enter picture in picture immediately otherwise
4099 enterPipRunnable.run();
4100 }
4101 return true;
4102 }
4103 } finally {
4104 Binder.restoreCallingIdentity(origId);
4105 }
4106 }
4107
4108 @Override
4109 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4110 final long origId = Binder.clearCallingIdentity();
4111 try {
4112 synchronized (mGlobalLock) {
4113 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4114 "setPictureInPictureParams", token, params);
4115
4116 // Only update the saved args from the args that are set
4117 r.pictureInPictureArgs.copyOnlySet(params);
4118 if (r.inPinnedWindowingMode()) {
4119 // If the activity is already in picture-in-picture, update the pinned stack now
4120 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4121 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004122 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004123 if (!stack.isAnimatingBoundsToFullscreen()) {
4124 stack.setPictureInPictureAspectRatio(
4125 r.pictureInPictureArgs.getAspectRatio());
4126 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4127 }
4128 }
4129 logPictureInPictureArgs(params);
4130 }
4131 } finally {
4132 Binder.restoreCallingIdentity(origId);
4133 }
4134 }
4135
4136 @Override
4137 public int getMaxNumPictureInPictureActions(IBinder token) {
4138 // Currently, this is a static constant, but later, we may change this to be dependent on
4139 // the context of the activity
4140 return 3;
4141 }
4142
4143 private void logPictureInPictureArgs(PictureInPictureParams params) {
4144 if (params.hasSetActions()) {
4145 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4146 params.getActions().size());
4147 }
4148 if (params.hasSetAspectRatio()) {
4149 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4150 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4151 MetricsLogger.action(lm);
4152 }
4153 }
4154
4155 /**
4156 * Checks the state of the system and the activity associated with the given {@param token} to
4157 * verify that picture-in-picture is supported for that activity.
4158 *
4159 * @return the activity record for the given {@param token} if all the checks pass.
4160 */
4161 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4162 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004163 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004164 throw new IllegalStateException(caller
4165 + ": Device doesn't support picture-in-picture mode.");
4166 }
4167
4168 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4169 if (r == null) {
4170 throw new IllegalStateException(caller
4171 + ": Can't find activity for token=" + token);
4172 }
4173
4174 if (!r.supportsPictureInPicture()) {
4175 throw new IllegalStateException(caller
4176 + ": Current activity does not support picture-in-picture.");
4177 }
4178
4179 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004180 && !mWindowManager.isValidPictureInPictureAspectRatio(
4181 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 final float minAspectRatio = mContext.getResources().getFloat(
4183 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4184 final float maxAspectRatio = mContext.getResources().getFloat(
4185 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4186 throw new IllegalArgumentException(String.format(caller
4187 + ": Aspect ratio is too extreme (must be between %f and %f).",
4188 minAspectRatio, maxAspectRatio));
4189 }
4190
4191 // Truncate the number of actions if necessary
4192 params.truncateActions(getMaxNumPictureInPictureActions(token));
4193
4194 return r;
4195 }
4196
4197 @Override
4198 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004199 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 synchronized (mGlobalLock) {
4201 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4202 if (r == null) {
4203 throw new IllegalArgumentException("Activity does not exist; token="
4204 + activityToken);
4205 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004206 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004207 }
4208 }
4209
4210 @Override
4211 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4212 Rect tempDockedTaskInsetBounds,
4213 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004214 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 long ident = Binder.clearCallingIdentity();
4216 try {
4217 synchronized (mGlobalLock) {
4218 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4219 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4220 PRESERVE_WINDOWS);
4221 }
4222 } finally {
4223 Binder.restoreCallingIdentity(ident);
4224 }
4225 }
4226
4227 @Override
4228 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004229 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004230 final long ident = Binder.clearCallingIdentity();
4231 try {
4232 synchronized (mGlobalLock) {
4233 mStackSupervisor.setSplitScreenResizing(resizing);
4234 }
4235 } finally {
4236 Binder.restoreCallingIdentity(ident);
4237 }
4238 }
4239
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004240 /**
4241 * Check that we have the features required for VR-related API calls, and throw an exception if
4242 * not.
4243 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004244 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004245 if (!mContext.getPackageManager().hasSystemFeature(
4246 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4247 throw new UnsupportedOperationException("VR mode not supported on this device!");
4248 }
4249 }
4250
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 @Override
4252 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254
4255 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4256
4257 ActivityRecord r;
4258 synchronized (mGlobalLock) {
4259 r = ActivityRecord.isInStackLocked(token);
4260 }
4261
4262 if (r == null) {
4263 throw new IllegalArgumentException();
4264 }
4265
4266 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004267 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004268 VrManagerInternal.NO_ERROR) {
4269 return err;
4270 }
4271
4272 // Clear the binder calling uid since this path may call moveToTask().
4273 final long callingId = Binder.clearCallingIdentity();
4274 try {
4275 synchronized (mGlobalLock) {
4276 r.requestedVrComponent = (enabled) ? packageName : null;
4277
4278 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004279 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004280 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 }
4282 return 0;
4283 }
4284 } finally {
4285 Binder.restoreCallingIdentity(callingId);
4286 }
4287 }
4288
4289 @Override
4290 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4291 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4292 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004293 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4295 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4296 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004297 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 || activity.voiceSession != null) {
4299 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4300 return;
4301 }
4302 if (activity.pendingVoiceInteractionStart) {
4303 Slog.w(TAG, "Pending start of voice interaction already.");
4304 return;
4305 }
4306 activity.pendingVoiceInteractionStart = true;
4307 }
4308 LocalServices.getService(VoiceInteractionManagerInternal.class)
4309 .startLocalVoiceInteraction(callingActivity, options);
4310 }
4311
4312 @Override
4313 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4314 LocalServices.getService(VoiceInteractionManagerInternal.class)
4315 .stopLocalVoiceInteraction(callingActivity);
4316 }
4317
4318 @Override
4319 public boolean supportsLocalVoiceInteraction() {
4320 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4321 .supportsLocalVoiceInteraction();
4322 }
4323
4324 /** Notifies all listeners when the pinned stack animation starts. */
4325 @Override
4326 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004327 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 }
4329
4330 /** Notifies all listeners when the pinned stack animation ends. */
4331 @Override
4332 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004333 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 }
4335
4336 @Override
4337 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004338 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339 final long ident = Binder.clearCallingIdentity();
4340 try {
4341 synchronized (mGlobalLock) {
4342 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4343 }
4344 } finally {
4345 Binder.restoreCallingIdentity(ident);
4346 }
4347 }
4348
4349 @Override
4350 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352
4353 synchronized (mGlobalLock) {
4354 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004355 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 // Call might come when display is not yet added or has already been removed.
4357 if (DEBUG_CONFIGURATION) {
4358 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4359 + displayId);
4360 }
4361 return false;
4362 }
4363
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004364 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004365 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367 }
4368
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004369 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004370 final Message msg = PooledLambda.obtainMessage(
4371 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4372 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 }
4374
4375 final long origId = Binder.clearCallingIdentity();
4376 try {
4377 if (values != null) {
4378 Settings.System.clearConfiguration(values);
4379 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4382 return mTmpUpdateConfigurationResult.changes != 0;
4383 } finally {
4384 Binder.restoreCallingIdentity(origId);
4385 }
4386 }
4387 }
4388
4389 @Override
4390 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004391 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392
4393 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004394 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004396 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004397 }
4398
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004399 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004400 final Message msg = PooledLambda.obtainMessage(
4401 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4402 DEFAULT_DISPLAY);
4403 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 }
4405
4406 final long origId = Binder.clearCallingIdentity();
4407 try {
4408 if (values != null) {
4409 Settings.System.clearConfiguration(values);
4410 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 UserHandle.USER_NULL, false /* deferResume */,
4413 mTmpUpdateConfigurationResult);
4414 return mTmpUpdateConfigurationResult.changes != 0;
4415 } finally {
4416 Binder.restoreCallingIdentity(origId);
4417 }
4418 }
4419 }
4420
4421 @Override
4422 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4423 CharSequence message) {
4424 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004425 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4427 }
4428 final long callingId = Binder.clearCallingIdentity();
4429 try {
4430 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004431 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004432 }
4433 } finally {
4434 Binder.restoreCallingIdentity(callingId);
4435 }
4436 }
4437
4438 @Override
4439 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004440 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 "cancelTaskWindowTransition()");
4442 final long ident = Binder.clearCallingIdentity();
4443 try {
4444 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004445 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 MATCH_TASK_IN_STACKS_ONLY);
4447 if (task == null) {
4448 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4449 return;
4450 }
4451 task.cancelWindowTransition();
4452 }
4453 } finally {
4454 Binder.restoreCallingIdentity(ident);
4455 }
4456 }
4457
4458 @Override
4459 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004460 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 final long ident = Binder.clearCallingIdentity();
4462 try {
4463 final TaskRecord task;
4464 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004465 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004466 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4467 if (task == null) {
4468 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4469 return null;
4470 }
4471 }
4472 // Don't call this while holding the lock as this operation might hit the disk.
4473 return task.getSnapshot(reducedResolution);
4474 } finally {
4475 Binder.restoreCallingIdentity(ident);
4476 }
4477 }
4478
4479 @Override
4480 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4481 synchronized (mGlobalLock) {
4482 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4483 if (r == null) {
4484 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4485 + token);
4486 return;
4487 }
4488 final long origId = Binder.clearCallingIdentity();
4489 try {
4490 r.setDisablePreviewScreenshots(disable);
4491 } finally {
4492 Binder.restoreCallingIdentity(origId);
4493 }
4494 }
4495 }
4496
4497 /** Return the user id of the last resumed activity. */
4498 @Override
4499 public @UserIdInt
4500 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004501 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004502 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4503 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004504 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004505 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004506 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004507 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004508 }
4509 }
4510
4511 @Override
4512 public void updateLockTaskFeatures(int userId, int flags) {
4513 final int callingUid = Binder.getCallingUid();
4514 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004515 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004516 "updateLockTaskFeatures()");
4517 }
4518 synchronized (mGlobalLock) {
4519 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4520 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004521 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 }
4523 }
4524
4525 @Override
4526 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4527 synchronized (mGlobalLock) {
4528 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4529 if (r == null) {
4530 return;
4531 }
4532 final long origId = Binder.clearCallingIdentity();
4533 try {
4534 r.setShowWhenLocked(showWhenLocked);
4535 } finally {
4536 Binder.restoreCallingIdentity(origId);
4537 }
4538 }
4539 }
4540
4541 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004542 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4543 synchronized (mGlobalLock) {
4544 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4545 if (r == null) {
4546 return;
4547 }
4548 final long origId = Binder.clearCallingIdentity();
4549 try {
4550 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4551 } finally {
4552 Binder.restoreCallingIdentity(origId);
4553 }
4554 }
4555 }
4556
4557 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4559 synchronized (mGlobalLock) {
4560 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4561 if (r == null) {
4562 return;
4563 }
4564 final long origId = Binder.clearCallingIdentity();
4565 try {
4566 r.setTurnScreenOn(turnScreenOn);
4567 } finally {
4568 Binder.restoreCallingIdentity(origId);
4569 }
4570 }
4571 }
4572
4573 @Override
4574 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004575 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004576 "registerRemoteAnimations");
4577 definition.setCallingPid(Binder.getCallingPid());
4578 synchronized (mGlobalLock) {
4579 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4580 if (r == null) {
4581 return;
4582 }
4583 final long origId = Binder.clearCallingIdentity();
4584 try {
4585 r.registerRemoteAnimations(definition);
4586 } finally {
4587 Binder.restoreCallingIdentity(origId);
4588 }
4589 }
4590 }
4591
4592 @Override
4593 public void registerRemoteAnimationForNextActivityStart(String packageName,
4594 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004595 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004596 "registerRemoteAnimationForNextActivityStart");
4597 adapter.setCallingPid(Binder.getCallingPid());
4598 synchronized (mGlobalLock) {
4599 final long origId = Binder.clearCallingIdentity();
4600 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004601 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004602 packageName, adapter);
4603 } finally {
4604 Binder.restoreCallingIdentity(origId);
4605 }
4606 }
4607 }
4608
Evan Rosky966759f2019-01-15 10:33:58 -08004609 @Override
4610 public void registerRemoteAnimationsForDisplay(int displayId,
4611 RemoteAnimationDefinition definition) {
4612 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4613 "registerRemoteAnimations");
4614 definition.setCallingPid(Binder.getCallingPid());
4615 synchronized (mGlobalLock) {
4616 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4617 if (display == null) {
4618 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4619 return;
4620 }
4621 final long origId = Binder.clearCallingIdentity();
4622 try {
4623 display.mDisplayContent.registerRemoteAnimations(definition);
4624 } finally {
4625 Binder.restoreCallingIdentity(origId);
4626 }
4627 }
4628 }
4629
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004630 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4631 @Override
4632 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4633 synchronized (mGlobalLock) {
4634 final long origId = Binder.clearCallingIdentity();
4635 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004636 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004637 } finally {
4638 Binder.restoreCallingIdentity(origId);
4639 }
4640 }
4641 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004642
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004643 @Override
4644 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004645 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004646 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004647 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004648 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004649 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004650 }
4651 }
4652
4653 @Override
4654 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004655 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004656 != PERMISSION_GRANTED) {
4657 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4658 + Binder.getCallingPid()
4659 + ", uid=" + Binder.getCallingUid()
4660 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4661 Slog.w(TAG, msg);
4662 throw new SecurityException(msg);
4663 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004664 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004665 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004666 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004667 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004668 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004669 }
4670 }
4671
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004672 @Override
4673 public void stopAppSwitches() {
4674 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4675 synchronized (mGlobalLock) {
4676 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4677 mDidAppSwitch = false;
4678 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4679 }
4680 }
4681
4682 @Override
4683 public void resumeAppSwitches() {
4684 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4685 synchronized (mGlobalLock) {
4686 // Note that we don't execute any pending app switches... we will
4687 // let those wait until either the timeout, or the next start
4688 // activity request.
4689 mAppSwitchesAllowedTime = 0;
4690 }
4691 }
4692
4693 void onStartActivitySetDidAppSwitch() {
4694 if (mDidAppSwitch) {
4695 // This is the second allowed switch since we stopped switches, so now just generally
4696 // allow switches. Use case:
4697 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4698 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4699 // anyone to switch again).
4700 mAppSwitchesAllowedTime = 0;
4701 } else {
4702 mDidAppSwitch = true;
4703 }
4704 }
4705
4706 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 boolean shouldDisableNonVrUiLocked() {
4708 return mVrController.shouldDisableNonVrUiLocked();
4709 }
4710
Wale Ogunwale53783742018-09-16 10:21:51 -07004711 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004712 // VR apps are expected to run in a main display. If an app is turning on VR for
4713 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4714 // fullscreen stack before enabling VR Mode.
4715 // TODO: The goal of this code is to keep the VR app on the main display. When the
4716 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4717 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4718 // option would be a better choice here.
4719 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4720 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4721 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004722 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004723 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004724 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004725 }
4726 mH.post(() -> {
4727 if (!mVrController.onVrModeChanged(r)) {
4728 return;
4729 }
4730 synchronized (mGlobalLock) {
4731 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4732 mWindowManager.disableNonVrUi(disableNonVrUi);
4733 if (disableNonVrUi) {
4734 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4735 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004736 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004737 }
4738 }
4739 });
4740 }
4741
Wale Ogunwale53783742018-09-16 10:21:51 -07004742 @Override
4743 public int getPackageScreenCompatMode(String packageName) {
4744 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4745 synchronized (mGlobalLock) {
4746 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4747 }
4748 }
4749
4750 @Override
4751 public void setPackageScreenCompatMode(String packageName, int mode) {
4752 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4753 "setPackageScreenCompatMode");
4754 synchronized (mGlobalLock) {
4755 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4756 }
4757 }
4758
4759 @Override
4760 public boolean getPackageAskScreenCompat(String packageName) {
4761 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4762 synchronized (mGlobalLock) {
4763 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4764 }
4765 }
4766
4767 @Override
4768 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4769 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4770 "setPackageAskScreenCompat");
4771 synchronized (mGlobalLock) {
4772 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4773 }
4774 }
4775
Wale Ogunwale64258362018-10-16 15:13:37 -07004776 public static String relaunchReasonToString(int relaunchReason) {
4777 switch (relaunchReason) {
4778 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4779 return "window_resize";
4780 case RELAUNCH_REASON_FREE_RESIZE:
4781 return "free_resize";
4782 default:
4783 return null;
4784 }
4785 }
4786
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004787 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004788 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004789 }
4790
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 /** Pokes the task persister. */
4792 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4793 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4794 }
4795
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004796 boolean isKeyguardLocked() {
4797 return mKeyguardController.isKeyguardLocked();
4798 }
4799
Garfield Tan01548632018-11-27 10:15:48 -08004800 /**
4801 * Clears launch params for the given package.
4802 * @param packageNames the names of the packages of which the launch params are to be cleared
4803 */
4804 @Override
4805 public void clearLaunchParamsForPackages(List<String> packageNames) {
4806 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4807 "clearLaunchParamsForPackages");
4808 synchronized (mGlobalLock) {
4809 for (int i = 0; i < packageNames.size(); ++i) {
4810 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4811 }
4812 }
4813 }
4814
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004815 /**
4816 * Makes the display with the given id a single task instance display. I.e the display can only
4817 * contain one task.
4818 */
4819 @Override
4820 public void setDisplayToSingleTaskInstance(int displayId) {
4821 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4822 "setDisplayToSingleTaskInstance");
4823 final long origId = Binder.clearCallingIdentity();
4824 try {
4825 final ActivityDisplay display =
4826 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4827 if (display != null) {
4828 display.setDisplayToSingleTaskInstance();
4829 }
4830 } finally {
4831 Binder.restoreCallingIdentity(origId);
4832 }
4833 }
4834
Wale Ogunwale31913b52018-10-13 08:29:31 -07004835 void dumpLastANRLocked(PrintWriter pw) {
4836 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4837 if (mLastANRState == null) {
4838 pw.println(" <no ANR has occurred since boot>");
4839 } else {
4840 pw.println(mLastANRState);
4841 }
4842 }
4843
4844 void dumpLastANRTracesLocked(PrintWriter pw) {
4845 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4846
4847 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4848 if (ArrayUtils.isEmpty(files)) {
4849 pw.println(" <no ANR has occurred since boot>");
4850 return;
4851 }
4852 // Find the latest file.
4853 File latest = null;
4854 for (File f : files) {
4855 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4856 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004857 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004858 }
4859 pw.print("File: ");
4860 pw.print(latest.getName());
4861 pw.println();
4862 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4863 String line;
4864 while ((line = in.readLine()) != null) {
4865 pw.println(line);
4866 }
4867 } catch (IOException e) {
4868 pw.print("Unable to read: ");
4869 pw.print(e);
4870 pw.println();
4871 }
4872 }
4873
4874 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4875 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4876 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4877 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4878 }
4879
4880 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4881 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4882 pw.println(header);
4883
Wale Ogunwaled32da472018-11-16 07:19:28 -08004884 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004885 dumpPackage);
4886 boolean needSep = printedAnything;
4887
4888 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004889 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004890 " ResumedActivity: ");
4891 if (printed) {
4892 printedAnything = true;
4893 needSep = false;
4894 }
4895
4896 if (dumpPackage == null) {
4897 if (needSep) {
4898 pw.println();
4899 }
4900 printedAnything = true;
4901 mStackSupervisor.dump(pw, " ");
4902 }
4903
4904 if (!printedAnything) {
4905 pw.println(" (nothing)");
4906 }
4907 }
4908
4909 void dumpActivityContainersLocked(PrintWriter pw) {
4910 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004911 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004912 pw.println(" ");
4913 }
4914
4915 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4916 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4917 getActivityStartController().dump(pw, "", dumpPackage);
4918 }
4919
4920 /**
4921 * There are three things that cmd can be:
4922 * - a flattened component name that matches an existing activity
4923 * - the cmd arg isn't the flattened component name of an existing activity:
4924 * dump all activity whose component contains the cmd as a substring
4925 * - A hex number of the ActivityRecord object instance.
4926 *
4927 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4928 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4929 */
4930 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4931 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4932 ArrayList<ActivityRecord> activities;
4933
4934 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004935 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004936 dumpFocusedStackOnly);
4937 }
4938
4939 if (activities.size() <= 0) {
4940 return false;
4941 }
4942
4943 String[] newArgs = new String[args.length - opti];
4944 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4945
4946 TaskRecord lastTask = null;
4947 boolean needSep = false;
4948 for (int i = activities.size() - 1; i >= 0; i--) {
4949 ActivityRecord r = activities.get(i);
4950 if (needSep) {
4951 pw.println();
4952 }
4953 needSep = true;
4954 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004955 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004956 if (lastTask != task) {
4957 lastTask = task;
4958 pw.print("TASK "); pw.print(lastTask.affinity);
4959 pw.print(" id="); pw.print(lastTask.taskId);
4960 pw.print(" userId="); pw.println(lastTask.userId);
4961 if (dumpAll) {
4962 lastTask.dump(pw, " ");
4963 }
4964 }
4965 }
4966 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4967 }
4968 return true;
4969 }
4970
4971 /**
4972 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4973 * there is a thread associated with the activity.
4974 */
4975 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4976 final ActivityRecord r, String[] args, boolean dumpAll) {
4977 String innerPrefix = prefix + " ";
4978 synchronized (mGlobalLock) {
4979 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4980 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4981 pw.print(" pid=");
4982 if (r.hasProcess()) pw.println(r.app.getPid());
4983 else pw.println("(not running)");
4984 if (dumpAll) {
4985 r.dump(pw, innerPrefix);
4986 }
4987 }
4988 if (r.attachedToProcess()) {
4989 // flush anything that is already in the PrintWriter since the thread is going
4990 // to write to the file descriptor directly
4991 pw.flush();
4992 try {
4993 TransferPipe tp = new TransferPipe();
4994 try {
4995 r.app.getThread().dumpActivity(tp.getWriteFd(),
4996 r.appToken, innerPrefix, args);
4997 tp.go(fd);
4998 } finally {
4999 tp.kill();
5000 }
5001 } catch (IOException e) {
5002 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5003 } catch (RemoteException e) {
5004 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5005 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005006 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005007 }
5008
sanryhuang498e77e2018-12-06 14:57:01 +08005009 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5010 boolean testPssMode) {
5011 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5012 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5013 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005014 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005015 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5016 st.toString());
5017 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005018 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5019 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5020 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005021 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5022 testPssMode);
5023 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005024 }
5025
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005026 int getCurrentUserId() {
5027 return mAmInternal.getCurrentUserId();
5028 }
5029
5030 private void enforceNotIsolatedCaller(String caller) {
5031 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5032 throw new SecurityException("Isolated process not allowed to call " + caller);
5033 }
5034 }
5035
Wale Ogunwalef6733932018-06-27 05:14:34 -07005036 public Configuration getConfiguration() {
5037 Configuration ci;
5038 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005039 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005040 ci.userSetLocale = false;
5041 }
5042 return ci;
5043 }
5044
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005045 /**
5046 * Current global configuration information. Contains general settings for the entire system,
5047 * also corresponds to the merged configuration of the default display.
5048 */
5049 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005050 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005051 }
5052
5053 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5054 boolean initLocale) {
5055 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5056 }
5057
5058 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5059 boolean initLocale, boolean deferResume) {
5060 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5061 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5062 UserHandle.USER_NULL, deferResume);
5063 }
5064
Wale Ogunwale59507092018-10-29 09:00:30 -07005065 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005066 final long origId = Binder.clearCallingIdentity();
5067 try {
5068 synchronized (mGlobalLock) {
5069 updateConfigurationLocked(values, null, false, true, userId,
5070 false /* deferResume */);
5071 }
5072 } finally {
5073 Binder.restoreCallingIdentity(origId);
5074 }
5075 }
5076
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005077 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5078 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5079 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5080 deferResume, null /* result */);
5081 }
5082
5083 /**
5084 * Do either or both things: (1) change the current configuration, and (2)
5085 * make sure the given activity is running with the (now) current
5086 * configuration. Returns true if the activity has been left running, or
5087 * false if <var>starting</var> is being destroyed to match the new
5088 * configuration.
5089 *
5090 * @param userId is only used when persistent parameter is set to true to persist configuration
5091 * for that particular user
5092 */
5093 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5094 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5095 ActivityTaskManagerService.UpdateConfigurationResult result) {
5096 int changes = 0;
5097 boolean kept = true;
5098
5099 if (mWindowManager != null) {
5100 mWindowManager.deferSurfaceLayout();
5101 }
5102 try {
5103 if (values != null) {
5104 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5105 deferResume);
5106 }
5107
5108 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5109 } finally {
5110 if (mWindowManager != null) {
5111 mWindowManager.continueSurfaceLayout();
5112 }
5113 }
5114
5115 if (result != null) {
5116 result.changes = changes;
5117 result.activityRelaunched = !kept;
5118 }
5119 return kept;
5120 }
5121
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005122 /** Update default (global) configuration and notify listeners about changes. */
5123 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5124 boolean persistent, int userId, boolean deferResume) {
5125 mTempConfig.setTo(getGlobalConfiguration());
5126 final int changes = mTempConfig.updateFrom(values);
5127 if (changes == 0) {
5128 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5129 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5130 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5131 // (even if there are no actual changes) to unfreeze the window.
5132 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5133 return 0;
5134 }
5135
5136 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5137 "Updating global configuration to: " + values);
5138
5139 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5140 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5141 values.colorMode,
5142 values.densityDpi,
5143 values.fontScale,
5144 values.hardKeyboardHidden,
5145 values.keyboard,
5146 values.keyboardHidden,
5147 values.mcc,
5148 values.mnc,
5149 values.navigation,
5150 values.navigationHidden,
5151 values.orientation,
5152 values.screenHeightDp,
5153 values.screenLayout,
5154 values.screenWidthDp,
5155 values.smallestScreenWidthDp,
5156 values.touchscreen,
5157 values.uiMode);
5158
5159
5160 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5161 final LocaleList locales = values.getLocales();
5162 int bestLocaleIndex = 0;
5163 if (locales.size() > 1) {
5164 if (mSupportedSystemLocales == null) {
5165 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5166 }
5167 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5168 }
5169 SystemProperties.set("persist.sys.locale",
5170 locales.get(bestLocaleIndex).toLanguageTag());
5171 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005172
5173 final Message m = PooledLambda.obtainMessage(
5174 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5175 locales.get(bestLocaleIndex));
5176 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177 }
5178
Yunfan Chen75157d72018-07-27 14:47:21 +09005179 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005180
5181 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005182 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005183
5184 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5185 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005186 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005187
5188 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005189 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005190
5191 AttributeCache ac = AttributeCache.instance();
5192 if (ac != null) {
5193 ac.updateConfiguration(mTempConfig);
5194 }
5195
5196 // Make sure all resources in our process are updated right now, so that anyone who is going
5197 // to retrieve resource values after we return will be sure to get the new ones. This is
5198 // especially important during boot, where the first config change needs to guarantee all
5199 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005200 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005201
5202 // We need another copy of global config because we're scheduling some calls instead of
5203 // running them in place. We need to be sure that object we send will be handled unchanged.
5204 final Configuration configCopy = new Configuration(mTempConfig);
5205 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005206 final Message msg = PooledLambda.obtainMessage(
5207 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5208 this, userId, configCopy);
5209 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005210 }
5211
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005212 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5213 for (int i = pidMap.size() - 1; i >= 0; i--) {
5214 final int pid = pidMap.keyAt(i);
5215 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005216 if (DEBUG_CONFIGURATION) {
5217 Slog.v(TAG_CONFIGURATION, "Update process config of "
5218 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005219 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005220 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221 }
5222
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005223 final Message msg = PooledLambda.obtainMessage(
5224 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5225 mAmInternal, changes, initLocale);
5226 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005227
5228 // Override configuration of the default display duplicates global config, so we need to
5229 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005230 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 DEFAULT_DISPLAY);
5232
5233 return changes;
5234 }
5235
5236 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5237 boolean deferResume, int displayId) {
5238 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5239 displayId, null /* result */);
5240 }
5241
5242 /**
5243 * Updates override configuration specific for the selected display. If no config is provided,
5244 * new one will be computed in WM based on current display info.
5245 */
5246 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5247 ActivityRecord starting, boolean deferResume, int displayId,
5248 ActivityTaskManagerService.UpdateConfigurationResult result) {
5249 int changes = 0;
5250 boolean kept = true;
5251
5252 if (mWindowManager != null) {
5253 mWindowManager.deferSurfaceLayout();
5254 }
5255 try {
5256 if (values != null) {
5257 if (displayId == DEFAULT_DISPLAY) {
5258 // Override configuration of the default display duplicates global config, so
5259 // we're calling global config update instead for default display. It will also
5260 // apply the correct override config.
5261 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5262 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5263 } else {
5264 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5265 }
5266 }
5267
5268 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5269 } finally {
5270 if (mWindowManager != null) {
5271 mWindowManager.continueSurfaceLayout();
5272 }
5273 }
5274
5275 if (result != null) {
5276 result.changes = changes;
5277 result.activityRelaunched = !kept;
5278 }
5279 return kept;
5280 }
5281
5282 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5283 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005284 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285 final int changes = mTempConfig.updateFrom(values);
5286 if (changes != 0) {
5287 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5288 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005289 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005290
5291 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5292 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005293 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005294
Wale Ogunwale5c918702018-10-18 11:06:33 -07005295 // Post message to start process to avoid possible deadlock of calling into AMS with
5296 // the ATMS lock held.
5297 final Message msg = PooledLambda.obtainMessage(
5298 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005299 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005300 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005301 }
5302 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005303 return changes;
5304 }
5305
Wale Ogunwalef6733932018-06-27 05:14:34 -07005306 private void updateEventDispatchingLocked(boolean booted) {
5307 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5308 }
5309
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005310 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5311 final ContentResolver resolver = mContext.getContentResolver();
5312 Settings.System.putConfigurationForUser(resolver, config, userId);
5313 }
5314
5315 private void sendLocaleToMountDaemonMsg(Locale l) {
5316 try {
5317 IBinder service = ServiceManager.getService("mount");
5318 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5319 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5320 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5321 } catch (RemoteException e) {
5322 Log.e(TAG, "Error storing locale for decryption UI", e);
5323 }
5324 }
5325
Alison Cichowlas3e340502018-08-07 17:15:01 -04005326 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5327 mStartActivitySources.remove(permissionToken);
5328 mExpiredStartAsCallerTokens.add(permissionToken);
5329 }
5330
5331 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5332 mExpiredStartAsCallerTokens.remove(permissionToken);
5333 }
5334
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005335 boolean isActivityStartsLoggingEnabled() {
5336 return mAmInternal.isActivityStartsLoggingEnabled();
5337 }
5338
Michal Karpinski8596ded2018-11-14 14:43:48 +00005339 boolean isBackgroundActivityStartsEnabled() {
5340 return mAmInternal.isBackgroundActivityStartsEnabled();
5341 }
5342
Ricky Waiaca8a772019-04-04 16:01:06 +01005343 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5344 if (packageName == null) {
5345 return false;
5346 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005347 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5348 }
5349
Wale Ogunwalef6733932018-06-27 05:14:34 -07005350 void enableScreenAfterBoot(boolean booted) {
5351 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5352 SystemClock.uptimeMillis());
5353 mWindowManager.enableScreenAfterBoot();
5354
5355 synchronized (mGlobalLock) {
5356 updateEventDispatchingLocked(booted);
5357 }
5358 }
5359
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005360 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5361 if (r == null || !r.hasProcess()) {
5362 return KEY_DISPATCHING_TIMEOUT_MS;
5363 }
5364 return getInputDispatchingTimeoutLocked(r.app);
5365 }
5366
5367 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005368 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005369 }
5370
Wale Ogunwalef6733932018-06-27 05:14:34 -07005371 /**
5372 * Decide based on the configuration whether we should show the ANR,
5373 * crash, etc dialogs. The idea is that if there is no affordance to
5374 * press the on-screen buttons, or the user experience would be more
5375 * greatly impacted than the crash itself, we shouldn't show the dialog.
5376 *
5377 * A thought: SystemUI might also want to get told about this, the Power
5378 * dialog / global actions also might want different behaviors.
5379 */
5380 private void updateShouldShowDialogsLocked(Configuration config) {
5381 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5382 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5383 && config.navigation == Configuration.NAVIGATION_NONAV);
5384 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5385 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5386 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5387 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5388 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5389 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5390 HIDE_ERROR_DIALOGS, 0) != 0;
5391 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5392 }
5393
5394 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5395 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5396 FONT_SCALE, 1.0f, userId);
5397
5398 synchronized (this) {
5399 if (getGlobalConfiguration().fontScale == scaleFactor) {
5400 return;
5401 }
5402
5403 final Configuration configuration
5404 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5405 configuration.fontScale = scaleFactor;
5406 updatePersistentConfiguration(configuration, userId);
5407 }
5408 }
5409
5410 // Actually is sleeping or shutting down or whatever else in the future
5411 // is an inactive state.
5412 boolean isSleepingOrShuttingDownLocked() {
5413 return isSleepingLocked() || mShuttingDown;
5414 }
5415
5416 boolean isSleepingLocked() {
5417 return mSleeping;
5418 }
5419
Riddle Hsu16567132018-08-16 21:37:47 +08005420 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005421 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005422 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005423 if (task.isActivityTypeStandard()) {
5424 if (mCurAppTimeTracker != r.appTimeTracker) {
5425 // We are switching app tracking. Complete the current one.
5426 if (mCurAppTimeTracker != null) {
5427 mCurAppTimeTracker.stop();
5428 mH.obtainMessage(
5429 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005430 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005431 mCurAppTimeTracker = null;
5432 }
5433 if (r.appTimeTracker != null) {
5434 mCurAppTimeTracker = r.appTimeTracker;
5435 startTimeTrackingFocusedActivityLocked();
5436 }
5437 } else {
5438 startTimeTrackingFocusedActivityLocked();
5439 }
5440 } else {
5441 r.appTimeTracker = null;
5442 }
5443 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5444 // TODO: Probably not, because we don't want to resume voice on switching
5445 // back to this activity
5446 if (task.voiceInteractor != null) {
5447 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5448 } else {
5449 finishRunningVoiceLocked();
5450
5451 if (mLastResumedActivity != null) {
5452 final IVoiceInteractionSession session;
5453
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005454 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 if (lastResumedActivityTask != null
5456 && lastResumedActivityTask.voiceSession != null) {
5457 session = lastResumedActivityTask.voiceSession;
5458 } else {
5459 session = mLastResumedActivity.voiceSession;
5460 }
5461
5462 if (session != null) {
5463 // We had been in a voice interaction session, but now focused has
5464 // move to something different. Just finish the session, we can't
5465 // return to it and retain the proper state and synchronization with
5466 // the voice interaction service.
5467 finishVoiceTask(session);
5468 }
5469 }
5470 }
5471
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005472 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5473 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005474 }
5475 updateResumedAppTrace(r);
5476 mLastResumedActivity = r;
5477
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005478 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005479
5480 applyUpdateLockStateLocked(r);
5481 applyUpdateVrModeLocked(r);
5482
5483 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005484 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005485 r == null ? "NULL" : r.shortComponentName,
5486 reason);
5487 }
5488
5489 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5490 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005491 final ActivityTaskManagerInternal.SleepToken token =
5492 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005493 updateSleepIfNeededLocked();
5494 return token;
5495 }
5496 }
5497
5498 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005499 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 final boolean wasSleeping = mSleeping;
5501 boolean updateOomAdj = false;
5502
5503 if (!shouldSleep) {
5504 // If wasSleeping is true, we need to wake up activity manager state from when
5505 // we started sleeping. In either case, we need to apply the sleep tokens, which
5506 // will wake up stacks or put them to sleep as appropriate.
5507 if (wasSleeping) {
5508 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005509 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5510 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511 startTimeTrackingFocusedActivityLocked();
5512 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5513 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5514 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005515 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005516 if (wasSleeping) {
5517 updateOomAdj = true;
5518 }
5519 } else if (!mSleeping && shouldSleep) {
5520 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005521 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5522 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005523 if (mCurAppTimeTracker != null) {
5524 mCurAppTimeTracker.stop();
5525 }
5526 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5527 mStackSupervisor.goingToSleepLocked();
5528 updateResumedAppTrace(null /* resumed */);
5529 updateOomAdj = true;
5530 }
5531 if (updateOomAdj) {
5532 mH.post(mAmInternal::updateOomAdj);
5533 }
5534 }
5535
5536 void updateOomAdj() {
5537 mH.post(mAmInternal::updateOomAdj);
5538 }
5539
Wale Ogunwale53783742018-09-16 10:21:51 -07005540 void updateCpuStats() {
5541 mH.post(mAmInternal::updateCpuStats);
5542 }
5543
Hui Yu03d12402018-12-06 18:00:37 -08005544 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5545 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005546 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5547 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005548 mH.sendMessage(m);
5549 }
5550
Hui Yu03d12402018-12-06 18:00:37 -08005551 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005552 ComponentName taskRoot = null;
5553 final TaskRecord task = activity.getTaskRecord();
5554 if (task != null) {
5555 final ActivityRecord rootActivity = task.getRootActivity();
5556 if (rootActivity != null) {
5557 taskRoot = rootActivity.mActivityComponent;
5558 }
5559 }
5560
Hui Yu03d12402018-12-06 18:00:37 -08005561 final Message m = PooledLambda.obtainMessage(
5562 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005563 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005564 mH.sendMessage(m);
5565 }
5566
Wale Ogunwale53783742018-09-16 10:21:51 -07005567 void setBooting(boolean booting) {
5568 mAmInternal.setBooting(booting);
5569 }
5570
5571 boolean isBooting() {
5572 return mAmInternal.isBooting();
5573 }
5574
5575 void setBooted(boolean booted) {
5576 mAmInternal.setBooted(booted);
5577 }
5578
5579 boolean isBooted() {
5580 return mAmInternal.isBooted();
5581 }
5582
5583 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5584 mH.post(() -> {
5585 if (finishBooting) {
5586 mAmInternal.finishBooting();
5587 }
5588 if (enableScreen) {
5589 mInternal.enableScreenAfterBoot(isBooted());
5590 }
5591 });
5592 }
5593
5594 void setHeavyWeightProcess(ActivityRecord root) {
5595 mHeavyWeightProcess = root.app;
5596 final Message m = PooledLambda.obtainMessage(
5597 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005598 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005599 mH.sendMessage(m);
5600 }
5601
5602 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5603 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5604 return;
5605 }
5606
5607 mHeavyWeightProcess = null;
5608 final Message m = PooledLambda.obtainMessage(
5609 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5610 proc.mUserId);
5611 mH.sendMessage(m);
5612 }
5613
5614 private void cancelHeavyWeightProcessNotification(int userId) {
5615 final INotificationManager inm = NotificationManager.getService();
5616 if (inm == null) {
5617 return;
5618 }
5619 try {
5620 inm.cancelNotificationWithTag("android", null,
5621 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5622 } catch (RuntimeException e) {
5623 Slog.w(TAG, "Error canceling notification for service", e);
5624 } catch (RemoteException e) {
5625 }
5626
5627 }
5628
5629 private void postHeavyWeightProcessNotification(
5630 WindowProcessController proc, Intent intent, int userId) {
5631 if (proc == null) {
5632 return;
5633 }
5634
5635 final INotificationManager inm = NotificationManager.getService();
5636 if (inm == null) {
5637 return;
5638 }
5639
5640 try {
5641 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5642 String text = mContext.getString(R.string.heavy_weight_notification,
5643 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5644 Notification notification =
5645 new Notification.Builder(context,
5646 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5647 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5648 .setWhen(0)
5649 .setOngoing(true)
5650 .setTicker(text)
5651 .setColor(mContext.getColor(
5652 com.android.internal.R.color.system_notification_accent_color))
5653 .setContentTitle(text)
5654 .setContentText(
5655 mContext.getText(R.string.heavy_weight_notification_detail))
5656 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5657 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5658 new UserHandle(userId)))
5659 .build();
5660 try {
5661 inm.enqueueNotificationWithTag("android", "android", null,
5662 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5663 } catch (RuntimeException e) {
5664 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5665 } catch (RemoteException e) {
5666 }
5667 } catch (PackageManager.NameNotFoundException e) {
5668 Slog.w(TAG, "Unable to create context for heavy notification", e);
5669 }
5670
5671 }
5672
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005673 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5674 IBinder token, String resultWho, int requestCode, Intent[] intents,
5675 String[] resolvedTypes, int flags, Bundle bOptions) {
5676
5677 ActivityRecord activity = null;
5678 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5679 activity = ActivityRecord.isInStackLocked(token);
5680 if (activity == null) {
5681 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5682 return null;
5683 }
5684 if (activity.finishing) {
5685 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5686 return null;
5687 }
5688 }
5689
5690 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5691 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5692 bOptions);
5693 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5694 if (noCreate) {
5695 return rec;
5696 }
5697 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5698 if (activity.pendingResults == null) {
5699 activity.pendingResults = new HashSet<>();
5700 }
5701 activity.pendingResults.add(rec.ref);
5702 }
5703 return rec;
5704 }
5705
Andrii Kulian52d255c2018-07-13 11:32:19 -07005706 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005707 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005708 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005709 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5710 mCurAppTimeTracker.start(resumedActivity.packageName);
5711 }
5712 }
5713
5714 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5715 if (mTracedResumedActivity != null) {
5716 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5717 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5718 }
5719 if (resumed != null) {
5720 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5721 constructResumedTraceName(resumed.packageName), 0);
5722 }
5723 mTracedResumedActivity = resumed;
5724 }
5725
5726 private String constructResumedTraceName(String packageName) {
5727 return "focused app: " + packageName;
5728 }
5729
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005730 /** Applies latest configuration and/or visibility updates if needed. */
5731 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5732 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005733 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005734 // mainStack is null during startup.
5735 if (mainStack != null) {
5736 if (changes != 0 && starting == null) {
5737 // If the configuration changed, and the caller is not already
5738 // in the process of starting an activity, then find the top
5739 // activity to check if its configuration needs to change.
5740 starting = mainStack.topRunningActivityLocked();
5741 }
5742
5743 if (starting != null) {
5744 kept = starting.ensureActivityConfiguration(changes,
5745 false /* preserveWindow */);
5746 // And we need to make sure at this point that all other activities
5747 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005748 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005749 !PRESERVE_WINDOWS);
5750 }
5751 }
5752
5753 return kept;
5754 }
5755
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005756 void scheduleAppGcsLocked() {
5757 mH.post(() -> mAmInternal.scheduleAppGcs());
5758 }
5759
Wale Ogunwale53783742018-09-16 10:21:51 -07005760 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5761 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5762 }
5763
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005764 /**
5765 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5766 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5767 * on demand.
5768 */
5769 IPackageManager getPackageManager() {
5770 return AppGlobals.getPackageManager();
5771 }
5772
5773 PackageManagerInternal getPackageManagerInternalLocked() {
5774 if (mPmInternal == null) {
5775 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5776 }
5777 return mPmInternal;
5778 }
5779
Wale Ogunwale008163e2018-07-23 23:11:08 -07005780 AppWarnings getAppWarningsLocked() {
5781 return mAppWarnings;
5782 }
5783
Wale Ogunwale214f3482018-10-04 11:00:47 -07005784 Intent getHomeIntent() {
5785 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5786 intent.setComponent(mTopComponent);
5787 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5788 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5789 intent.addCategory(Intent.CATEGORY_HOME);
5790 }
5791 return intent;
5792 }
5793
Chilun2ef71f72018-11-16 17:57:15 +08005794 /**
5795 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5796 * activities.
5797 *
5798 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5799 * component defined in config_secondaryHomeComponent.
5800 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5801 */
5802 Intent getSecondaryHomeIntent(String preferredPackage) {
5803 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5804 if (preferredPackage == null) {
5805 // Using the component stored in config if no package name.
5806 final String secondaryHomeComponent = mContext.getResources().getString(
5807 com.android.internal.R.string.config_secondaryHomeComponent);
5808 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5809 } else {
5810 intent.setPackage(preferredPackage);
5811 }
5812 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5813 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5814 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5815 }
5816 return intent;
5817 }
5818
Wale Ogunwale214f3482018-10-04 11:00:47 -07005819 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5820 if (info == null) return null;
5821 ApplicationInfo newInfo = new ApplicationInfo(info);
5822 newInfo.initForUser(userId);
5823 return newInfo;
5824 }
5825
Wale Ogunwale9c103022018-10-18 07:44:54 -07005826 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005827 if (uid == SYSTEM_UID) {
5828 // The system gets to run in any process. If there are multiple processes with the same
5829 // uid, just pick the first (this should never happen).
5830 final SparseArray<WindowProcessController> procs =
5831 mProcessNames.getMap().get(processName);
5832 if (procs == null) return null;
5833 final int procCount = procs.size();
5834 for (int i = 0; i < procCount; i++) {
5835 final int procUid = procs.keyAt(i);
5836 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5837 // Don't use an app process or different user process for system component.
5838 continue;
5839 }
5840 return procs.valueAt(i);
5841 }
5842 }
5843
5844 return mProcessNames.get(processName, uid);
5845 }
5846
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005847 WindowProcessController getProcessController(IApplicationThread thread) {
5848 if (thread == null) {
5849 return null;
5850 }
5851
5852 final IBinder threadBinder = thread.asBinder();
5853 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5854 for (int i = pmap.size()-1; i >= 0; i--) {
5855 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5856 for (int j = procs.size() - 1; j >= 0; j--) {
5857 final WindowProcessController proc = procs.valueAt(j);
5858 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5859 return proc;
5860 }
5861 }
5862 }
5863
5864 return null;
5865 }
5866
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005867 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005868 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005869 if (proc == null) return null;
5870 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5871 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005872 }
5873 return null;
5874 }
5875
Riddle Hsua0536432019-02-16 00:38:59 +08005876 int getUidState(int uid) {
5877 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005878 }
5879
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005880 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005881 // A uid is considered to be foreground if it has a visible non-toast window.
5882 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005883 }
5884
Ricky Wai96f5c352019-04-10 18:40:17 +01005885 boolean isDeviceOwner(int uid) {
5886 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005887 }
5888
Ricky Wai96f5c352019-04-10 18:40:17 +01005889 void setDeviceOwnerUid(int uid) {
5890 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005891 }
5892
Wale Ogunwale9de19442018-10-18 19:05:03 -07005893 /**
5894 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5895 * the whitelist
5896 */
5897 String getPendingTempWhitelistTagForUidLocked(int uid) {
5898 return mPendingTempWhitelist.get(uid);
5899 }
5900
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005901 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5902 if (true || Build.IS_USER) {
5903 return;
5904 }
5905
5906 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5907 StrictMode.allowThreadDiskWrites();
5908 try {
5909 File tracesDir = new File("/data/anr");
5910 File tracesFile = null;
5911 try {
5912 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5913
5914 StringBuilder sb = new StringBuilder();
5915 Time tobj = new Time();
5916 tobj.set(System.currentTimeMillis());
5917 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5918 sb.append(": ");
5919 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5920 sb.append(" since ");
5921 sb.append(msg);
5922 FileOutputStream fos = new FileOutputStream(tracesFile);
5923 fos.write(sb.toString().getBytes());
5924 if (app == null) {
5925 fos.write("\n*** No application process!".getBytes());
5926 }
5927 fos.close();
5928 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5929 } catch (IOException e) {
5930 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5931 return;
5932 }
5933
5934 if (app != null && app.getPid() > 0) {
5935 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5936 firstPids.add(app.getPid());
5937 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5938 }
5939
5940 File lastTracesFile = null;
5941 File curTracesFile = null;
5942 for (int i=9; i>=0; i--) {
5943 String name = String.format(Locale.US, "slow%02d.txt", i);
5944 curTracesFile = new File(tracesDir, name);
5945 if (curTracesFile.exists()) {
5946 if (lastTracesFile != null) {
5947 curTracesFile.renameTo(lastTracesFile);
5948 } else {
5949 curTracesFile.delete();
5950 }
5951 }
5952 lastTracesFile = curTracesFile;
5953 }
5954 tracesFile.renameTo(curTracesFile);
5955 } finally {
5956 StrictMode.setThreadPolicy(oldPolicy);
5957 }
5958 }
5959
Michal Karpinskida34cd42019-04-02 19:46:52 +01005960 boolean isAssociatedCompanionApp(int userId, int uid) {
5961 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5962 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005963 return false;
5964 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005965 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005966 }
5967
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005968 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005969 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005970
5971
Wale Ogunwale98875612018-10-12 07:53:02 -07005972 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5973 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005974
Riddle Hsud93a6c42018-11-29 21:50:06 +08005975 H(Looper looper) {
5976 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005977 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005978
5979 @Override
5980 public void handleMessage(Message msg) {
5981 switch (msg.what) {
5982 case REPORT_TIME_TRACKER_MSG: {
5983 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5984 tracker.deliverResult(mContext);
5985 } break;
5986 }
5987 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005988 }
5989
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005990 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005991 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005992
5993 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005994 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005995 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005996
5997 @Override
5998 public void handleMessage(Message msg) {
5999 switch (msg.what) {
6000 case DISMISS_DIALOG_UI_MSG: {
6001 final Dialog d = (Dialog) msg.obj;
6002 d.dismiss();
6003 break;
6004 }
6005 }
6006 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006007 }
6008
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006009 final class LocalService extends ActivityTaskManagerInternal {
6010 @Override
6011 public SleepToken acquireSleepToken(String tag, int displayId) {
6012 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006013 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006014 }
6015
6016 @Override
6017 public ComponentName getHomeActivityForUser(int userId) {
6018 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006019 final ActivityRecord homeActivity =
6020 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006021 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006022 }
6023 }
6024
6025 @Override
6026 public void onLocalVoiceInteractionStarted(IBinder activity,
6027 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6028 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006029 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006030 }
6031 }
6032
6033 @Override
6034 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6035 synchronized (mGlobalLock) {
6036 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6037 reasons, timestamp);
6038 }
6039 }
6040
6041 @Override
6042 public void notifyAppTransitionFinished() {
6043 synchronized (mGlobalLock) {
6044 mStackSupervisor.notifyAppTransitionDone();
6045 }
6046 }
6047
6048 @Override
6049 public void notifyAppTransitionCancelled() {
6050 synchronized (mGlobalLock) {
6051 mStackSupervisor.notifyAppTransitionDone();
6052 }
6053 }
6054
6055 @Override
6056 public List<IBinder> getTopVisibleActivities() {
6057 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006058 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006059 }
6060 }
6061
6062 @Override
6063 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6064 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006065 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006066 }
6067 }
6068
6069 @Override
6070 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6071 Bundle bOptions) {
6072 Preconditions.checkNotNull(intents, "intents");
6073 final String[] resolvedTypes = new String[intents.length];
6074
6075 // UID of the package on user userId.
6076 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6077 // packageUid may not be initialized.
6078 int packageUid = 0;
6079 final long ident = Binder.clearCallingIdentity();
6080
6081 try {
6082 for (int i = 0; i < intents.length; i++) {
6083 resolvedTypes[i] =
6084 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6085 }
6086
6087 packageUid = AppGlobals.getPackageManager().getPackageUid(
6088 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6089 } catch (RemoteException e) {
6090 // Shouldn't happen.
6091 } finally {
6092 Binder.restoreCallingIdentity(ident);
6093 }
6094
Riddle Hsu591bf612019-02-14 17:55:31 +08006095 return getActivityStartController().startActivitiesInPackage(
6096 packageUid, packageName,
6097 intents, resolvedTypes, null /* resultTo */,
6098 SafeActivityOptions.fromBundle(bOptions), userId,
6099 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6100 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006101 }
6102
6103 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006104 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6105 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6106 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6107 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006108 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006109 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006110 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6111 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6112 userId, validateIncomingUser, originatingPendingIntent,
6113 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006114 }
6115 }
6116
6117 @Override
6118 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6119 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6120 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6121 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006122 PendingIntentRecord originatingPendingIntent,
6123 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006124 synchronized (mGlobalLock) {
6125 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6126 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6127 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006128 validateIncomingUser, originatingPendingIntent,
6129 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006130 }
6131 }
6132
6133 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006134 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6135 Intent intent, Bundle options, int userId) {
6136 return ActivityTaskManagerService.this.startActivityAsUser(
6137 caller, callerPacakge, intent,
6138 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6139 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6140 false /*validateIncomingUser*/);
6141 }
6142
6143 @Override
lumark588a3e82018-07-20 18:53:54 +08006144 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006145 synchronized (mGlobalLock) {
6146
6147 // We might change the visibilities here, so prepare an empty app transition which
6148 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006149 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006150 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006151 if (activityDisplay == null) {
6152 return;
6153 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006154 final DisplayContent dc = activityDisplay.mDisplayContent;
6155 final boolean wasTransitionSet =
6156 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006157 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006158 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006159 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006160 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161
6162 // If there was a transition set already we don't want to interfere with it as we
6163 // might be starting it too early.
6164 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006165 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006166 }
6167 }
6168 if (callback != null) {
6169 callback.run();
6170 }
6171 }
6172
6173 @Override
6174 public void notifyKeyguardTrustedChanged() {
6175 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006176 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006177 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178 }
6179 }
6180 }
6181
6182 /**
6183 * Called after virtual display Id is updated by
6184 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6185 * {@param vrVr2dDisplayId}.
6186 */
6187 @Override
6188 public void setVr2dDisplayId(int vr2dDisplayId) {
6189 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6190 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006191 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006192 }
6193 }
6194
6195 @Override
6196 public void setFocusedActivity(IBinder token) {
6197 synchronized (mGlobalLock) {
6198 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6199 if (r == null) {
6200 throw new IllegalArgumentException(
6201 "setFocusedActivity: No activity record matching token=" + token);
6202 }
Louis Chang19443452018-10-09 12:10:21 +08006203 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006204 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 }
6206 }
6207 }
6208
6209 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006210 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006211 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006212 }
6213
6214 @Override
6215 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006216 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006217 }
6218
6219 @Override
6220 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006221 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 }
6223
6224 @Override
6225 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6226 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6227 }
6228
6229 @Override
6230 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006231 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006232 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006233
6234 @Override
6235 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6236 synchronized (mGlobalLock) {
6237 mActiveVoiceInteractionServiceComponent = component;
6238 }
6239 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006240
6241 @Override
6242 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6243 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6244 return;
6245 }
6246 synchronized (mGlobalLock) {
6247 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6248 if (types == null) {
6249 if (uid < 0) {
6250 return;
6251 }
6252 types = new ArrayMap<>();
6253 mAllowAppSwitchUids.put(userId, types);
6254 }
6255 if (uid < 0) {
6256 types.remove(type);
6257 } else {
6258 types.put(type, uid);
6259 }
6260 }
6261 }
6262
6263 @Override
6264 public void onUserStopped(int userId) {
6265 synchronized (mGlobalLock) {
6266 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6267 mAllowAppSwitchUids.remove(userId);
6268 }
6269 }
6270
6271 @Override
6272 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6273 synchronized (mGlobalLock) {
6274 return ActivityTaskManagerService.this.isGetTasksAllowed(
6275 caller, callingPid, callingUid);
6276 }
6277 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006278
Riddle Hsua0536432019-02-16 00:38:59 +08006279 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006280 @Override
6281 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006282 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006283 mProcessNames.put(proc.mName, proc.mUid, proc);
6284 }
6285 }
6286
Riddle Hsua0536432019-02-16 00:38:59 +08006287 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006288 @Override
6289 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006290 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006291 mProcessNames.remove(name, uid);
6292 }
6293 }
6294
Riddle Hsua0536432019-02-16 00:38:59 +08006295 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006296 @Override
6297 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006298 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006299 if (proc == mHomeProcess) {
6300 mHomeProcess = null;
6301 }
6302 if (proc == mPreviousProcess) {
6303 mPreviousProcess = null;
6304 }
6305 }
6306 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006307
Riddle Hsua0536432019-02-16 00:38:59 +08006308 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006309 @Override
6310 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006311 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006312 return mTopProcessState;
6313 }
6314 }
6315
Riddle Hsua0536432019-02-16 00:38:59 +08006316 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006317 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006318 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006319 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006320 return proc == mHeavyWeightProcess;
6321 }
6322 }
6323
Riddle Hsua0536432019-02-16 00:38:59 +08006324 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006325 @Override
6326 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006327 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006328 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6329 }
6330 }
6331
6332 @Override
6333 public void finishHeavyWeightApp() {
6334 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006335 if (mHeavyWeightProcess != null) {
6336 mHeavyWeightProcess.finishActivities();
6337 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006338 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6339 mHeavyWeightProcess);
6340 }
6341 }
6342
Riddle Hsua0536432019-02-16 00:38:59 +08006343 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006344 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006345 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006346 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006347 return isSleepingLocked();
6348 }
6349 }
6350
6351 @Override
6352 public boolean isShuttingDown() {
6353 synchronized (mGlobalLock) {
6354 return mShuttingDown;
6355 }
6356 }
6357
6358 @Override
6359 public boolean shuttingDown(boolean booted, int timeout) {
6360 synchronized (mGlobalLock) {
6361 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006362 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006363 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006364 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006365 return mStackSupervisor.shutdownLocked(timeout);
6366 }
6367 }
6368
6369 @Override
6370 public void enableScreenAfterBoot(boolean booted) {
6371 synchronized (mGlobalLock) {
6372 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6373 SystemClock.uptimeMillis());
6374 mWindowManager.enableScreenAfterBoot();
6375 updateEventDispatchingLocked(booted);
6376 }
6377 }
6378
6379 @Override
6380 public boolean showStrictModeViolationDialog() {
6381 synchronized (mGlobalLock) {
6382 return mShowDialogs && !mSleeping && !mShuttingDown;
6383 }
6384 }
6385
6386 @Override
6387 public void showSystemReadyErrorDialogsIfNeeded() {
6388 synchronized (mGlobalLock) {
6389 try {
6390 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6391 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6392 + " data partition or your device will be unstable.");
6393 mUiHandler.post(() -> {
6394 if (mShowDialogs) {
6395 AlertDialog d = new BaseErrorDialog(mUiContext);
6396 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6397 d.setCancelable(false);
6398 d.setTitle(mUiContext.getText(R.string.android_system_label));
6399 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6400 d.setButton(DialogInterface.BUTTON_POSITIVE,
6401 mUiContext.getText(R.string.ok),
6402 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6403 d.show();
6404 }
6405 });
6406 }
6407 } catch (RemoteException e) {
6408 }
6409
6410 if (!Build.isBuildConsistent()) {
6411 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6412 mUiHandler.post(() -> {
6413 if (mShowDialogs) {
6414 AlertDialog d = new BaseErrorDialog(mUiContext);
6415 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6416 d.setCancelable(false);
6417 d.setTitle(mUiContext.getText(R.string.android_system_label));
6418 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6419 d.setButton(DialogInterface.BUTTON_POSITIVE,
6420 mUiContext.getText(R.string.ok),
6421 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6422 d.show();
6423 }
6424 });
6425 }
6426 }
6427 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006428
6429 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006430 public void onProcessMapped(int pid, WindowProcessController proc) {
6431 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006432 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006433 }
6434 }
6435
6436 @Override
6437 public void onProcessUnMapped(int pid) {
6438 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006439 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006440 }
6441 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006442
6443 @Override
6444 public void onPackageDataCleared(String name) {
6445 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006446 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006447 mAppWarnings.onPackageDataCleared(name);
6448 }
6449 }
6450
6451 @Override
6452 public void onPackageUninstalled(String name) {
6453 synchronized (mGlobalLock) {
6454 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006455 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006456 }
6457 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006458
6459 @Override
6460 public void onPackageAdded(String name, boolean replacing) {
6461 synchronized (mGlobalLock) {
6462 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6463 }
6464 }
6465
6466 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006467 public void onPackageReplaced(ApplicationInfo aInfo) {
6468 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006469 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006470 }
6471 }
6472
6473 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006474 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6475 synchronized (mGlobalLock) {
6476 return compatibilityInfoForPackageLocked(ai);
6477 }
6478 }
6479
Yunfan Chen75157d72018-07-27 14:47:21 +09006480 /**
6481 * Set the corresponding display information for the process global configuration. To be
6482 * called when we need to show IME on a different display.
6483 *
6484 * @param pid The process id associated with the IME window.
6485 * @param displayId The ID of the display showing the IME.
6486 */
6487 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006488 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006489 // Don't update process-level configuration for Multi-Client IME process since other
6490 // IMEs on other displays will also receive this configuration change due to IME
6491 // services use the same application config/context.
6492 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006493
Yunfan Chen75157d72018-07-27 14:47:21 +09006494 if (pid == MY_PID || pid < 0) {
6495 if (DEBUG_CONFIGURATION) {
6496 Slog.w(TAG,
6497 "Trying to update display configuration for system/invalid process.");
6498 }
6499 return;
6500 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006501 synchronized (mGlobalLock) {
6502 final ActivityDisplay activityDisplay =
6503 mRootActivityContainer.getActivityDisplay(displayId);
6504 if (activityDisplay == null) {
6505 // Call might come when display is not yet added or has been removed.
6506 if (DEBUG_CONFIGURATION) {
6507 Slog.w(TAG, "Trying to update display configuration for non-existing "
6508 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006509 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006510 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006511 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006512 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006513 if (process == null) {
6514 if (DEBUG_CONFIGURATION) {
6515 Slog.w(TAG, "Trying to update display configuration for invalid "
6516 + "process, pid=" + pid);
6517 }
6518 return;
6519 }
6520 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6521 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006522 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006523
6524 @Override
6525 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6526 int requestCode, int resultCode, Intent data) {
6527 synchronized (mGlobalLock) {
6528 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006529 if (r != null && r.getActivityStack() != null) {
6530 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6531 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006532 }
6533 }
6534 }
6535
6536 @Override
6537 public void clearPendingResultForActivity(IBinder activityToken,
6538 WeakReference<PendingIntentRecord> pir) {
6539 synchronized (mGlobalLock) {
6540 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6541 if (r != null && r.pendingResults != null) {
6542 r.pendingResults.remove(pir);
6543 }
6544 }
6545 }
6546
6547 @Override
6548 public IIntentSender getIntentSender(int type, String packageName,
6549 int callingUid, int userId, IBinder token, String resultWho,
6550 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6551 Bundle bOptions) {
6552 synchronized (mGlobalLock) {
6553 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6554 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6555 }
6556 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006557
6558 @Override
6559 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6560 synchronized (mGlobalLock) {
6561 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6562 if (r == null) {
6563 return null;
6564 }
6565 if (r.mServiceConnectionsHolder == null) {
6566 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6567 ActivityTaskManagerService.this, r);
6568 }
6569
6570 return r.mServiceConnectionsHolder;
6571 }
6572 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006573
6574 @Override
6575 public Intent getHomeIntent() {
6576 synchronized (mGlobalLock) {
6577 return ActivityTaskManagerService.this.getHomeIntent();
6578 }
6579 }
6580
6581 @Override
6582 public boolean startHomeActivity(int userId, String reason) {
6583 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006584 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006585 }
6586 }
6587
6588 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006589 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006590 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006591 synchronized (mGlobalLock) {
6592 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006593 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006594 }
Chilun8b1f1be2019-03-13 17:14:36 +08006595 }
6596
6597 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006598 public boolean startHomeOnAllDisplays(int userId, String reason) {
6599 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006600 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006601 }
6602 }
6603
Riddle Hsua0536432019-02-16 00:38:59 +08006604 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006605 @Override
6606 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006607 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006608 if (mFactoryTest == FACTORY_TEST_OFF) {
6609 return false;
6610 }
6611 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6612 && wpc.mName.equals(mTopComponent.getPackageName())) {
6613 return true;
6614 }
6615 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6616 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6617 }
6618 }
6619
6620 @Override
6621 public void updateTopComponentForFactoryTest() {
6622 synchronized (mGlobalLock) {
6623 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6624 return;
6625 }
6626 final ResolveInfo ri = mContext.getPackageManager()
6627 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6628 final CharSequence errorMsg;
6629 if (ri != null) {
6630 final ActivityInfo ai = ri.activityInfo;
6631 final ApplicationInfo app = ai.applicationInfo;
6632 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6633 mTopAction = Intent.ACTION_FACTORY_TEST;
6634 mTopData = null;
6635 mTopComponent = new ComponentName(app.packageName, ai.name);
6636 errorMsg = null;
6637 } else {
6638 errorMsg = mContext.getResources().getText(
6639 com.android.internal.R.string.factorytest_not_system);
6640 }
6641 } else {
6642 errorMsg = mContext.getResources().getText(
6643 com.android.internal.R.string.factorytest_no_action);
6644 }
6645 if (errorMsg == null) {
6646 return;
6647 }
6648
6649 mTopAction = null;
6650 mTopData = null;
6651 mTopComponent = null;
6652 mUiHandler.post(() -> {
6653 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6654 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006655 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006656 });
6657 }
6658 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006659
Riddle Hsua0536432019-02-16 00:38:59 +08006660 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006661 @Override
6662 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6663 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006664 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006665 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006666 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006667
6668 wpc.clearRecentTasks();
6669 wpc.clearActivities();
6670
6671 if (wpc.isInstrumenting()) {
6672 finishInstrumentationCallback.run();
6673 }
6674
Jorim Jaggid0752812018-10-16 16:07:20 +02006675 if (!restarting && hasVisibleActivities) {
6676 mWindowManager.deferSurfaceLayout();
6677 try {
6678 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6679 // If there was nothing to resume, and we are not already restarting
6680 // this process, but there is a visible activity that is hosted by the
6681 // process...then make sure all visible activities are running, taking
6682 // care of restarting this process.
6683 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6684 !PRESERVE_WINDOWS);
6685 }
6686 } finally {
6687 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006688 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006689 }
6690 }
6691 }
6692
6693 @Override
6694 public void closeSystemDialogs(String reason) {
6695 enforceNotIsolatedCaller("closeSystemDialogs");
6696
6697 final int pid = Binder.getCallingPid();
6698 final int uid = Binder.getCallingUid();
6699 final long origId = Binder.clearCallingIdentity();
6700 try {
6701 synchronized (mGlobalLock) {
6702 // Only allow this from foreground processes, so that background
6703 // applications can't abuse it to prevent system UI from being shown.
6704 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006705 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 if (!proc.isPerceptible()) {
6707 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6708 + " from background process " + proc);
6709 return;
6710 }
6711 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006712 mWindowManager.closeSystemDialogs(reason);
6713
Wale Ogunwaled32da472018-11-16 07:19:28 -08006714 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006715 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006716 // Call into AM outside the synchronized block.
6717 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006718 } finally {
6719 Binder.restoreCallingIdentity(origId);
6720 }
6721 }
6722
6723 @Override
6724 public void cleanupDisabledPackageComponents(
6725 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6726 synchronized (mGlobalLock) {
6727 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006728 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006729 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006730 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 mStackSupervisor.scheduleIdleLocked();
6732 }
6733
6734 // Clean-up disabled tasks
6735 getRecentTasks().cleanupDisabledPackageTasksLocked(
6736 packageName, disabledClasses, userId);
6737 }
6738 }
6739
6740 @Override
6741 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6742 int userId) {
6743 synchronized (mGlobalLock) {
6744
6745 boolean didSomething =
6746 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006747 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006748 null, doit, evenPersistent, userId);
6749 return didSomething;
6750 }
6751 }
6752
6753 @Override
6754 public void resumeTopActivities(boolean scheduleIdle) {
6755 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006756 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006757 if (scheduleIdle) {
6758 mStackSupervisor.scheduleIdleLocked();
6759 }
6760 }
6761 }
6762
Riddle Hsua0536432019-02-16 00:38:59 +08006763 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006764 @Override
6765 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006766 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6768 }
6769 }
6770
Riddle Hsua0536432019-02-16 00:38:59 +08006771 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006772 @Override
6773 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006774 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006775 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006776 }
6777 }
6778
6779 @Override
6780 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6781 try {
6782 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6783 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6784 }
6785 } catch (RemoteException ex) {
6786 throw new SecurityException("Fail to check is caller a privileged app", ex);
6787 }
6788
6789 synchronized (mGlobalLock) {
6790 final long ident = Binder.clearCallingIdentity();
6791 try {
6792 if (mAmInternal.shouldConfirmCredentials(userId)) {
6793 if (mKeyguardController.isKeyguardLocked()) {
6794 // Showing launcher to avoid user entering credential twice.
6795 startHomeActivity(currentUserId, "notifyLockedProfile");
6796 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006797 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798 }
6799 } finally {
6800 Binder.restoreCallingIdentity(ident);
6801 }
6802 }
6803 }
6804
6805 @Override
6806 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6807 mAmInternal.enforceCallingPermission(
6808 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6809
6810 synchronized (mGlobalLock) {
6811 final long ident = Binder.clearCallingIdentity();
6812 try {
6813 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6814 FLAG_ACTIVITY_TASK_ON_HOME);
6815 ActivityOptions activityOptions = options != null
6816 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006817 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006818 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006819 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006820 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006821 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006822 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6823 UserHandle.CURRENT);
6824 } finally {
6825 Binder.restoreCallingIdentity(ident);
6826 }
6827 }
6828 }
6829
6830 @Override
6831 public void writeActivitiesToProto(ProtoOutputStream proto) {
6832 synchronized (mGlobalLock) {
6833 // The output proto of "activity --proto activities"
6834 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006835 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006836 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6837 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 }
6839 }
6840
6841 @Override
6842 public void saveANRState(String reason) {
6843 synchronized (mGlobalLock) {
6844 final StringWriter sw = new StringWriter();
6845 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6846 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6847 if (reason != null) {
6848 pw.println(" Reason: " + reason);
6849 }
6850 pw.println();
6851 getActivityStartController().dump(pw, " ", null);
6852 pw.println();
6853 pw.println("-------------------------------------------------------------------------------");
6854 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6855 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6856 "" /* header */);
6857 pw.println();
6858 pw.close();
6859
6860 mLastANRState = sw.toString();
6861 }
6862 }
6863
6864 @Override
6865 public void clearSavedANRState() {
6866 synchronized (mGlobalLock) {
6867 mLastANRState = null;
6868 }
6869 }
6870
6871 @Override
6872 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6873 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6874 synchronized (mGlobalLock) {
6875 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6876 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6877 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6878 dumpLastANRLocked(pw);
6879 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6880 dumpLastANRTracesLocked(pw);
6881 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6882 dumpActivityStarterLocked(pw, dumpPackage);
6883 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6884 dumpActivityContainersLocked(pw);
6885 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6886 if (getRecentTasks() != null) {
6887 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6888 }
6889 }
6890 }
6891 }
6892
6893 @Override
6894 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6895 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6896 int wakefulness) {
6897 synchronized (mGlobalLock) {
6898 if (mHomeProcess != null && (dumpPackage == null
6899 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6900 if (needSep) {
6901 pw.println();
6902 needSep = false;
6903 }
6904 pw.println(" mHomeProcess: " + mHomeProcess);
6905 }
6906 if (mPreviousProcess != null && (dumpPackage == null
6907 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6908 if (needSep) {
6909 pw.println();
6910 needSep = false;
6911 }
6912 pw.println(" mPreviousProcess: " + mPreviousProcess);
6913 }
6914 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6915 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6916 StringBuilder sb = new StringBuilder(128);
6917 sb.append(" mPreviousProcessVisibleTime: ");
6918 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6919 pw.println(sb);
6920 }
6921 if (mHeavyWeightProcess != null && (dumpPackage == null
6922 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6923 if (needSep) {
6924 pw.println();
6925 needSep = false;
6926 }
6927 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6928 }
6929 if (dumpPackage == null) {
6930 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006931 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006932 }
6933 if (dumpAll) {
6934 if (dumpPackage == null) {
6935 pw.println(" mConfigWillChange: "
6936 + getTopDisplayFocusedStack().mConfigWillChange);
6937 }
6938 if (mCompatModePackages.getPackages().size() > 0) {
6939 boolean printed = false;
6940 for (Map.Entry<String, Integer> entry
6941 : mCompatModePackages.getPackages().entrySet()) {
6942 String pkg = entry.getKey();
6943 int mode = entry.getValue();
6944 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6945 continue;
6946 }
6947 if (!printed) {
6948 pw.println(" mScreenCompatPackages:");
6949 printed = true;
6950 }
6951 pw.println(" " + pkg + ": " + mode);
6952 }
6953 }
6954 }
6955
6956 if (dumpPackage == null) {
6957 pw.println(" mWakefulness="
6958 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006959 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006960 if (mRunningVoice != null) {
6961 pw.println(" mRunningVoice=" + mRunningVoice);
6962 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6963 }
6964 pw.println(" mSleeping=" + mSleeping);
6965 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6966 pw.println(" mVrController=" + mVrController);
6967 }
6968 if (mCurAppTimeTracker != null) {
6969 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6970 }
6971 if (mAllowAppSwitchUids.size() > 0) {
6972 boolean printed = false;
6973 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6974 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6975 for (int j = 0; j < types.size(); j++) {
6976 if (dumpPackage == null ||
6977 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6978 if (needSep) {
6979 pw.println();
6980 needSep = false;
6981 }
6982 if (!printed) {
6983 pw.println(" mAllowAppSwitchUids:");
6984 printed = true;
6985 }
6986 pw.print(" User ");
6987 pw.print(mAllowAppSwitchUids.keyAt(i));
6988 pw.print(": Type ");
6989 pw.print(types.keyAt(j));
6990 pw.print(" = ");
6991 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6992 pw.println();
6993 }
6994 }
6995 }
6996 }
6997 if (dumpPackage == null) {
6998 if (mController != null) {
6999 pw.println(" mController=" + mController
7000 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7001 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007002 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7003 pw.println(" mLaunchingActivityWakeLock="
7004 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007005 }
7006
7007 return needSep;
7008 }
7009 }
7010
7011 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007012 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7013 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007014 synchronized (mGlobalLock) {
7015 if (dumpPackage == null) {
7016 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7017 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007018 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7019 if (mRunningVoice != null) {
7020 final long vrToken = proto.start(
7021 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7022 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7023 mRunningVoice.toString());
7024 mVoiceWakeLock.writeToProto(
7025 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7026 proto.end(vrToken);
7027 }
7028 mVrController.writeToProto(proto,
7029 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007030 if (mController != null) {
7031 final long token = proto.start(CONTROLLER);
7032 proto.write(CONTROLLER, mController.toString());
7033 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7034 proto.end(token);
7035 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007036 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7037 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7038 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007039 }
7040
7041 if (mHomeProcess != null && (dumpPackage == null
7042 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007043 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007044 }
7045
7046 if (mPreviousProcess != null && (dumpPackage == null
7047 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007048 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007049 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7050 }
7051
7052 if (mHeavyWeightProcess != null && (dumpPackage == null
7053 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007054 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007055 }
7056
7057 for (Map.Entry<String, Integer> entry
7058 : mCompatModePackages.getPackages().entrySet()) {
7059 String pkg = entry.getKey();
7060 int mode = entry.getValue();
7061 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7062 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7063 proto.write(PACKAGE, pkg);
7064 proto.write(MODE, mode);
7065 proto.end(compatToken);
7066 }
7067 }
7068
7069 if (mCurAppTimeTracker != null) {
7070 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7071 }
7072
7073 }
7074 }
7075
7076 @Override
7077 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7078 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7079 boolean dumpFocusedStackOnly) {
7080 synchronized (mGlobalLock) {
7081 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7082 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7083 }
7084 }
7085
7086 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007087 public void dumpForOom(PrintWriter pw) {
7088 synchronized (mGlobalLock) {
7089 pw.println(" mHomeProcess: " + mHomeProcess);
7090 pw.println(" mPreviousProcess: " + mPreviousProcess);
7091 if (mHeavyWeightProcess != null) {
7092 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7093 }
7094 }
7095 }
7096
7097 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007098 public boolean canGcNow() {
7099 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007100 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007101 }
7102 }
7103
Riddle Hsua0536432019-02-16 00:38:59 +08007104 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007105 @Override
7106 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007107 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007108 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007109 return top != null ? top.app : null;
7110 }
7111 }
7112
Riddle Hsua0536432019-02-16 00:38:59 +08007113 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007114 @Override
7115 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007116 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007117 if (mRootActivityContainer != null) {
7118 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007119 }
7120 }
7121 }
7122
7123 @Override
7124 public void scheduleDestroyAllActivities(String reason) {
7125 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007126 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 }
7128 }
7129
7130 @Override
7131 public void removeUser(int userId) {
7132 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007133 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007134 }
7135 }
7136
7137 @Override
7138 public boolean switchUser(int userId, UserState userState) {
7139 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007140 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007141 }
7142 }
7143
7144 @Override
7145 public void onHandleAppCrash(WindowProcessController wpc) {
7146 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007147 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007148 }
7149 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007150
7151 @Override
7152 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7153 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007154 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007155 }
7156 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007157
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 onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007161 mActiveUids.onUidActive(uid, procState);
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 onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007167 mActiveUids.onUidInactive(uid);
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 onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007173 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007174 }
7175
Riddle Hsua0536432019-02-16 00:38:59 +08007176 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007177 @Override
7178 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007179 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007180 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007181
7182 @Override
7183 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007184 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007185 mPendingTempWhitelist.put(uid, tag);
7186 }
7187 }
7188
7189 @Override
7190 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007191 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007192 mPendingTempWhitelist.remove(uid);
7193 }
7194 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007195
7196 @Override
7197 public boolean handleAppCrashInActivityController(String processName, int pid,
7198 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7199 Runnable killCrashingAppCallback) {
7200 synchronized (mGlobalLock) {
7201 if (mController == null) {
7202 return false;
7203 }
7204
7205 try {
7206 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7207 stackTrace)) {
7208 killCrashingAppCallback.run();
7209 return true;
7210 }
7211 } catch (RemoteException e) {
7212 mController = null;
7213 Watchdog.getInstance().setActivityController(null);
7214 }
7215 return false;
7216 }
7217 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007218
7219 @Override
7220 public void removeRecentTasksByPackageName(String packageName, int userId) {
7221 synchronized (mGlobalLock) {
7222 mRecentTasks.removeTasksByPackageName(packageName, userId);
7223 }
7224 }
7225
7226 @Override
7227 public void cleanupRecentTasksForUser(int userId) {
7228 synchronized (mGlobalLock) {
7229 mRecentTasks.cleanupLocked(userId);
7230 }
7231 }
7232
7233 @Override
7234 public void loadRecentTasksForUser(int userId) {
7235 synchronized (mGlobalLock) {
7236 mRecentTasks.loadUserRecentsLocked(userId);
7237 }
7238 }
7239
7240 @Override
7241 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7242 synchronized (mGlobalLock) {
7243 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7244 }
7245 }
7246
7247 @Override
7248 public void flushRecentTasks() {
7249 mRecentTasks.flush();
7250 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007251
7252 @Override
7253 public WindowProcessController getHomeProcess() {
7254 synchronized (mGlobalLock) {
7255 return mHomeProcess;
7256 }
7257 }
7258
7259 @Override
7260 public WindowProcessController getPreviousProcess() {
7261 synchronized (mGlobalLock) {
7262 return mPreviousProcess;
7263 }
7264 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007265
7266 @Override
7267 public void clearLockedTasks(String reason) {
7268 synchronized (mGlobalLock) {
7269 getLockTaskController().clearLockedTasks(reason);
7270 }
7271 }
7272
7273 @Override
7274 public void updateUserConfiguration() {
7275 synchronized (mGlobalLock) {
7276 final Configuration configuration = new Configuration(getGlobalConfiguration());
7277 final int currentUserId = mAmInternal.getCurrentUserId();
7278 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7279 configuration, currentUserId, Settings.System.canWrite(mContext));
7280 updateConfigurationLocked(configuration, null /* starting */,
7281 false /* initLocale */, false /* persistent */, currentUserId,
7282 false /* deferResume */);
7283 }
7284 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007285
7286 @Override
7287 public boolean canShowErrorDialogs() {
7288 synchronized (mGlobalLock) {
7289 return mShowDialogs && !mSleeping && !mShuttingDown
7290 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7291 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7292 mAmInternal.getCurrentUserId())
7293 && !(UserManager.isDeviceInDemoMode(mContext)
7294 && mAmInternal.getCurrentUser().isDemo());
7295 }
7296 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007297
7298 @Override
7299 public void setProfileApp(String profileApp) {
7300 synchronized (mGlobalLock) {
7301 mProfileApp = profileApp;
7302 }
7303 }
7304
7305 @Override
7306 public void setProfileProc(WindowProcessController wpc) {
7307 synchronized (mGlobalLock) {
7308 mProfileProc = wpc;
7309 }
7310 }
7311
7312 @Override
7313 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7314 synchronized (mGlobalLock) {
7315 mProfilerInfo = profilerInfo;
7316 }
7317 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007318
7319 @Override
7320 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7321 synchronized (mGlobalLock) {
7322 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7323 }
7324 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007325
7326 @Override
7327 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7328 synchronized (mGlobalLock) {
7329 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7330 }
7331 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007332
7333 @Override
7334 public boolean isUidForeground(int uid) {
7335 synchronized (mGlobalLock) {
7336 return ActivityTaskManagerService.this.isUidForeground(uid);
7337 }
7338 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007339
7340 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007341 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007342 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007343 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007344 }
7345 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007346
7347 @Override
7348 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007349 // Translate package names into UIDs
7350 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007351 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007352 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7353 if (uid >= 0) {
7354 result.add(uid);
7355 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007356 }
7357 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007358 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007359 }
7360 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007361 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007362}