blob: 3fa02687395379c855bd9afa6184b32c996e428e [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);
3375 } else {
3376 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3377 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003378 } finally {
3379 Binder.restoreCallingIdentity(ident);
3380 }
3381 }
3382 }
3383
3384 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3385 @Override
3386 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003387 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003389 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 }
3391
3392 /** Unregister a task stack listener so that it stops receiving callbacks. */
3393 @Override
3394 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003395 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003397 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 }
3399
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 @Override
3401 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3402 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3403 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3404 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3405 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3406 }
3407
3408 @Override
3409 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3410 IBinder activityToken, int flags) {
3411 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3412 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3413 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3414 }
3415
3416 @Override
3417 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3418 Bundle args) {
3419 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3420 true /* focused */, true /* newSessionId */, userHandle, args,
3421 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3422 }
3423
3424 @Override
3425 public Bundle getAssistContextExtras(int requestType) {
3426 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3427 null, null, true /* focused */, true /* newSessionId */,
3428 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3429 if (pae == null) {
3430 return null;
3431 }
3432 synchronized (pae) {
3433 while (!pae.haveResult) {
3434 try {
3435 pae.wait();
3436 } catch (InterruptedException e) {
3437 }
3438 }
3439 }
3440 synchronized (mGlobalLock) {
3441 buildAssistBundleLocked(pae, pae.result);
3442 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003443 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003444 }
3445 return pae.extras;
3446 }
3447
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003448 /**
3449 * Binder IPC calls go through the public entry point.
3450 * This can be called with or without the global lock held.
3451 */
3452 private static int checkCallingPermission(String permission) {
3453 return checkPermission(
3454 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3455 }
3456
3457 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003458 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3460 mAmInternal.enforceCallingPermission(permission, func);
3461 }
3462 }
3463
3464 @VisibleForTesting
3465 int checkGetTasksPermission(String permission, int pid, int uid) {
3466 return checkPermission(permission, pid, uid);
3467 }
3468
3469 static int checkPermission(String permission, int pid, int uid) {
3470 if (permission == null) {
3471 return PackageManager.PERMISSION_DENIED;
3472 }
3473 return checkComponentPermission(permission, pid, uid, -1, true);
3474 }
3475
Wale Ogunwale214f3482018-10-04 11:00:47 -07003476 public static int checkComponentPermission(String permission, int pid, int uid,
3477 int owningUid, boolean exported) {
3478 return ActivityManagerService.checkComponentPermission(
3479 permission, pid, uid, owningUid, exported);
3480 }
3481
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003482 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3483 if (getRecentTasks().isCallerRecents(callingUid)) {
3484 // Always allow the recents component to get tasks
3485 return true;
3486 }
3487
3488 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3489 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3490 if (!allowed) {
3491 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3492 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3493 // Temporary compatibility: some existing apps on the system image may
3494 // still be requesting the old permission and not switched to the new
3495 // one; if so, we'll still allow them full access. This means we need
3496 // to see if they are holding the old permission and are a system app.
3497 try {
3498 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3499 allowed = true;
3500 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3501 + " is using old GET_TASKS but privileged; allowing");
3502 }
3503 } catch (RemoteException e) {
3504 }
3505 }
3506 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3507 + " does not hold REAL_GET_TASKS; limiting output");
3508 }
3509 return allowed;
3510 }
3511
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003512 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3513 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3514 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3515 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003516 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003517 "enqueueAssistContext()");
3518
3519 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003520 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003521 if (activity == null) {
3522 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3523 return null;
3524 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003525 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003526 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3527 return null;
3528 }
3529 if (focused) {
3530 if (activityToken != null) {
3531 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3532 if (activity != caller) {
3533 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3534 + " is not current top " + activity);
3535 return null;
3536 }
3537 }
3538 } else {
3539 activity = ActivityRecord.forTokenLocked(activityToken);
3540 if (activity == null) {
3541 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3542 + " couldn't be found");
3543 return null;
3544 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003545 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003546 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3547 return null;
3548 }
3549 }
3550
3551 PendingAssistExtras pae;
3552 Bundle extras = new Bundle();
3553 if (args != null) {
3554 extras.putAll(args);
3555 }
3556 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003557 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003558
3559 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3560 userHandle);
3561 pae.isHome = activity.isActivityTypeHome();
3562
3563 // Increment the sessionId if necessary
3564 if (newSessionId) {
3565 mViSessionId++;
3566 }
3567 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003568 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3569 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003570 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003571 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003572 } catch (RemoteException e) {
3573 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3574 return null;
3575 }
3576 return pae;
3577 }
3578 }
3579
3580 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3581 if (result != null) {
3582 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3583 }
3584 if (pae.hint != null) {
3585 pae.extras.putBoolean(pae.hint, true);
3586 }
3587 }
3588
3589 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3590 IAssistDataReceiver receiver;
3591 synchronized (mGlobalLock) {
3592 mPendingAssistExtras.remove(pae);
3593 receiver = pae.receiver;
3594 }
3595 if (receiver != null) {
3596 // Caller wants result sent back to them.
3597 Bundle sendBundle = new Bundle();
3598 // At least return the receiver extras
3599 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3600 try {
3601 pae.receiver.onHandleAssistData(sendBundle);
3602 } catch (RemoteException e) {
3603 }
3604 }
3605 }
3606
3607 public class PendingAssistExtras extends Binder implements Runnable {
3608 public final ActivityRecord activity;
3609 public boolean isHome;
3610 public final Bundle extras;
3611 public final Intent intent;
3612 public final String hint;
3613 public final IAssistDataReceiver receiver;
3614 public final int userHandle;
3615 public boolean haveResult = false;
3616 public Bundle result = null;
3617 public AssistStructure structure = null;
3618 public AssistContent content = null;
3619 public Bundle receiverExtras;
3620
3621 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3622 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3623 int _userHandle) {
3624 activity = _activity;
3625 extras = _extras;
3626 intent = _intent;
3627 hint = _hint;
3628 receiver = _receiver;
3629 receiverExtras = _receiverExtras;
3630 userHandle = _userHandle;
3631 }
3632
3633 @Override
3634 public void run() {
3635 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3636 synchronized (this) {
3637 haveResult = true;
3638 notifyAll();
3639 }
3640 pendingAssistExtrasTimedOut(this);
3641 }
3642 }
3643
3644 @Override
3645 public boolean isAssistDataAllowedOnCurrentActivity() {
3646 int userId;
3647 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003648 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3650 return false;
3651 }
3652
3653 final ActivityRecord activity = focusedStack.getTopActivity();
3654 if (activity == null) {
3655 return false;
3656 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003657 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 }
3659 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3660 }
3661
3662 @Override
3663 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3664 long ident = Binder.clearCallingIdentity();
3665 try {
3666 synchronized (mGlobalLock) {
3667 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003668 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 if (top != caller) {
3670 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3671 + " is not current top " + top);
3672 return false;
3673 }
3674 if (!top.nowVisible) {
3675 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3676 + " is not visible");
3677 return false;
3678 }
3679 }
3680 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3681 token);
3682 } finally {
3683 Binder.restoreCallingIdentity(ident);
3684 }
3685 }
3686
3687 @Override
3688 public boolean isRootVoiceInteraction(IBinder token) {
3689 synchronized (mGlobalLock) {
3690 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3691 if (r == null) {
3692 return false;
3693 }
3694 return r.rootVoiceInteraction;
3695 }
3696 }
3697
Wale Ogunwalef6733932018-06-27 05:14:34 -07003698 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3699 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3700 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3701 if (activityToCallback == null) return;
3702 activityToCallback.setVoiceSessionLocked(voiceSession);
3703
3704 // Inform the activity
3705 try {
3706 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3707 voiceInteractor);
3708 long token = Binder.clearCallingIdentity();
3709 try {
3710 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3711 } finally {
3712 Binder.restoreCallingIdentity(token);
3713 }
3714 // TODO: VI Should we cache the activity so that it's easier to find later
3715 // rather than scan through all the stacks and activities?
3716 } catch (RemoteException re) {
3717 activityToCallback.clearVoiceSessionLocked();
3718 // TODO: VI Should this terminate the voice session?
3719 }
3720 }
3721
3722 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3723 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3724 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3725 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3726 boolean wasRunningVoice = mRunningVoice != null;
3727 mRunningVoice = session;
3728 if (!wasRunningVoice) {
3729 mVoiceWakeLock.acquire();
3730 updateSleepIfNeededLocked();
3731 }
3732 }
3733 }
3734
3735 void finishRunningVoiceLocked() {
3736 if (mRunningVoice != null) {
3737 mRunningVoice = null;
3738 mVoiceWakeLock.release();
3739 updateSleepIfNeededLocked();
3740 }
3741 }
3742
3743 @Override
3744 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3745 synchronized (mGlobalLock) {
3746 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3747 if (keepAwake) {
3748 mVoiceWakeLock.acquire();
3749 } else {
3750 mVoiceWakeLock.release();
3751 }
3752 }
3753 }
3754 }
3755
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003756 @Override
3757 public ComponentName getActivityClassForToken(IBinder token) {
3758 synchronized (mGlobalLock) {
3759 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3760 if (r == null) {
3761 return null;
3762 }
3763 return r.intent.getComponent();
3764 }
3765 }
3766
3767 @Override
3768 public String getPackageForToken(IBinder token) {
3769 synchronized (mGlobalLock) {
3770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3771 if (r == null) {
3772 return null;
3773 }
3774 return r.packageName;
3775 }
3776 }
3777
3778 @Override
3779 public void showLockTaskEscapeMessage(IBinder token) {
3780 synchronized (mGlobalLock) {
3781 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3782 if (r == null) {
3783 return;
3784 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003785 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 }
3787 }
3788
3789 @Override
3790 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003791 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 final long token = Binder.clearCallingIdentity();
3793 try {
3794 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003795 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003796 }
3797 } finally {
3798 Binder.restoreCallingIdentity(token);
3799 }
3800 }
3801
3802 /**
3803 * Try to place task to provided position. The final position might be different depending on
3804 * current user and stacks state. The task will be moved to target stack if it's currently in
3805 * different stack.
3806 */
3807 @Override
3808 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003809 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 synchronized (mGlobalLock) {
3811 long ident = Binder.clearCallingIdentity();
3812 try {
3813 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3814 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003815 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003816 if (task == null) {
3817 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3818 + taskId);
3819 }
3820
Wale Ogunwaled32da472018-11-16 07:19:28 -08003821 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822
3823 if (stack == null) {
3824 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3825 + stackId);
3826 }
3827 if (!stack.isActivityTypeStandardOrUndefined()) {
3828 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3829 + " the position of task " + taskId + " in/to non-standard stack");
3830 }
3831
3832 // TODO: Have the callers of this API call a separate reparent method if that is
3833 // what they intended to do vs. having this method also do reparenting.
3834 if (task.getStack() == stack) {
3835 // Change position in current stack.
3836 stack.positionChildAt(task, position);
3837 } else {
3838 // Reparent to new stack.
3839 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3840 !DEFER_RESUME, "positionTaskInStack");
3841 }
3842 } finally {
3843 Binder.restoreCallingIdentity(ident);
3844 }
3845 }
3846 }
3847
3848 @Override
3849 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3850 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3851 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3852 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3853 synchronized (mGlobalLock) {
3854 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3855 if (record == null) {
3856 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3857 + "found for: " + token);
3858 }
3859 record.setSizeConfigurations(horizontalSizeConfiguration,
3860 verticalSizeConfigurations, smallestSizeConfigurations);
3861 }
3862 }
3863
3864 /**
3865 * Dismisses split-screen multi-window mode.
3866 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3867 */
3868 @Override
3869 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003870 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003871 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3872 final long ident = Binder.clearCallingIdentity();
3873 try {
3874 synchronized (mGlobalLock) {
3875 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003876 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003877 if (stack == null) {
3878 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3879 return;
3880 }
3881
3882 if (toTop) {
3883 // Caller wants the current split-screen primary stack to be the top stack after
3884 // it goes fullscreen, so move it to the front.
3885 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003886 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003887 // In this case the current split-screen primary stack shouldn't be the top
3888 // stack after it goes fullscreen, but it current has focus, so we move the
3889 // focus to the top-most split-screen secondary stack next to it.
3890 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3891 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3892 if (otherStack != null) {
3893 otherStack.moveToFront("dismissSplitScreenMode_other");
3894 }
3895 }
3896
Evan Rosky10475742018-09-05 19:02:48 -07003897 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003898 }
3899 } finally {
3900 Binder.restoreCallingIdentity(ident);
3901 }
3902 }
3903
3904 /**
3905 * Dismisses Pip
3906 * @param animate True if the dismissal should be animated.
3907 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3908 * default animation duration should be used.
3909 */
3910 @Override
3911 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003912 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 final long ident = Binder.clearCallingIdentity();
3914 try {
3915 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003916 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003917 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 if (stack == null) {
3919 Slog.w(TAG, "dismissPip: pinned stack not found.");
3920 return;
3921 }
3922 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3923 throw new IllegalArgumentException("Stack: " + stack
3924 + " doesn't support animated resize.");
3925 }
3926 if (animate) {
3927 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3928 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3929 } else {
3930 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3931 }
3932 }
3933 } finally {
3934 Binder.restoreCallingIdentity(ident);
3935 }
3936 }
3937
3938 @Override
3939 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003940 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003941 synchronized (mGlobalLock) {
3942 mSuppressResizeConfigChanges = suppress;
3943 }
3944 }
3945
3946 /**
3947 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3948 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3949 * activity and clearing the task at the same time.
3950 */
3951 @Override
3952 // TODO: API should just be about changing windowing modes...
3953 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003954 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 "moveTasksToFullscreenStack()");
3956 synchronized (mGlobalLock) {
3957 final long origId = Binder.clearCallingIdentity();
3958 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003959 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 if (stack != null){
3961 if (!stack.isActivityTypeStandardOrUndefined()) {
3962 throw new IllegalArgumentException(
3963 "You can't move tasks from non-standard stacks.");
3964 }
3965 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3966 }
3967 } finally {
3968 Binder.restoreCallingIdentity(origId);
3969 }
3970 }
3971 }
3972
3973 /**
3974 * Moves the top activity in the input stackId to the pinned stack.
3975 *
3976 * @param stackId Id of stack to move the top activity to pinned stack.
3977 * @param bounds Bounds to use for pinned stack.
3978 *
3979 * @return True if the top activity of the input stack was successfully moved to the pinned
3980 * stack.
3981 */
3982 @Override
3983 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003984 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 "moveTopActivityToPinnedStack()");
3986 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003987 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003988 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3989 + "Device doesn't support picture-in-picture mode");
3990 }
3991
3992 long ident = Binder.clearCallingIdentity();
3993 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003994 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 } finally {
3996 Binder.restoreCallingIdentity(ident);
3997 }
3998 }
3999 }
4000
4001 @Override
4002 public boolean isInMultiWindowMode(IBinder token) {
4003 final long origId = Binder.clearCallingIdentity();
4004 try {
4005 synchronized (mGlobalLock) {
4006 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4007 if (r == null) {
4008 return false;
4009 }
4010 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4011 return r.inMultiWindowMode();
4012 }
4013 } finally {
4014 Binder.restoreCallingIdentity(origId);
4015 }
4016 }
4017
4018 @Override
4019 public boolean isInPictureInPictureMode(IBinder token) {
4020 final long origId = Binder.clearCallingIdentity();
4021 try {
4022 synchronized (mGlobalLock) {
4023 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4024 }
4025 } finally {
4026 Binder.restoreCallingIdentity(origId);
4027 }
4028 }
4029
4030 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004031 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4032 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004033 return false;
4034 }
4035
4036 // If we are animating to fullscreen then we have already dispatched the PIP mode
4037 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004038 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4039 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004040 }
4041
4042 @Override
4043 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4044 final long origId = Binder.clearCallingIdentity();
4045 try {
4046 synchronized (mGlobalLock) {
4047 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4048 "enterPictureInPictureMode", token, params);
4049
4050 // If the activity is already in picture in picture mode, then just return early
4051 if (isInPictureInPictureMode(r)) {
4052 return true;
4053 }
4054
4055 // Activity supports picture-in-picture, now check that we can enter PiP at this
4056 // point, if it is
4057 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4058 false /* beforeStopping */)) {
4059 return false;
4060 }
4061
4062 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004063 synchronized (mGlobalLock) {
4064 // Only update the saved args from the args that are set
4065 r.pictureInPictureArgs.copyOnlySet(params);
4066 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4067 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4068 // Adjust the source bounds by the insets for the transition down
4069 final Rect sourceBounds = new Rect(
4070 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004071 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004072 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004073 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004074 stack.setPictureInPictureAspectRatio(aspectRatio);
4075 stack.setPictureInPictureActions(actions);
4076 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4077 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4078 logPictureInPictureArgs(params);
4079 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 };
4081
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004082 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004083 // If the keyguard is showing or occluded, then try and dismiss it before
4084 // entering picture-in-picture (this will prompt the user to authenticate if the
4085 // device is currently locked).
4086 dismissKeyguard(token, new KeyguardDismissCallback() {
4087 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004088 public void onDismissSucceeded() {
4089 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 }
4091 }, null /* message */);
4092 } else {
4093 // Enter picture in picture immediately otherwise
4094 enterPipRunnable.run();
4095 }
4096 return true;
4097 }
4098 } finally {
4099 Binder.restoreCallingIdentity(origId);
4100 }
4101 }
4102
4103 @Override
4104 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4105 final long origId = Binder.clearCallingIdentity();
4106 try {
4107 synchronized (mGlobalLock) {
4108 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4109 "setPictureInPictureParams", token, params);
4110
4111 // Only update the saved args from the args that are set
4112 r.pictureInPictureArgs.copyOnlySet(params);
4113 if (r.inPinnedWindowingMode()) {
4114 // If the activity is already in picture-in-picture, update the pinned stack now
4115 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4116 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004117 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 if (!stack.isAnimatingBoundsToFullscreen()) {
4119 stack.setPictureInPictureAspectRatio(
4120 r.pictureInPictureArgs.getAspectRatio());
4121 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4122 }
4123 }
4124 logPictureInPictureArgs(params);
4125 }
4126 } finally {
4127 Binder.restoreCallingIdentity(origId);
4128 }
4129 }
4130
4131 @Override
4132 public int getMaxNumPictureInPictureActions(IBinder token) {
4133 // Currently, this is a static constant, but later, we may change this to be dependent on
4134 // the context of the activity
4135 return 3;
4136 }
4137
4138 private void logPictureInPictureArgs(PictureInPictureParams params) {
4139 if (params.hasSetActions()) {
4140 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4141 params.getActions().size());
4142 }
4143 if (params.hasSetAspectRatio()) {
4144 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4145 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4146 MetricsLogger.action(lm);
4147 }
4148 }
4149
4150 /**
4151 * Checks the state of the system and the activity associated with the given {@param token} to
4152 * verify that picture-in-picture is supported for that activity.
4153 *
4154 * @return the activity record for the given {@param token} if all the checks pass.
4155 */
4156 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4157 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 throw new IllegalStateException(caller
4160 + ": Device doesn't support picture-in-picture mode.");
4161 }
4162
4163 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4164 if (r == null) {
4165 throw new IllegalStateException(caller
4166 + ": Can't find activity for token=" + token);
4167 }
4168
4169 if (!r.supportsPictureInPicture()) {
4170 throw new IllegalStateException(caller
4171 + ": Current activity does not support picture-in-picture.");
4172 }
4173
4174 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004175 && !mWindowManager.isValidPictureInPictureAspectRatio(
4176 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 final float minAspectRatio = mContext.getResources().getFloat(
4178 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4179 final float maxAspectRatio = mContext.getResources().getFloat(
4180 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4181 throw new IllegalArgumentException(String.format(caller
4182 + ": Aspect ratio is too extreme (must be between %f and %f).",
4183 minAspectRatio, maxAspectRatio));
4184 }
4185
4186 // Truncate the number of actions if necessary
4187 params.truncateActions(getMaxNumPictureInPictureActions(token));
4188
4189 return r;
4190 }
4191
4192 @Override
4193 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004194 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004195 synchronized (mGlobalLock) {
4196 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4197 if (r == null) {
4198 throw new IllegalArgumentException("Activity does not exist; token="
4199 + activityToken);
4200 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004201 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 }
4203 }
4204
4205 @Override
4206 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4207 Rect tempDockedTaskInsetBounds,
4208 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004209 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004210 long ident = Binder.clearCallingIdentity();
4211 try {
4212 synchronized (mGlobalLock) {
4213 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4214 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4215 PRESERVE_WINDOWS);
4216 }
4217 } finally {
4218 Binder.restoreCallingIdentity(ident);
4219 }
4220 }
4221
4222 @Override
4223 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004224 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 final long ident = Binder.clearCallingIdentity();
4226 try {
4227 synchronized (mGlobalLock) {
4228 mStackSupervisor.setSplitScreenResizing(resizing);
4229 }
4230 } finally {
4231 Binder.restoreCallingIdentity(ident);
4232 }
4233 }
4234
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004235 /**
4236 * Check that we have the features required for VR-related API calls, and throw an exception if
4237 * not.
4238 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004239 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004240 if (!mContext.getPackageManager().hasSystemFeature(
4241 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4242 throw new UnsupportedOperationException("VR mode not supported on this device!");
4243 }
4244 }
4245
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 @Override
4247 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004248 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249
4250 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4251
4252 ActivityRecord r;
4253 synchronized (mGlobalLock) {
4254 r = ActivityRecord.isInStackLocked(token);
4255 }
4256
4257 if (r == null) {
4258 throw new IllegalArgumentException();
4259 }
4260
4261 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004262 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 VrManagerInternal.NO_ERROR) {
4264 return err;
4265 }
4266
4267 // Clear the binder calling uid since this path may call moveToTask().
4268 final long callingId = Binder.clearCallingIdentity();
4269 try {
4270 synchronized (mGlobalLock) {
4271 r.requestedVrComponent = (enabled) ? packageName : null;
4272
4273 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004274 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004275 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 }
4277 return 0;
4278 }
4279 } finally {
4280 Binder.restoreCallingIdentity(callingId);
4281 }
4282 }
4283
4284 @Override
4285 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4286 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4287 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004288 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4290 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4291 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004292 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004293 || activity.voiceSession != null) {
4294 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4295 return;
4296 }
4297 if (activity.pendingVoiceInteractionStart) {
4298 Slog.w(TAG, "Pending start of voice interaction already.");
4299 return;
4300 }
4301 activity.pendingVoiceInteractionStart = true;
4302 }
4303 LocalServices.getService(VoiceInteractionManagerInternal.class)
4304 .startLocalVoiceInteraction(callingActivity, options);
4305 }
4306
4307 @Override
4308 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4309 LocalServices.getService(VoiceInteractionManagerInternal.class)
4310 .stopLocalVoiceInteraction(callingActivity);
4311 }
4312
4313 @Override
4314 public boolean supportsLocalVoiceInteraction() {
4315 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4316 .supportsLocalVoiceInteraction();
4317 }
4318
4319 /** Notifies all listeners when the pinned stack animation starts. */
4320 @Override
4321 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004322 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004323 }
4324
4325 /** Notifies all listeners when the pinned stack animation ends. */
4326 @Override
4327 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004328 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 }
4330
4331 @Override
4332 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004333 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 final long ident = Binder.clearCallingIdentity();
4335 try {
4336 synchronized (mGlobalLock) {
4337 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4338 }
4339 } finally {
4340 Binder.restoreCallingIdentity(ident);
4341 }
4342 }
4343
4344 @Override
4345 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347
4348 synchronized (mGlobalLock) {
4349 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004350 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 // Call might come when display is not yet added or has already been removed.
4352 if (DEBUG_CONFIGURATION) {
4353 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4354 + displayId);
4355 }
4356 return false;
4357 }
4358
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004359 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004360 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004361 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 }
4363
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004364 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004365 final Message msg = PooledLambda.obtainMessage(
4366 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4367 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 }
4369
4370 final long origId = Binder.clearCallingIdentity();
4371 try {
4372 if (values != null) {
4373 Settings.System.clearConfiguration(values);
4374 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004376 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4377 return mTmpUpdateConfigurationResult.changes != 0;
4378 } finally {
4379 Binder.restoreCallingIdentity(origId);
4380 }
4381 }
4382 }
4383
4384 @Override
4385 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004386 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387
4388 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004389 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004390 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004391 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004392 }
4393
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004394 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004395 final Message msg = PooledLambda.obtainMessage(
4396 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4397 DEFAULT_DISPLAY);
4398 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004399 }
4400
4401 final long origId = Binder.clearCallingIdentity();
4402 try {
4403 if (values != null) {
4404 Settings.System.clearConfiguration(values);
4405 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 UserHandle.USER_NULL, false /* deferResume */,
4408 mTmpUpdateConfigurationResult);
4409 return mTmpUpdateConfigurationResult.changes != 0;
4410 } finally {
4411 Binder.restoreCallingIdentity(origId);
4412 }
4413 }
4414 }
4415
4416 @Override
4417 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4418 CharSequence message) {
4419 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004420 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004421 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4422 }
4423 final long callingId = Binder.clearCallingIdentity();
4424 try {
4425 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004426 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 }
4428 } finally {
4429 Binder.restoreCallingIdentity(callingId);
4430 }
4431 }
4432
4433 @Override
4434 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004435 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004436 "cancelTaskWindowTransition()");
4437 final long ident = Binder.clearCallingIdentity();
4438 try {
4439 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004440 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 MATCH_TASK_IN_STACKS_ONLY);
4442 if (task == null) {
4443 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4444 return;
4445 }
4446 task.cancelWindowTransition();
4447 }
4448 } finally {
4449 Binder.restoreCallingIdentity(ident);
4450 }
4451 }
4452
4453 @Override
4454 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 final long ident = Binder.clearCallingIdentity();
4457 try {
4458 final TaskRecord task;
4459 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004460 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4462 if (task == null) {
4463 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4464 return null;
4465 }
4466 }
4467 // Don't call this while holding the lock as this operation might hit the disk.
4468 return task.getSnapshot(reducedResolution);
4469 } finally {
4470 Binder.restoreCallingIdentity(ident);
4471 }
4472 }
4473
4474 @Override
4475 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4476 synchronized (mGlobalLock) {
4477 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4478 if (r == null) {
4479 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4480 + token);
4481 return;
4482 }
4483 final long origId = Binder.clearCallingIdentity();
4484 try {
4485 r.setDisablePreviewScreenshots(disable);
4486 } finally {
4487 Binder.restoreCallingIdentity(origId);
4488 }
4489 }
4490 }
4491
4492 /** Return the user id of the last resumed activity. */
4493 @Override
4494 public @UserIdInt
4495 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004496 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004497 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4498 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004499 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004501 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004502 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004503 }
4504 }
4505
4506 @Override
4507 public void updateLockTaskFeatures(int userId, int flags) {
4508 final int callingUid = Binder.getCallingUid();
4509 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004510 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004511 "updateLockTaskFeatures()");
4512 }
4513 synchronized (mGlobalLock) {
4514 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4515 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004516 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 }
4518 }
4519
4520 @Override
4521 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4522 synchronized (mGlobalLock) {
4523 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4524 if (r == null) {
4525 return;
4526 }
4527 final long origId = Binder.clearCallingIdentity();
4528 try {
4529 r.setShowWhenLocked(showWhenLocked);
4530 } finally {
4531 Binder.restoreCallingIdentity(origId);
4532 }
4533 }
4534 }
4535
4536 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004537 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4538 synchronized (mGlobalLock) {
4539 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4540 if (r == null) {
4541 return;
4542 }
4543 final long origId = Binder.clearCallingIdentity();
4544 try {
4545 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4546 } finally {
4547 Binder.restoreCallingIdentity(origId);
4548 }
4549 }
4550 }
4551
4552 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004553 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4554 synchronized (mGlobalLock) {
4555 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4556 if (r == null) {
4557 return;
4558 }
4559 final long origId = Binder.clearCallingIdentity();
4560 try {
4561 r.setTurnScreenOn(turnScreenOn);
4562 } finally {
4563 Binder.restoreCallingIdentity(origId);
4564 }
4565 }
4566 }
4567
4568 @Override
4569 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004570 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004571 "registerRemoteAnimations");
4572 definition.setCallingPid(Binder.getCallingPid());
4573 synchronized (mGlobalLock) {
4574 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4575 if (r == null) {
4576 return;
4577 }
4578 final long origId = Binder.clearCallingIdentity();
4579 try {
4580 r.registerRemoteAnimations(definition);
4581 } finally {
4582 Binder.restoreCallingIdentity(origId);
4583 }
4584 }
4585 }
4586
4587 @Override
4588 public void registerRemoteAnimationForNextActivityStart(String packageName,
4589 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004590 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004591 "registerRemoteAnimationForNextActivityStart");
4592 adapter.setCallingPid(Binder.getCallingPid());
4593 synchronized (mGlobalLock) {
4594 final long origId = Binder.clearCallingIdentity();
4595 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004596 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 packageName, adapter);
4598 } finally {
4599 Binder.restoreCallingIdentity(origId);
4600 }
4601 }
4602 }
4603
Evan Rosky966759f2019-01-15 10:33:58 -08004604 @Override
4605 public void registerRemoteAnimationsForDisplay(int displayId,
4606 RemoteAnimationDefinition definition) {
4607 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4608 "registerRemoteAnimations");
4609 definition.setCallingPid(Binder.getCallingPid());
4610 synchronized (mGlobalLock) {
4611 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4612 if (display == null) {
4613 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4614 return;
4615 }
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 display.mDisplayContent.registerRemoteAnimations(definition);
4619 } finally {
4620 Binder.restoreCallingIdentity(origId);
4621 }
4622 }
4623 }
4624
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004625 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4626 @Override
4627 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4628 synchronized (mGlobalLock) {
4629 final long origId = Binder.clearCallingIdentity();
4630 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004631 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 } finally {
4633 Binder.restoreCallingIdentity(origId);
4634 }
4635 }
4636 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004637
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004638 @Override
4639 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004640 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004642 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004643 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004644 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004645 }
4646 }
4647
4648 @Override
4649 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004650 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004651 != PERMISSION_GRANTED) {
4652 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4653 + Binder.getCallingPid()
4654 + ", uid=" + Binder.getCallingUid()
4655 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4656 Slog.w(TAG, msg);
4657 throw new SecurityException(msg);
4658 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004659 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004660 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004661 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004662 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004663 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004664 }
4665 }
4666
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004667 @Override
4668 public void stopAppSwitches() {
4669 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4670 synchronized (mGlobalLock) {
4671 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4672 mDidAppSwitch = false;
4673 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4674 }
4675 }
4676
4677 @Override
4678 public void resumeAppSwitches() {
4679 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4680 synchronized (mGlobalLock) {
4681 // Note that we don't execute any pending app switches... we will
4682 // let those wait until either the timeout, or the next start
4683 // activity request.
4684 mAppSwitchesAllowedTime = 0;
4685 }
4686 }
4687
4688 void onStartActivitySetDidAppSwitch() {
4689 if (mDidAppSwitch) {
4690 // This is the second allowed switch since we stopped switches, so now just generally
4691 // allow switches. Use case:
4692 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4693 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4694 // anyone to switch again).
4695 mAppSwitchesAllowedTime = 0;
4696 } else {
4697 mDidAppSwitch = true;
4698 }
4699 }
4700
4701 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004702 boolean shouldDisableNonVrUiLocked() {
4703 return mVrController.shouldDisableNonVrUiLocked();
4704 }
4705
Wale Ogunwale53783742018-09-16 10:21:51 -07004706 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004707 // VR apps are expected to run in a main display. If an app is turning on VR for
4708 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4709 // fullscreen stack before enabling VR Mode.
4710 // TODO: The goal of this code is to keep the VR app on the main display. When the
4711 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4712 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4713 // option would be a better choice here.
4714 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4715 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4716 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004717 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004718 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004719 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 }
4721 mH.post(() -> {
4722 if (!mVrController.onVrModeChanged(r)) {
4723 return;
4724 }
4725 synchronized (mGlobalLock) {
4726 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4727 mWindowManager.disableNonVrUi(disableNonVrUi);
4728 if (disableNonVrUi) {
4729 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4730 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004731 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004732 }
4733 }
4734 });
4735 }
4736
Wale Ogunwale53783742018-09-16 10:21:51 -07004737 @Override
4738 public int getPackageScreenCompatMode(String packageName) {
4739 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4740 synchronized (mGlobalLock) {
4741 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4742 }
4743 }
4744
4745 @Override
4746 public void setPackageScreenCompatMode(String packageName, int mode) {
4747 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4748 "setPackageScreenCompatMode");
4749 synchronized (mGlobalLock) {
4750 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4751 }
4752 }
4753
4754 @Override
4755 public boolean getPackageAskScreenCompat(String packageName) {
4756 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4757 synchronized (mGlobalLock) {
4758 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4759 }
4760 }
4761
4762 @Override
4763 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4764 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4765 "setPackageAskScreenCompat");
4766 synchronized (mGlobalLock) {
4767 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4768 }
4769 }
4770
Wale Ogunwale64258362018-10-16 15:13:37 -07004771 public static String relaunchReasonToString(int relaunchReason) {
4772 switch (relaunchReason) {
4773 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4774 return "window_resize";
4775 case RELAUNCH_REASON_FREE_RESIZE:
4776 return "free_resize";
4777 default:
4778 return null;
4779 }
4780 }
4781
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004782 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004783 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784 }
4785
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004786 /** Pokes the task persister. */
4787 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4788 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4789 }
4790
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004791 boolean isKeyguardLocked() {
4792 return mKeyguardController.isKeyguardLocked();
4793 }
4794
Garfield Tan01548632018-11-27 10:15:48 -08004795 /**
4796 * Clears launch params for the given package.
4797 * @param packageNames the names of the packages of which the launch params are to be cleared
4798 */
4799 @Override
4800 public void clearLaunchParamsForPackages(List<String> packageNames) {
4801 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4802 "clearLaunchParamsForPackages");
4803 synchronized (mGlobalLock) {
4804 for (int i = 0; i < packageNames.size(); ++i) {
4805 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4806 }
4807 }
4808 }
4809
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004810 /**
4811 * Makes the display with the given id a single task instance display. I.e the display can only
4812 * contain one task.
4813 */
4814 @Override
4815 public void setDisplayToSingleTaskInstance(int displayId) {
4816 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4817 "setDisplayToSingleTaskInstance");
4818 final long origId = Binder.clearCallingIdentity();
4819 try {
4820 final ActivityDisplay display =
4821 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4822 if (display != null) {
4823 display.setDisplayToSingleTaskInstance();
4824 }
4825 } finally {
4826 Binder.restoreCallingIdentity(origId);
4827 }
4828 }
4829
Wale Ogunwale31913b52018-10-13 08:29:31 -07004830 void dumpLastANRLocked(PrintWriter pw) {
4831 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4832 if (mLastANRState == null) {
4833 pw.println(" <no ANR has occurred since boot>");
4834 } else {
4835 pw.println(mLastANRState);
4836 }
4837 }
4838
4839 void dumpLastANRTracesLocked(PrintWriter pw) {
4840 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4841
4842 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4843 if (ArrayUtils.isEmpty(files)) {
4844 pw.println(" <no ANR has occurred since boot>");
4845 return;
4846 }
4847 // Find the latest file.
4848 File latest = null;
4849 for (File f : files) {
4850 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4851 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004852 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004853 }
4854 pw.print("File: ");
4855 pw.print(latest.getName());
4856 pw.println();
4857 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4858 String line;
4859 while ((line = in.readLine()) != null) {
4860 pw.println(line);
4861 }
4862 } catch (IOException e) {
4863 pw.print("Unable to read: ");
4864 pw.print(e);
4865 pw.println();
4866 }
4867 }
4868
4869 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4870 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4871 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4872 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4873 }
4874
4875 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4876 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4877 pw.println(header);
4878
Wale Ogunwaled32da472018-11-16 07:19:28 -08004879 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004880 dumpPackage);
4881 boolean needSep = printedAnything;
4882
4883 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004884 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004885 " ResumedActivity: ");
4886 if (printed) {
4887 printedAnything = true;
4888 needSep = false;
4889 }
4890
4891 if (dumpPackage == null) {
4892 if (needSep) {
4893 pw.println();
4894 }
4895 printedAnything = true;
4896 mStackSupervisor.dump(pw, " ");
4897 }
4898
4899 if (!printedAnything) {
4900 pw.println(" (nothing)");
4901 }
4902 }
4903
4904 void dumpActivityContainersLocked(PrintWriter pw) {
4905 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004906 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004907 pw.println(" ");
4908 }
4909
4910 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4911 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4912 getActivityStartController().dump(pw, "", dumpPackage);
4913 }
4914
4915 /**
4916 * There are three things that cmd can be:
4917 * - a flattened component name that matches an existing activity
4918 * - the cmd arg isn't the flattened component name of an existing activity:
4919 * dump all activity whose component contains the cmd as a substring
4920 * - A hex number of the ActivityRecord object instance.
4921 *
4922 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4923 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4924 */
4925 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4926 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4927 ArrayList<ActivityRecord> activities;
4928
4929 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004930 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004931 dumpFocusedStackOnly);
4932 }
4933
4934 if (activities.size() <= 0) {
4935 return false;
4936 }
4937
4938 String[] newArgs = new String[args.length - opti];
4939 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4940
4941 TaskRecord lastTask = null;
4942 boolean needSep = false;
4943 for (int i = activities.size() - 1; i >= 0; i--) {
4944 ActivityRecord r = activities.get(i);
4945 if (needSep) {
4946 pw.println();
4947 }
4948 needSep = true;
4949 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004950 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004951 if (lastTask != task) {
4952 lastTask = task;
4953 pw.print("TASK "); pw.print(lastTask.affinity);
4954 pw.print(" id="); pw.print(lastTask.taskId);
4955 pw.print(" userId="); pw.println(lastTask.userId);
4956 if (dumpAll) {
4957 lastTask.dump(pw, " ");
4958 }
4959 }
4960 }
4961 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4962 }
4963 return true;
4964 }
4965
4966 /**
4967 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4968 * there is a thread associated with the activity.
4969 */
4970 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4971 final ActivityRecord r, String[] args, boolean dumpAll) {
4972 String innerPrefix = prefix + " ";
4973 synchronized (mGlobalLock) {
4974 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4975 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4976 pw.print(" pid=");
4977 if (r.hasProcess()) pw.println(r.app.getPid());
4978 else pw.println("(not running)");
4979 if (dumpAll) {
4980 r.dump(pw, innerPrefix);
4981 }
4982 }
4983 if (r.attachedToProcess()) {
4984 // flush anything that is already in the PrintWriter since the thread is going
4985 // to write to the file descriptor directly
4986 pw.flush();
4987 try {
4988 TransferPipe tp = new TransferPipe();
4989 try {
4990 r.app.getThread().dumpActivity(tp.getWriteFd(),
4991 r.appToken, innerPrefix, args);
4992 tp.go(fd);
4993 } finally {
4994 tp.kill();
4995 }
4996 } catch (IOException e) {
4997 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4998 } catch (RemoteException e) {
4999 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5000 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005001 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005002 }
5003
sanryhuang498e77e2018-12-06 14:57:01 +08005004 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5005 boolean testPssMode) {
5006 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5007 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5008 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005009 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005010 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5011 st.toString());
5012 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005013 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5014 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5015 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005016 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5017 testPssMode);
5018 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005019 }
5020
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005021 int getCurrentUserId() {
5022 return mAmInternal.getCurrentUserId();
5023 }
5024
5025 private void enforceNotIsolatedCaller(String caller) {
5026 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5027 throw new SecurityException("Isolated process not allowed to call " + caller);
5028 }
5029 }
5030
Wale Ogunwalef6733932018-06-27 05:14:34 -07005031 public Configuration getConfiguration() {
5032 Configuration ci;
5033 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005034 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005035 ci.userSetLocale = false;
5036 }
5037 return ci;
5038 }
5039
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005040 /**
5041 * Current global configuration information. Contains general settings for the entire system,
5042 * also corresponds to the merged configuration of the default display.
5043 */
5044 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005045 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005046 }
5047
5048 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5049 boolean initLocale) {
5050 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5051 }
5052
5053 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5054 boolean initLocale, boolean deferResume) {
5055 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5056 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5057 UserHandle.USER_NULL, deferResume);
5058 }
5059
Wale Ogunwale59507092018-10-29 09:00:30 -07005060 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005061 final long origId = Binder.clearCallingIdentity();
5062 try {
5063 synchronized (mGlobalLock) {
5064 updateConfigurationLocked(values, null, false, true, userId,
5065 false /* deferResume */);
5066 }
5067 } finally {
5068 Binder.restoreCallingIdentity(origId);
5069 }
5070 }
5071
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005072 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5073 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5074 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5075 deferResume, null /* result */);
5076 }
5077
5078 /**
5079 * Do either or both things: (1) change the current configuration, and (2)
5080 * make sure the given activity is running with the (now) current
5081 * configuration. Returns true if the activity has been left running, or
5082 * false if <var>starting</var> is being destroyed to match the new
5083 * configuration.
5084 *
5085 * @param userId is only used when persistent parameter is set to true to persist configuration
5086 * for that particular user
5087 */
5088 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5089 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5090 ActivityTaskManagerService.UpdateConfigurationResult result) {
5091 int changes = 0;
5092 boolean kept = true;
5093
5094 if (mWindowManager != null) {
5095 mWindowManager.deferSurfaceLayout();
5096 }
5097 try {
5098 if (values != null) {
5099 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5100 deferResume);
5101 }
5102
5103 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5104 } finally {
5105 if (mWindowManager != null) {
5106 mWindowManager.continueSurfaceLayout();
5107 }
5108 }
5109
5110 if (result != null) {
5111 result.changes = changes;
5112 result.activityRelaunched = !kept;
5113 }
5114 return kept;
5115 }
5116
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005117 /** Update default (global) configuration and notify listeners about changes. */
5118 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5119 boolean persistent, int userId, boolean deferResume) {
5120 mTempConfig.setTo(getGlobalConfiguration());
5121 final int changes = mTempConfig.updateFrom(values);
5122 if (changes == 0) {
5123 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5124 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5125 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5126 // (even if there are no actual changes) to unfreeze the window.
5127 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5128 return 0;
5129 }
5130
5131 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5132 "Updating global configuration to: " + values);
5133
5134 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5135 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5136 values.colorMode,
5137 values.densityDpi,
5138 values.fontScale,
5139 values.hardKeyboardHidden,
5140 values.keyboard,
5141 values.keyboardHidden,
5142 values.mcc,
5143 values.mnc,
5144 values.navigation,
5145 values.navigationHidden,
5146 values.orientation,
5147 values.screenHeightDp,
5148 values.screenLayout,
5149 values.screenWidthDp,
5150 values.smallestScreenWidthDp,
5151 values.touchscreen,
5152 values.uiMode);
5153
5154
5155 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5156 final LocaleList locales = values.getLocales();
5157 int bestLocaleIndex = 0;
5158 if (locales.size() > 1) {
5159 if (mSupportedSystemLocales == null) {
5160 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5161 }
5162 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5163 }
5164 SystemProperties.set("persist.sys.locale",
5165 locales.get(bestLocaleIndex).toLanguageTag());
5166 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005167
5168 final Message m = PooledLambda.obtainMessage(
5169 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5170 locales.get(bestLocaleIndex));
5171 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005172 }
5173
Yunfan Chen75157d72018-07-27 14:47:21 +09005174 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005175
5176 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005177 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005178
5179 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5180 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005181 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005182
5183 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005184 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005185
5186 AttributeCache ac = AttributeCache.instance();
5187 if (ac != null) {
5188 ac.updateConfiguration(mTempConfig);
5189 }
5190
5191 // Make sure all resources in our process are updated right now, so that anyone who is going
5192 // to retrieve resource values after we return will be sure to get the new ones. This is
5193 // especially important during boot, where the first config change needs to guarantee all
5194 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005195 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005196
5197 // We need another copy of global config because we're scheduling some calls instead of
5198 // running them in place. We need to be sure that object we send will be handled unchanged.
5199 final Configuration configCopy = new Configuration(mTempConfig);
5200 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005201 final Message msg = PooledLambda.obtainMessage(
5202 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5203 this, userId, configCopy);
5204 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205 }
5206
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005207 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5208 for (int i = pidMap.size() - 1; i >= 0; i--) {
5209 final int pid = pidMap.keyAt(i);
5210 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005211 if (DEBUG_CONFIGURATION) {
5212 Slog.v(TAG_CONFIGURATION, "Update process config of "
5213 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005214 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005215 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216 }
5217
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005218 final Message msg = PooledLambda.obtainMessage(
5219 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5220 mAmInternal, changes, initLocale);
5221 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005222
5223 // Override configuration of the default display duplicates global config, so we need to
5224 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005225 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005226 DEFAULT_DISPLAY);
5227
5228 return changes;
5229 }
5230
5231 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5232 boolean deferResume, int displayId) {
5233 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5234 displayId, null /* result */);
5235 }
5236
5237 /**
5238 * Updates override configuration specific for the selected display. If no config is provided,
5239 * new one will be computed in WM based on current display info.
5240 */
5241 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5242 ActivityRecord starting, boolean deferResume, int displayId,
5243 ActivityTaskManagerService.UpdateConfigurationResult result) {
5244 int changes = 0;
5245 boolean kept = true;
5246
5247 if (mWindowManager != null) {
5248 mWindowManager.deferSurfaceLayout();
5249 }
5250 try {
5251 if (values != null) {
5252 if (displayId == DEFAULT_DISPLAY) {
5253 // Override configuration of the default display duplicates global config, so
5254 // we're calling global config update instead for default display. It will also
5255 // apply the correct override config.
5256 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5257 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5258 } else {
5259 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5260 }
5261 }
5262
5263 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5264 } finally {
5265 if (mWindowManager != null) {
5266 mWindowManager.continueSurfaceLayout();
5267 }
5268 }
5269
5270 if (result != null) {
5271 result.changes = changes;
5272 result.activityRelaunched = !kept;
5273 }
5274 return kept;
5275 }
5276
5277 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5278 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005279 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005280 final int changes = mTempConfig.updateFrom(values);
5281 if (changes != 0) {
5282 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5283 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005284 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005285
5286 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5287 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005288 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005289
Wale Ogunwale5c918702018-10-18 11:06:33 -07005290 // Post message to start process to avoid possible deadlock of calling into AMS with
5291 // the ATMS lock held.
5292 final Message msg = PooledLambda.obtainMessage(
5293 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005294 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005295 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005296 }
5297 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005298 return changes;
5299 }
5300
Wale Ogunwalef6733932018-06-27 05:14:34 -07005301 private void updateEventDispatchingLocked(boolean booted) {
5302 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5303 }
5304
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005305 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5306 final ContentResolver resolver = mContext.getContentResolver();
5307 Settings.System.putConfigurationForUser(resolver, config, userId);
5308 }
5309
5310 private void sendLocaleToMountDaemonMsg(Locale l) {
5311 try {
5312 IBinder service = ServiceManager.getService("mount");
5313 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5314 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5315 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5316 } catch (RemoteException e) {
5317 Log.e(TAG, "Error storing locale for decryption UI", e);
5318 }
5319 }
5320
Alison Cichowlas3e340502018-08-07 17:15:01 -04005321 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5322 mStartActivitySources.remove(permissionToken);
5323 mExpiredStartAsCallerTokens.add(permissionToken);
5324 }
5325
5326 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5327 mExpiredStartAsCallerTokens.remove(permissionToken);
5328 }
5329
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005330 boolean isActivityStartsLoggingEnabled() {
5331 return mAmInternal.isActivityStartsLoggingEnabled();
5332 }
5333
Michal Karpinski8596ded2018-11-14 14:43:48 +00005334 boolean isBackgroundActivityStartsEnabled() {
5335 return mAmInternal.isBackgroundActivityStartsEnabled();
5336 }
5337
Ricky Waiaca8a772019-04-04 16:01:06 +01005338 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5339 if (packageName == null) {
5340 return false;
5341 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005342 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5343 }
5344
Wale Ogunwalef6733932018-06-27 05:14:34 -07005345 void enableScreenAfterBoot(boolean booted) {
5346 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5347 SystemClock.uptimeMillis());
5348 mWindowManager.enableScreenAfterBoot();
5349
5350 synchronized (mGlobalLock) {
5351 updateEventDispatchingLocked(booted);
5352 }
5353 }
5354
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005355 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5356 if (r == null || !r.hasProcess()) {
5357 return KEY_DISPATCHING_TIMEOUT_MS;
5358 }
5359 return getInputDispatchingTimeoutLocked(r.app);
5360 }
5361
5362 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005363 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005364 }
5365
Wale Ogunwalef6733932018-06-27 05:14:34 -07005366 /**
5367 * Decide based on the configuration whether we should show the ANR,
5368 * crash, etc dialogs. The idea is that if there is no affordance to
5369 * press the on-screen buttons, or the user experience would be more
5370 * greatly impacted than the crash itself, we shouldn't show the dialog.
5371 *
5372 * A thought: SystemUI might also want to get told about this, the Power
5373 * dialog / global actions also might want different behaviors.
5374 */
5375 private void updateShouldShowDialogsLocked(Configuration config) {
5376 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5377 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5378 && config.navigation == Configuration.NAVIGATION_NONAV);
5379 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5380 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5381 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5382 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5383 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5384 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5385 HIDE_ERROR_DIALOGS, 0) != 0;
5386 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5387 }
5388
5389 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5390 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5391 FONT_SCALE, 1.0f, userId);
5392
5393 synchronized (this) {
5394 if (getGlobalConfiguration().fontScale == scaleFactor) {
5395 return;
5396 }
5397
5398 final Configuration configuration
5399 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5400 configuration.fontScale = scaleFactor;
5401 updatePersistentConfiguration(configuration, userId);
5402 }
5403 }
5404
5405 // Actually is sleeping or shutting down or whatever else in the future
5406 // is an inactive state.
5407 boolean isSleepingOrShuttingDownLocked() {
5408 return isSleepingLocked() || mShuttingDown;
5409 }
5410
5411 boolean isSleepingLocked() {
5412 return mSleeping;
5413 }
5414
Riddle Hsu16567132018-08-16 21:37:47 +08005415 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005416 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005417 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005418 if (task.isActivityTypeStandard()) {
5419 if (mCurAppTimeTracker != r.appTimeTracker) {
5420 // We are switching app tracking. Complete the current one.
5421 if (mCurAppTimeTracker != null) {
5422 mCurAppTimeTracker.stop();
5423 mH.obtainMessage(
5424 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005425 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005426 mCurAppTimeTracker = null;
5427 }
5428 if (r.appTimeTracker != null) {
5429 mCurAppTimeTracker = r.appTimeTracker;
5430 startTimeTrackingFocusedActivityLocked();
5431 }
5432 } else {
5433 startTimeTrackingFocusedActivityLocked();
5434 }
5435 } else {
5436 r.appTimeTracker = null;
5437 }
5438 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5439 // TODO: Probably not, because we don't want to resume voice on switching
5440 // back to this activity
5441 if (task.voiceInteractor != null) {
5442 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5443 } else {
5444 finishRunningVoiceLocked();
5445
5446 if (mLastResumedActivity != null) {
5447 final IVoiceInteractionSession session;
5448
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005449 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005450 if (lastResumedActivityTask != null
5451 && lastResumedActivityTask.voiceSession != null) {
5452 session = lastResumedActivityTask.voiceSession;
5453 } else {
5454 session = mLastResumedActivity.voiceSession;
5455 }
5456
5457 if (session != null) {
5458 // We had been in a voice interaction session, but now focused has
5459 // move to something different. Just finish the session, we can't
5460 // return to it and retain the proper state and synchronization with
5461 // the voice interaction service.
5462 finishVoiceTask(session);
5463 }
5464 }
5465 }
5466
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005467 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5468 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005469 }
5470 updateResumedAppTrace(r);
5471 mLastResumedActivity = r;
5472
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005473 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005474
5475 applyUpdateLockStateLocked(r);
5476 applyUpdateVrModeLocked(r);
5477
5478 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005479 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005480 r == null ? "NULL" : r.shortComponentName,
5481 reason);
5482 }
5483
5484 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5485 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005486 final ActivityTaskManagerInternal.SleepToken token =
5487 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005488 updateSleepIfNeededLocked();
5489 return token;
5490 }
5491 }
5492
5493 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005494 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005495 final boolean wasSleeping = mSleeping;
5496 boolean updateOomAdj = false;
5497
5498 if (!shouldSleep) {
5499 // If wasSleeping is true, we need to wake up activity manager state from when
5500 // we started sleeping. In either case, we need to apply the sleep tokens, which
5501 // will wake up stacks or put them to sleep as appropriate.
5502 if (wasSleeping) {
5503 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005504 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5505 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005506 startTimeTrackingFocusedActivityLocked();
5507 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5508 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5509 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005510 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005511 if (wasSleeping) {
5512 updateOomAdj = true;
5513 }
5514 } else if (!mSleeping && shouldSleep) {
5515 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005516 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5517 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005518 if (mCurAppTimeTracker != null) {
5519 mCurAppTimeTracker.stop();
5520 }
5521 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5522 mStackSupervisor.goingToSleepLocked();
5523 updateResumedAppTrace(null /* resumed */);
5524 updateOomAdj = true;
5525 }
5526 if (updateOomAdj) {
5527 mH.post(mAmInternal::updateOomAdj);
5528 }
5529 }
5530
5531 void updateOomAdj() {
5532 mH.post(mAmInternal::updateOomAdj);
5533 }
5534
Wale Ogunwale53783742018-09-16 10:21:51 -07005535 void updateCpuStats() {
5536 mH.post(mAmInternal::updateCpuStats);
5537 }
5538
Hui Yu03d12402018-12-06 18:00:37 -08005539 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5540 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005541 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5542 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005543 mH.sendMessage(m);
5544 }
5545
Hui Yu03d12402018-12-06 18:00:37 -08005546 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005547 ComponentName taskRoot = null;
5548 final TaskRecord task = activity.getTaskRecord();
5549 if (task != null) {
5550 final ActivityRecord rootActivity = task.getRootActivity();
5551 if (rootActivity != null) {
5552 taskRoot = rootActivity.mActivityComponent;
5553 }
5554 }
5555
Hui Yu03d12402018-12-06 18:00:37 -08005556 final Message m = PooledLambda.obtainMessage(
5557 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005558 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005559 mH.sendMessage(m);
5560 }
5561
Wale Ogunwale53783742018-09-16 10:21:51 -07005562 void setBooting(boolean booting) {
5563 mAmInternal.setBooting(booting);
5564 }
5565
5566 boolean isBooting() {
5567 return mAmInternal.isBooting();
5568 }
5569
5570 void setBooted(boolean booted) {
5571 mAmInternal.setBooted(booted);
5572 }
5573
5574 boolean isBooted() {
5575 return mAmInternal.isBooted();
5576 }
5577
5578 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5579 mH.post(() -> {
5580 if (finishBooting) {
5581 mAmInternal.finishBooting();
5582 }
5583 if (enableScreen) {
5584 mInternal.enableScreenAfterBoot(isBooted());
5585 }
5586 });
5587 }
5588
5589 void setHeavyWeightProcess(ActivityRecord root) {
5590 mHeavyWeightProcess = root.app;
5591 final Message m = PooledLambda.obtainMessage(
5592 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005593 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005594 mH.sendMessage(m);
5595 }
5596
5597 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5598 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5599 return;
5600 }
5601
5602 mHeavyWeightProcess = null;
5603 final Message m = PooledLambda.obtainMessage(
5604 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5605 proc.mUserId);
5606 mH.sendMessage(m);
5607 }
5608
5609 private void cancelHeavyWeightProcessNotification(int userId) {
5610 final INotificationManager inm = NotificationManager.getService();
5611 if (inm == null) {
5612 return;
5613 }
5614 try {
5615 inm.cancelNotificationWithTag("android", null,
5616 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5617 } catch (RuntimeException e) {
5618 Slog.w(TAG, "Error canceling notification for service", e);
5619 } catch (RemoteException e) {
5620 }
5621
5622 }
5623
5624 private void postHeavyWeightProcessNotification(
5625 WindowProcessController proc, Intent intent, int userId) {
5626 if (proc == null) {
5627 return;
5628 }
5629
5630 final INotificationManager inm = NotificationManager.getService();
5631 if (inm == null) {
5632 return;
5633 }
5634
5635 try {
5636 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5637 String text = mContext.getString(R.string.heavy_weight_notification,
5638 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5639 Notification notification =
5640 new Notification.Builder(context,
5641 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5642 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5643 .setWhen(0)
5644 .setOngoing(true)
5645 .setTicker(text)
5646 .setColor(mContext.getColor(
5647 com.android.internal.R.color.system_notification_accent_color))
5648 .setContentTitle(text)
5649 .setContentText(
5650 mContext.getText(R.string.heavy_weight_notification_detail))
5651 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5652 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5653 new UserHandle(userId)))
5654 .build();
5655 try {
5656 inm.enqueueNotificationWithTag("android", "android", null,
5657 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5658 } catch (RuntimeException e) {
5659 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5660 } catch (RemoteException e) {
5661 }
5662 } catch (PackageManager.NameNotFoundException e) {
5663 Slog.w(TAG, "Unable to create context for heavy notification", e);
5664 }
5665
5666 }
5667
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005668 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5669 IBinder token, String resultWho, int requestCode, Intent[] intents,
5670 String[] resolvedTypes, int flags, Bundle bOptions) {
5671
5672 ActivityRecord activity = null;
5673 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5674 activity = ActivityRecord.isInStackLocked(token);
5675 if (activity == null) {
5676 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5677 return null;
5678 }
5679 if (activity.finishing) {
5680 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5681 return null;
5682 }
5683 }
5684
5685 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5686 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5687 bOptions);
5688 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5689 if (noCreate) {
5690 return rec;
5691 }
5692 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5693 if (activity.pendingResults == null) {
5694 activity.pendingResults = new HashSet<>();
5695 }
5696 activity.pendingResults.add(rec.ref);
5697 }
5698 return rec;
5699 }
5700
Andrii Kulian52d255c2018-07-13 11:32:19 -07005701 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005702 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005703 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005704 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5705 mCurAppTimeTracker.start(resumedActivity.packageName);
5706 }
5707 }
5708
5709 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5710 if (mTracedResumedActivity != null) {
5711 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5712 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5713 }
5714 if (resumed != null) {
5715 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5716 constructResumedTraceName(resumed.packageName), 0);
5717 }
5718 mTracedResumedActivity = resumed;
5719 }
5720
5721 private String constructResumedTraceName(String packageName) {
5722 return "focused app: " + packageName;
5723 }
5724
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005725 /** Applies latest configuration and/or visibility updates if needed. */
5726 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5727 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005728 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005729 // mainStack is null during startup.
5730 if (mainStack != null) {
5731 if (changes != 0 && starting == null) {
5732 // If the configuration changed, and the caller is not already
5733 // in the process of starting an activity, then find the top
5734 // activity to check if its configuration needs to change.
5735 starting = mainStack.topRunningActivityLocked();
5736 }
5737
5738 if (starting != null) {
5739 kept = starting.ensureActivityConfiguration(changes,
5740 false /* preserveWindow */);
5741 // And we need to make sure at this point that all other activities
5742 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005743 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005744 !PRESERVE_WINDOWS);
5745 }
5746 }
5747
5748 return kept;
5749 }
5750
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005751 void scheduleAppGcsLocked() {
5752 mH.post(() -> mAmInternal.scheduleAppGcs());
5753 }
5754
Wale Ogunwale53783742018-09-16 10:21:51 -07005755 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5756 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5757 }
5758
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005759 /**
5760 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5761 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5762 * on demand.
5763 */
5764 IPackageManager getPackageManager() {
5765 return AppGlobals.getPackageManager();
5766 }
5767
5768 PackageManagerInternal getPackageManagerInternalLocked() {
5769 if (mPmInternal == null) {
5770 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5771 }
5772 return mPmInternal;
5773 }
5774
Wale Ogunwale008163e2018-07-23 23:11:08 -07005775 AppWarnings getAppWarningsLocked() {
5776 return mAppWarnings;
5777 }
5778
Wale Ogunwale214f3482018-10-04 11:00:47 -07005779 Intent getHomeIntent() {
5780 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5781 intent.setComponent(mTopComponent);
5782 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5783 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5784 intent.addCategory(Intent.CATEGORY_HOME);
5785 }
5786 return intent;
5787 }
5788
Chilun2ef71f72018-11-16 17:57:15 +08005789 /**
5790 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5791 * activities.
5792 *
5793 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5794 * component defined in config_secondaryHomeComponent.
5795 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5796 */
5797 Intent getSecondaryHomeIntent(String preferredPackage) {
5798 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5799 if (preferredPackage == null) {
5800 // Using the component stored in config if no package name.
5801 final String secondaryHomeComponent = mContext.getResources().getString(
5802 com.android.internal.R.string.config_secondaryHomeComponent);
5803 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5804 } else {
5805 intent.setPackage(preferredPackage);
5806 }
5807 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5808 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5809 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5810 }
5811 return intent;
5812 }
5813
Wale Ogunwale214f3482018-10-04 11:00:47 -07005814 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5815 if (info == null) return null;
5816 ApplicationInfo newInfo = new ApplicationInfo(info);
5817 newInfo.initForUser(userId);
5818 return newInfo;
5819 }
5820
Wale Ogunwale9c103022018-10-18 07:44:54 -07005821 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005822 if (uid == SYSTEM_UID) {
5823 // The system gets to run in any process. If there are multiple processes with the same
5824 // uid, just pick the first (this should never happen).
5825 final SparseArray<WindowProcessController> procs =
5826 mProcessNames.getMap().get(processName);
5827 if (procs == null) return null;
5828 final int procCount = procs.size();
5829 for (int i = 0; i < procCount; i++) {
5830 final int procUid = procs.keyAt(i);
5831 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5832 // Don't use an app process or different user process for system component.
5833 continue;
5834 }
5835 return procs.valueAt(i);
5836 }
5837 }
5838
5839 return mProcessNames.get(processName, uid);
5840 }
5841
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005842 WindowProcessController getProcessController(IApplicationThread thread) {
5843 if (thread == null) {
5844 return null;
5845 }
5846
5847 final IBinder threadBinder = thread.asBinder();
5848 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5849 for (int i = pmap.size()-1; i >= 0; i--) {
5850 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5851 for (int j = procs.size() - 1; j >= 0; j--) {
5852 final WindowProcessController proc = procs.valueAt(j);
5853 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5854 return proc;
5855 }
5856 }
5857 }
5858
5859 return null;
5860 }
5861
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005862 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005863 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005864 if (proc == null) return null;
5865 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5866 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005867 }
5868 return null;
5869 }
5870
Riddle Hsua0536432019-02-16 00:38:59 +08005871 int getUidState(int uid) {
5872 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005873 }
5874
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005875 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005876 // A uid is considered to be foreground if it has a visible non-toast window.
5877 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005878 }
5879
Ricky Wai96f5c352019-04-10 18:40:17 +01005880 boolean isDeviceOwner(int uid) {
5881 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005882 }
5883
Ricky Wai96f5c352019-04-10 18:40:17 +01005884 void setDeviceOwnerUid(int uid) {
5885 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005886 }
5887
Wale Ogunwale9de19442018-10-18 19:05:03 -07005888 /**
5889 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5890 * the whitelist
5891 */
5892 String getPendingTempWhitelistTagForUidLocked(int uid) {
5893 return mPendingTempWhitelist.get(uid);
5894 }
5895
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005896 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5897 if (true || Build.IS_USER) {
5898 return;
5899 }
5900
5901 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5902 StrictMode.allowThreadDiskWrites();
5903 try {
5904 File tracesDir = new File("/data/anr");
5905 File tracesFile = null;
5906 try {
5907 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5908
5909 StringBuilder sb = new StringBuilder();
5910 Time tobj = new Time();
5911 tobj.set(System.currentTimeMillis());
5912 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5913 sb.append(": ");
5914 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5915 sb.append(" since ");
5916 sb.append(msg);
5917 FileOutputStream fos = new FileOutputStream(tracesFile);
5918 fos.write(sb.toString().getBytes());
5919 if (app == null) {
5920 fos.write("\n*** No application process!".getBytes());
5921 }
5922 fos.close();
5923 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5924 } catch (IOException e) {
5925 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5926 return;
5927 }
5928
5929 if (app != null && app.getPid() > 0) {
5930 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5931 firstPids.add(app.getPid());
5932 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5933 }
5934
5935 File lastTracesFile = null;
5936 File curTracesFile = null;
5937 for (int i=9; i>=0; i--) {
5938 String name = String.format(Locale.US, "slow%02d.txt", i);
5939 curTracesFile = new File(tracesDir, name);
5940 if (curTracesFile.exists()) {
5941 if (lastTracesFile != null) {
5942 curTracesFile.renameTo(lastTracesFile);
5943 } else {
5944 curTracesFile.delete();
5945 }
5946 }
5947 lastTracesFile = curTracesFile;
5948 }
5949 tracesFile.renameTo(curTracesFile);
5950 } finally {
5951 StrictMode.setThreadPolicy(oldPolicy);
5952 }
5953 }
5954
Michal Karpinskida34cd42019-04-02 19:46:52 +01005955 boolean isAssociatedCompanionApp(int userId, int uid) {
5956 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5957 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005958 return false;
5959 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005960 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005961 }
5962
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005963 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005964 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005965
5966
Wale Ogunwale98875612018-10-12 07:53:02 -07005967 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5968 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005969
Riddle Hsud93a6c42018-11-29 21:50:06 +08005970 H(Looper looper) {
5971 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005972 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005973
5974 @Override
5975 public void handleMessage(Message msg) {
5976 switch (msg.what) {
5977 case REPORT_TIME_TRACKER_MSG: {
5978 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5979 tracker.deliverResult(mContext);
5980 } break;
5981 }
5982 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005983 }
5984
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005985 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005986 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005987
5988 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005989 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005990 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005991
5992 @Override
5993 public void handleMessage(Message msg) {
5994 switch (msg.what) {
5995 case DISMISS_DIALOG_UI_MSG: {
5996 final Dialog d = (Dialog) msg.obj;
5997 d.dismiss();
5998 break;
5999 }
6000 }
6001 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006002 }
6003
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006004 final class LocalService extends ActivityTaskManagerInternal {
6005 @Override
6006 public SleepToken acquireSleepToken(String tag, int displayId) {
6007 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006008 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006009 }
6010
6011 @Override
6012 public ComponentName getHomeActivityForUser(int userId) {
6013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006014 final ActivityRecord homeActivity =
6015 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006016 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006017 }
6018 }
6019
6020 @Override
6021 public void onLocalVoiceInteractionStarted(IBinder activity,
6022 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6023 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006024 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006025 }
6026 }
6027
6028 @Override
6029 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6030 synchronized (mGlobalLock) {
6031 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6032 reasons, timestamp);
6033 }
6034 }
6035
6036 @Override
6037 public void notifyAppTransitionFinished() {
6038 synchronized (mGlobalLock) {
6039 mStackSupervisor.notifyAppTransitionDone();
6040 }
6041 }
6042
6043 @Override
6044 public void notifyAppTransitionCancelled() {
6045 synchronized (mGlobalLock) {
6046 mStackSupervisor.notifyAppTransitionDone();
6047 }
6048 }
6049
6050 @Override
6051 public List<IBinder> getTopVisibleActivities() {
6052 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006053 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006054 }
6055 }
6056
6057 @Override
6058 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6059 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006060 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
6062 }
6063
6064 @Override
6065 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6066 Bundle bOptions) {
6067 Preconditions.checkNotNull(intents, "intents");
6068 final String[] resolvedTypes = new String[intents.length];
6069
6070 // UID of the package on user userId.
6071 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6072 // packageUid may not be initialized.
6073 int packageUid = 0;
6074 final long ident = Binder.clearCallingIdentity();
6075
6076 try {
6077 for (int i = 0; i < intents.length; i++) {
6078 resolvedTypes[i] =
6079 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6080 }
6081
6082 packageUid = AppGlobals.getPackageManager().getPackageUid(
6083 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6084 } catch (RemoteException e) {
6085 // Shouldn't happen.
6086 } finally {
6087 Binder.restoreCallingIdentity(ident);
6088 }
6089
Riddle Hsu591bf612019-02-14 17:55:31 +08006090 return getActivityStartController().startActivitiesInPackage(
6091 packageUid, packageName,
6092 intents, resolvedTypes, null /* resultTo */,
6093 SafeActivityOptions.fromBundle(bOptions), userId,
6094 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6095 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006096 }
6097
6098 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006099 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6100 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6101 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6102 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006103 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006104 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006105 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6106 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6107 userId, validateIncomingUser, originatingPendingIntent,
6108 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006109 }
6110 }
6111
6112 @Override
6113 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6114 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6115 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6116 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006117 PendingIntentRecord originatingPendingIntent,
6118 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006119 synchronized (mGlobalLock) {
6120 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6121 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6122 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006123 validateIncomingUser, originatingPendingIntent,
6124 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006125 }
6126 }
6127
6128 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006129 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6130 Intent intent, Bundle options, int userId) {
6131 return ActivityTaskManagerService.this.startActivityAsUser(
6132 caller, callerPacakge, intent,
6133 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6134 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6135 false /*validateIncomingUser*/);
6136 }
6137
6138 @Override
lumark588a3e82018-07-20 18:53:54 +08006139 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006140 synchronized (mGlobalLock) {
6141
6142 // We might change the visibilities here, so prepare an empty app transition which
6143 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006144 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006145 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006146 if (activityDisplay == null) {
6147 return;
6148 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006149 final DisplayContent dc = activityDisplay.mDisplayContent;
6150 final boolean wasTransitionSet =
6151 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006152 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006153 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006154 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006155 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006156
6157 // If there was a transition set already we don't want to interfere with it as we
6158 // might be starting it too early.
6159 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006160 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006161 }
6162 }
6163 if (callback != null) {
6164 callback.run();
6165 }
6166 }
6167
6168 @Override
6169 public void notifyKeyguardTrustedChanged() {
6170 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006171 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006172 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006173 }
6174 }
6175 }
6176
6177 /**
6178 * Called after virtual display Id is updated by
6179 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6180 * {@param vrVr2dDisplayId}.
6181 */
6182 @Override
6183 public void setVr2dDisplayId(int vr2dDisplayId) {
6184 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6185 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006186 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006187 }
6188 }
6189
6190 @Override
6191 public void setFocusedActivity(IBinder token) {
6192 synchronized (mGlobalLock) {
6193 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6194 if (r == null) {
6195 throw new IllegalArgumentException(
6196 "setFocusedActivity: No activity record matching token=" + token);
6197 }
Louis Chang19443452018-10-09 12:10:21 +08006198 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006199 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006200 }
6201 }
6202 }
6203
6204 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006205 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006206 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006207 }
6208
6209 @Override
6210 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006211 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006212 }
6213
6214 @Override
6215 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006216 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006217 }
6218
6219 @Override
6220 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6221 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6222 }
6223
6224 @Override
6225 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006226 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006227 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006228
6229 @Override
6230 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6231 synchronized (mGlobalLock) {
6232 mActiveVoiceInteractionServiceComponent = component;
6233 }
6234 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006235
6236 @Override
6237 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6238 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6239 return;
6240 }
6241 synchronized (mGlobalLock) {
6242 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6243 if (types == null) {
6244 if (uid < 0) {
6245 return;
6246 }
6247 types = new ArrayMap<>();
6248 mAllowAppSwitchUids.put(userId, types);
6249 }
6250 if (uid < 0) {
6251 types.remove(type);
6252 } else {
6253 types.put(type, uid);
6254 }
6255 }
6256 }
6257
6258 @Override
6259 public void onUserStopped(int userId) {
6260 synchronized (mGlobalLock) {
6261 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6262 mAllowAppSwitchUids.remove(userId);
6263 }
6264 }
6265
6266 @Override
6267 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6268 synchronized (mGlobalLock) {
6269 return ActivityTaskManagerService.this.isGetTasksAllowed(
6270 caller, callingPid, callingUid);
6271 }
6272 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006273
Riddle Hsua0536432019-02-16 00:38:59 +08006274 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006275 @Override
6276 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006277 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006278 mProcessNames.put(proc.mName, proc.mUid, proc);
6279 }
6280 }
6281
Riddle Hsua0536432019-02-16 00:38:59 +08006282 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006283 @Override
6284 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006285 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006286 mProcessNames.remove(name, uid);
6287 }
6288 }
6289
Riddle Hsua0536432019-02-16 00:38:59 +08006290 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006291 @Override
6292 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006293 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006294 if (proc == mHomeProcess) {
6295 mHomeProcess = null;
6296 }
6297 if (proc == mPreviousProcess) {
6298 mPreviousProcess = null;
6299 }
6300 }
6301 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006302
Riddle Hsua0536432019-02-16 00:38:59 +08006303 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006304 @Override
6305 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006306 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006307 return mTopProcessState;
6308 }
6309 }
6310
Riddle Hsua0536432019-02-16 00:38:59 +08006311 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006312 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006313 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006314 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006315 return proc == mHeavyWeightProcess;
6316 }
6317 }
6318
Riddle Hsua0536432019-02-16 00:38:59 +08006319 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006320 @Override
6321 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006322 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006323 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6324 }
6325 }
6326
6327 @Override
6328 public void finishHeavyWeightApp() {
6329 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006330 if (mHeavyWeightProcess != null) {
6331 mHeavyWeightProcess.finishActivities();
6332 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006333 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6334 mHeavyWeightProcess);
6335 }
6336 }
6337
Riddle Hsua0536432019-02-16 00:38:59 +08006338 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006339 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006340 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006341 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006342 return isSleepingLocked();
6343 }
6344 }
6345
6346 @Override
6347 public boolean isShuttingDown() {
6348 synchronized (mGlobalLock) {
6349 return mShuttingDown;
6350 }
6351 }
6352
6353 @Override
6354 public boolean shuttingDown(boolean booted, int timeout) {
6355 synchronized (mGlobalLock) {
6356 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006357 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006358 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006359 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006360 return mStackSupervisor.shutdownLocked(timeout);
6361 }
6362 }
6363
6364 @Override
6365 public void enableScreenAfterBoot(boolean booted) {
6366 synchronized (mGlobalLock) {
6367 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6368 SystemClock.uptimeMillis());
6369 mWindowManager.enableScreenAfterBoot();
6370 updateEventDispatchingLocked(booted);
6371 }
6372 }
6373
6374 @Override
6375 public boolean showStrictModeViolationDialog() {
6376 synchronized (mGlobalLock) {
6377 return mShowDialogs && !mSleeping && !mShuttingDown;
6378 }
6379 }
6380
6381 @Override
6382 public void showSystemReadyErrorDialogsIfNeeded() {
6383 synchronized (mGlobalLock) {
6384 try {
6385 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6386 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6387 + " data partition or your device will be unstable.");
6388 mUiHandler.post(() -> {
6389 if (mShowDialogs) {
6390 AlertDialog d = new BaseErrorDialog(mUiContext);
6391 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6392 d.setCancelable(false);
6393 d.setTitle(mUiContext.getText(R.string.android_system_label));
6394 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6395 d.setButton(DialogInterface.BUTTON_POSITIVE,
6396 mUiContext.getText(R.string.ok),
6397 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6398 d.show();
6399 }
6400 });
6401 }
6402 } catch (RemoteException e) {
6403 }
6404
6405 if (!Build.isBuildConsistent()) {
6406 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6407 mUiHandler.post(() -> {
6408 if (mShowDialogs) {
6409 AlertDialog d = new BaseErrorDialog(mUiContext);
6410 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6411 d.setCancelable(false);
6412 d.setTitle(mUiContext.getText(R.string.android_system_label));
6413 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6414 d.setButton(DialogInterface.BUTTON_POSITIVE,
6415 mUiContext.getText(R.string.ok),
6416 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6417 d.show();
6418 }
6419 });
6420 }
6421 }
6422 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006423
6424 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006425 public void onProcessMapped(int pid, WindowProcessController proc) {
6426 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006427 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006428 }
6429 }
6430
6431 @Override
6432 public void onProcessUnMapped(int pid) {
6433 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006434 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006435 }
6436 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006437
6438 @Override
6439 public void onPackageDataCleared(String name) {
6440 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006442 mAppWarnings.onPackageDataCleared(name);
6443 }
6444 }
6445
6446 @Override
6447 public void onPackageUninstalled(String name) {
6448 synchronized (mGlobalLock) {
6449 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006450 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006451 }
6452 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006453
6454 @Override
6455 public void onPackageAdded(String name, boolean replacing) {
6456 synchronized (mGlobalLock) {
6457 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6458 }
6459 }
6460
6461 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006462 public void onPackageReplaced(ApplicationInfo aInfo) {
6463 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006464 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006465 }
6466 }
6467
6468 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006469 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6470 synchronized (mGlobalLock) {
6471 return compatibilityInfoForPackageLocked(ai);
6472 }
6473 }
6474
Yunfan Chen75157d72018-07-27 14:47:21 +09006475 /**
6476 * Set the corresponding display information for the process global configuration. To be
6477 * called when we need to show IME on a different display.
6478 *
6479 * @param pid The process id associated with the IME window.
6480 * @param displayId The ID of the display showing the IME.
6481 */
6482 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006483 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006484 // Don't update process-level configuration for Multi-Client IME process since other
6485 // IMEs on other displays will also receive this configuration change due to IME
6486 // services use the same application config/context.
6487 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006488
Yunfan Chen75157d72018-07-27 14:47:21 +09006489 if (pid == MY_PID || pid < 0) {
6490 if (DEBUG_CONFIGURATION) {
6491 Slog.w(TAG,
6492 "Trying to update display configuration for system/invalid process.");
6493 }
6494 return;
6495 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006496 synchronized (mGlobalLock) {
6497 final ActivityDisplay activityDisplay =
6498 mRootActivityContainer.getActivityDisplay(displayId);
6499 if (activityDisplay == null) {
6500 // Call might come when display is not yet added or has been removed.
6501 if (DEBUG_CONFIGURATION) {
6502 Slog.w(TAG, "Trying to update display configuration for non-existing "
6503 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006504 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006505 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006506 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006507 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006508 if (process == null) {
6509 if (DEBUG_CONFIGURATION) {
6510 Slog.w(TAG, "Trying to update display configuration for invalid "
6511 + "process, pid=" + pid);
6512 }
6513 return;
6514 }
6515 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6516 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006517 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006518
6519 @Override
6520 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6521 int requestCode, int resultCode, Intent data) {
6522 synchronized (mGlobalLock) {
6523 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006524 if (r != null && r.getActivityStack() != null) {
6525 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6526 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006527 }
6528 }
6529 }
6530
6531 @Override
6532 public void clearPendingResultForActivity(IBinder activityToken,
6533 WeakReference<PendingIntentRecord> pir) {
6534 synchronized (mGlobalLock) {
6535 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6536 if (r != null && r.pendingResults != null) {
6537 r.pendingResults.remove(pir);
6538 }
6539 }
6540 }
6541
6542 @Override
6543 public IIntentSender getIntentSender(int type, String packageName,
6544 int callingUid, int userId, IBinder token, String resultWho,
6545 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6546 Bundle bOptions) {
6547 synchronized (mGlobalLock) {
6548 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6549 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6550 }
6551 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006552
6553 @Override
6554 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6555 synchronized (mGlobalLock) {
6556 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6557 if (r == null) {
6558 return null;
6559 }
6560 if (r.mServiceConnectionsHolder == null) {
6561 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6562 ActivityTaskManagerService.this, r);
6563 }
6564
6565 return r.mServiceConnectionsHolder;
6566 }
6567 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006568
6569 @Override
6570 public Intent getHomeIntent() {
6571 synchronized (mGlobalLock) {
6572 return ActivityTaskManagerService.this.getHomeIntent();
6573 }
6574 }
6575
6576 @Override
6577 public boolean startHomeActivity(int userId, String reason) {
6578 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006579 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006580 }
6581 }
6582
6583 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006584 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006585 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006586 synchronized (mGlobalLock) {
6587 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006588 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006589 }
Chilun8b1f1be2019-03-13 17:14:36 +08006590 }
6591
6592 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006593 public boolean startHomeOnAllDisplays(int userId, String reason) {
6594 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006595 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006596 }
6597 }
6598
Riddle Hsua0536432019-02-16 00:38:59 +08006599 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006600 @Override
6601 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006602 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006603 if (mFactoryTest == FACTORY_TEST_OFF) {
6604 return false;
6605 }
6606 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6607 && wpc.mName.equals(mTopComponent.getPackageName())) {
6608 return true;
6609 }
6610 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6611 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6612 }
6613 }
6614
6615 @Override
6616 public void updateTopComponentForFactoryTest() {
6617 synchronized (mGlobalLock) {
6618 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6619 return;
6620 }
6621 final ResolveInfo ri = mContext.getPackageManager()
6622 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6623 final CharSequence errorMsg;
6624 if (ri != null) {
6625 final ActivityInfo ai = ri.activityInfo;
6626 final ApplicationInfo app = ai.applicationInfo;
6627 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6628 mTopAction = Intent.ACTION_FACTORY_TEST;
6629 mTopData = null;
6630 mTopComponent = new ComponentName(app.packageName, ai.name);
6631 errorMsg = null;
6632 } else {
6633 errorMsg = mContext.getResources().getText(
6634 com.android.internal.R.string.factorytest_not_system);
6635 }
6636 } else {
6637 errorMsg = mContext.getResources().getText(
6638 com.android.internal.R.string.factorytest_no_action);
6639 }
6640 if (errorMsg == null) {
6641 return;
6642 }
6643
6644 mTopAction = null;
6645 mTopData = null;
6646 mTopComponent = null;
6647 mUiHandler.post(() -> {
6648 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6649 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006650 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006651 });
6652 }
6653 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006654
Riddle Hsua0536432019-02-16 00:38:59 +08006655 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006656 @Override
6657 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6658 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006659 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006660 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006661 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006662
6663 wpc.clearRecentTasks();
6664 wpc.clearActivities();
6665
6666 if (wpc.isInstrumenting()) {
6667 finishInstrumentationCallback.run();
6668 }
6669
Jorim Jaggid0752812018-10-16 16:07:20 +02006670 if (!restarting && hasVisibleActivities) {
6671 mWindowManager.deferSurfaceLayout();
6672 try {
6673 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6674 // If there was nothing to resume, and we are not already restarting
6675 // this process, but there is a visible activity that is hosted by the
6676 // process...then make sure all visible activities are running, taking
6677 // care of restarting this process.
6678 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6679 !PRESERVE_WINDOWS);
6680 }
6681 } finally {
6682 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006683 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006684 }
6685 }
6686 }
6687
6688 @Override
6689 public void closeSystemDialogs(String reason) {
6690 enforceNotIsolatedCaller("closeSystemDialogs");
6691
6692 final int pid = Binder.getCallingPid();
6693 final int uid = Binder.getCallingUid();
6694 final long origId = Binder.clearCallingIdentity();
6695 try {
6696 synchronized (mGlobalLock) {
6697 // Only allow this from foreground processes, so that background
6698 // applications can't abuse it to prevent system UI from being shown.
6699 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006700 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 if (!proc.isPerceptible()) {
6702 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6703 + " from background process " + proc);
6704 return;
6705 }
6706 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707 mWindowManager.closeSystemDialogs(reason);
6708
Wale Ogunwaled32da472018-11-16 07:19:28 -08006709 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006710 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006711 // Call into AM outside the synchronized block.
6712 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006713 } finally {
6714 Binder.restoreCallingIdentity(origId);
6715 }
6716 }
6717
6718 @Override
6719 public void cleanupDisabledPackageComponents(
6720 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6721 synchronized (mGlobalLock) {
6722 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006723 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006724 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006725 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006726 mStackSupervisor.scheduleIdleLocked();
6727 }
6728
6729 // Clean-up disabled tasks
6730 getRecentTasks().cleanupDisabledPackageTasksLocked(
6731 packageName, disabledClasses, userId);
6732 }
6733 }
6734
6735 @Override
6736 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6737 int userId) {
6738 synchronized (mGlobalLock) {
6739
6740 boolean didSomething =
6741 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006742 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 null, doit, evenPersistent, userId);
6744 return didSomething;
6745 }
6746 }
6747
6748 @Override
6749 public void resumeTopActivities(boolean scheduleIdle) {
6750 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006751 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006752 if (scheduleIdle) {
6753 mStackSupervisor.scheduleIdleLocked();
6754 }
6755 }
6756 }
6757
Riddle Hsua0536432019-02-16 00:38:59 +08006758 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 @Override
6760 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006761 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006762 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6763 }
6764 }
6765
Riddle Hsua0536432019-02-16 00:38:59 +08006766 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 @Override
6768 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006769 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006770 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006771 }
6772 }
6773
6774 @Override
6775 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6776 try {
6777 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6778 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6779 }
6780 } catch (RemoteException ex) {
6781 throw new SecurityException("Fail to check is caller a privileged app", ex);
6782 }
6783
6784 synchronized (mGlobalLock) {
6785 final long ident = Binder.clearCallingIdentity();
6786 try {
6787 if (mAmInternal.shouldConfirmCredentials(userId)) {
6788 if (mKeyguardController.isKeyguardLocked()) {
6789 // Showing launcher to avoid user entering credential twice.
6790 startHomeActivity(currentUserId, "notifyLockedProfile");
6791 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006792 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006793 }
6794 } finally {
6795 Binder.restoreCallingIdentity(ident);
6796 }
6797 }
6798 }
6799
6800 @Override
6801 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6802 mAmInternal.enforceCallingPermission(
6803 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6804
6805 synchronized (mGlobalLock) {
6806 final long ident = Binder.clearCallingIdentity();
6807 try {
6808 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6809 FLAG_ACTIVITY_TASK_ON_HOME);
6810 ActivityOptions activityOptions = options != null
6811 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006812 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006813 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006814 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006815 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006816 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006817 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6818 UserHandle.CURRENT);
6819 } finally {
6820 Binder.restoreCallingIdentity(ident);
6821 }
6822 }
6823 }
6824
6825 @Override
6826 public void writeActivitiesToProto(ProtoOutputStream proto) {
6827 synchronized (mGlobalLock) {
6828 // The output proto of "activity --proto activities"
6829 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006830 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006831 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6832 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006833 }
6834 }
6835
6836 @Override
6837 public void saveANRState(String reason) {
6838 synchronized (mGlobalLock) {
6839 final StringWriter sw = new StringWriter();
6840 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6841 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6842 if (reason != null) {
6843 pw.println(" Reason: " + reason);
6844 }
6845 pw.println();
6846 getActivityStartController().dump(pw, " ", null);
6847 pw.println();
6848 pw.println("-------------------------------------------------------------------------------");
6849 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6850 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6851 "" /* header */);
6852 pw.println();
6853 pw.close();
6854
6855 mLastANRState = sw.toString();
6856 }
6857 }
6858
6859 @Override
6860 public void clearSavedANRState() {
6861 synchronized (mGlobalLock) {
6862 mLastANRState = null;
6863 }
6864 }
6865
6866 @Override
6867 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6868 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6869 synchronized (mGlobalLock) {
6870 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6871 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6872 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6873 dumpLastANRLocked(pw);
6874 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6875 dumpLastANRTracesLocked(pw);
6876 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6877 dumpActivityStarterLocked(pw, dumpPackage);
6878 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6879 dumpActivityContainersLocked(pw);
6880 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6881 if (getRecentTasks() != null) {
6882 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6883 }
6884 }
6885 }
6886 }
6887
6888 @Override
6889 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6890 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6891 int wakefulness) {
6892 synchronized (mGlobalLock) {
6893 if (mHomeProcess != null && (dumpPackage == null
6894 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6895 if (needSep) {
6896 pw.println();
6897 needSep = false;
6898 }
6899 pw.println(" mHomeProcess: " + mHomeProcess);
6900 }
6901 if (mPreviousProcess != null && (dumpPackage == null
6902 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6903 if (needSep) {
6904 pw.println();
6905 needSep = false;
6906 }
6907 pw.println(" mPreviousProcess: " + mPreviousProcess);
6908 }
6909 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6910 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6911 StringBuilder sb = new StringBuilder(128);
6912 sb.append(" mPreviousProcessVisibleTime: ");
6913 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6914 pw.println(sb);
6915 }
6916 if (mHeavyWeightProcess != null && (dumpPackage == null
6917 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6918 if (needSep) {
6919 pw.println();
6920 needSep = false;
6921 }
6922 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6923 }
6924 if (dumpPackage == null) {
6925 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006926 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006927 }
6928 if (dumpAll) {
6929 if (dumpPackage == null) {
6930 pw.println(" mConfigWillChange: "
6931 + getTopDisplayFocusedStack().mConfigWillChange);
6932 }
6933 if (mCompatModePackages.getPackages().size() > 0) {
6934 boolean printed = false;
6935 for (Map.Entry<String, Integer> entry
6936 : mCompatModePackages.getPackages().entrySet()) {
6937 String pkg = entry.getKey();
6938 int mode = entry.getValue();
6939 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6940 continue;
6941 }
6942 if (!printed) {
6943 pw.println(" mScreenCompatPackages:");
6944 printed = true;
6945 }
6946 pw.println(" " + pkg + ": " + mode);
6947 }
6948 }
6949 }
6950
6951 if (dumpPackage == null) {
6952 pw.println(" mWakefulness="
6953 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006954 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006955 if (mRunningVoice != null) {
6956 pw.println(" mRunningVoice=" + mRunningVoice);
6957 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6958 }
6959 pw.println(" mSleeping=" + mSleeping);
6960 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6961 pw.println(" mVrController=" + mVrController);
6962 }
6963 if (mCurAppTimeTracker != null) {
6964 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6965 }
6966 if (mAllowAppSwitchUids.size() > 0) {
6967 boolean printed = false;
6968 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6969 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6970 for (int j = 0; j < types.size(); j++) {
6971 if (dumpPackage == null ||
6972 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6973 if (needSep) {
6974 pw.println();
6975 needSep = false;
6976 }
6977 if (!printed) {
6978 pw.println(" mAllowAppSwitchUids:");
6979 printed = true;
6980 }
6981 pw.print(" User ");
6982 pw.print(mAllowAppSwitchUids.keyAt(i));
6983 pw.print(": Type ");
6984 pw.print(types.keyAt(j));
6985 pw.print(" = ");
6986 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6987 pw.println();
6988 }
6989 }
6990 }
6991 }
6992 if (dumpPackage == null) {
6993 if (mController != null) {
6994 pw.println(" mController=" + mController
6995 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6996 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006997 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6998 pw.println(" mLaunchingActivityWakeLock="
6999 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007000 }
7001
7002 return needSep;
7003 }
7004 }
7005
7006 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007007 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7008 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007009 synchronized (mGlobalLock) {
7010 if (dumpPackage == null) {
7011 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7012 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007013 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7014 if (mRunningVoice != null) {
7015 final long vrToken = proto.start(
7016 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7017 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7018 mRunningVoice.toString());
7019 mVoiceWakeLock.writeToProto(
7020 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7021 proto.end(vrToken);
7022 }
7023 mVrController.writeToProto(proto,
7024 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007025 if (mController != null) {
7026 final long token = proto.start(CONTROLLER);
7027 proto.write(CONTROLLER, mController.toString());
7028 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7029 proto.end(token);
7030 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007031 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7032 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7033 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007034 }
7035
7036 if (mHomeProcess != null && (dumpPackage == null
7037 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007038 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007039 }
7040
7041 if (mPreviousProcess != null && (dumpPackage == null
7042 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007043 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007044 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7045 }
7046
7047 if (mHeavyWeightProcess != null && (dumpPackage == null
7048 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007049 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007050 }
7051
7052 for (Map.Entry<String, Integer> entry
7053 : mCompatModePackages.getPackages().entrySet()) {
7054 String pkg = entry.getKey();
7055 int mode = entry.getValue();
7056 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7057 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7058 proto.write(PACKAGE, pkg);
7059 proto.write(MODE, mode);
7060 proto.end(compatToken);
7061 }
7062 }
7063
7064 if (mCurAppTimeTracker != null) {
7065 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7066 }
7067
7068 }
7069 }
7070
7071 @Override
7072 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7073 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7074 boolean dumpFocusedStackOnly) {
7075 synchronized (mGlobalLock) {
7076 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7077 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7078 }
7079 }
7080
7081 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007082 public void dumpForOom(PrintWriter pw) {
7083 synchronized (mGlobalLock) {
7084 pw.println(" mHomeProcess: " + mHomeProcess);
7085 pw.println(" mPreviousProcess: " + mPreviousProcess);
7086 if (mHeavyWeightProcess != null) {
7087 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7088 }
7089 }
7090 }
7091
7092 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 public boolean canGcNow() {
7094 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007095 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007096 }
7097 }
7098
Riddle Hsua0536432019-02-16 00:38:59 +08007099 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007100 @Override
7101 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007102 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007103 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007104 return top != null ? top.app : null;
7105 }
7106 }
7107
Riddle Hsua0536432019-02-16 00:38:59 +08007108 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007109 @Override
7110 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007111 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007112 if (mRootActivityContainer != null) {
7113 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007114 }
7115 }
7116 }
7117
7118 @Override
7119 public void scheduleDestroyAllActivities(String reason) {
7120 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007121 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007122 }
7123 }
7124
7125 @Override
7126 public void removeUser(int userId) {
7127 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007128 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007129 }
7130 }
7131
7132 @Override
7133 public boolean switchUser(int userId, UserState userState) {
7134 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007135 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007136 }
7137 }
7138
7139 @Override
7140 public void onHandleAppCrash(WindowProcessController wpc) {
7141 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007142 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007143 }
7144 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007145
7146 @Override
7147 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7148 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007149 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007150 }
7151 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007152
Riddle Hsua0536432019-02-16 00:38:59 +08007153 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007154 @Override
7155 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007156 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007157 }
7158
Riddle Hsua0536432019-02-16 00:38:59 +08007159 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007160 @Override
7161 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007162 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007163 }
7164
Riddle Hsua0536432019-02-16 00:38:59 +08007165 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007166 @Override
7167 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007168 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007169 }
7170
Riddle Hsua0536432019-02-16 00:38:59 +08007171 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007172 @Override
7173 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007174 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007175 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007176
7177 @Override
7178 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007179 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007180 mPendingTempWhitelist.put(uid, tag);
7181 }
7182 }
7183
7184 @Override
7185 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007186 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007187 mPendingTempWhitelist.remove(uid);
7188 }
7189 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007190
7191 @Override
7192 public boolean handleAppCrashInActivityController(String processName, int pid,
7193 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7194 Runnable killCrashingAppCallback) {
7195 synchronized (mGlobalLock) {
7196 if (mController == null) {
7197 return false;
7198 }
7199
7200 try {
7201 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7202 stackTrace)) {
7203 killCrashingAppCallback.run();
7204 return true;
7205 }
7206 } catch (RemoteException e) {
7207 mController = null;
7208 Watchdog.getInstance().setActivityController(null);
7209 }
7210 return false;
7211 }
7212 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007213
7214 @Override
7215 public void removeRecentTasksByPackageName(String packageName, int userId) {
7216 synchronized (mGlobalLock) {
7217 mRecentTasks.removeTasksByPackageName(packageName, userId);
7218 }
7219 }
7220
7221 @Override
7222 public void cleanupRecentTasksForUser(int userId) {
7223 synchronized (mGlobalLock) {
7224 mRecentTasks.cleanupLocked(userId);
7225 }
7226 }
7227
7228 @Override
7229 public void loadRecentTasksForUser(int userId) {
7230 synchronized (mGlobalLock) {
7231 mRecentTasks.loadUserRecentsLocked(userId);
7232 }
7233 }
7234
7235 @Override
7236 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7237 synchronized (mGlobalLock) {
7238 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7239 }
7240 }
7241
7242 @Override
7243 public void flushRecentTasks() {
7244 mRecentTasks.flush();
7245 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007246
7247 @Override
7248 public WindowProcessController getHomeProcess() {
7249 synchronized (mGlobalLock) {
7250 return mHomeProcess;
7251 }
7252 }
7253
7254 @Override
7255 public WindowProcessController getPreviousProcess() {
7256 synchronized (mGlobalLock) {
7257 return mPreviousProcess;
7258 }
7259 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007260
7261 @Override
7262 public void clearLockedTasks(String reason) {
7263 synchronized (mGlobalLock) {
7264 getLockTaskController().clearLockedTasks(reason);
7265 }
7266 }
7267
7268 @Override
7269 public void updateUserConfiguration() {
7270 synchronized (mGlobalLock) {
7271 final Configuration configuration = new Configuration(getGlobalConfiguration());
7272 final int currentUserId = mAmInternal.getCurrentUserId();
7273 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7274 configuration, currentUserId, Settings.System.canWrite(mContext));
7275 updateConfigurationLocked(configuration, null /* starting */,
7276 false /* initLocale */, false /* persistent */, currentUserId,
7277 false /* deferResume */);
7278 }
7279 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007280
7281 @Override
7282 public boolean canShowErrorDialogs() {
7283 synchronized (mGlobalLock) {
7284 return mShowDialogs && !mSleeping && !mShuttingDown
7285 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7286 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7287 mAmInternal.getCurrentUserId())
7288 && !(UserManager.isDeviceInDemoMode(mContext)
7289 && mAmInternal.getCurrentUser().isDemo());
7290 }
7291 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007292
7293 @Override
7294 public void setProfileApp(String profileApp) {
7295 synchronized (mGlobalLock) {
7296 mProfileApp = profileApp;
7297 }
7298 }
7299
7300 @Override
7301 public void setProfileProc(WindowProcessController wpc) {
7302 synchronized (mGlobalLock) {
7303 mProfileProc = wpc;
7304 }
7305 }
7306
7307 @Override
7308 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7309 synchronized (mGlobalLock) {
7310 mProfilerInfo = profilerInfo;
7311 }
7312 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007313
7314 @Override
7315 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7316 synchronized (mGlobalLock) {
7317 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7318 }
7319 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007320
7321 @Override
7322 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7323 synchronized (mGlobalLock) {
7324 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7325 }
7326 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007327
7328 @Override
7329 public boolean isUidForeground(int uid) {
7330 synchronized (mGlobalLock) {
7331 return ActivityTaskManagerService.this.isUidForeground(uid);
7332 }
7333 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007334
7335 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007336 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007337 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007338 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007339 }
7340 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007341
7342 @Override
7343 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007344 // Translate package names into UIDs
7345 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007346 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007347 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7348 if (uid >= 0) {
7349 result.add(uid);
7350 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007351 }
7352 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007353 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007354 }
7355 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007356 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007357}