blob: 4a6aa336e36f410d3f3607ea9c6f6b462913434e [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;
Michal Karpinski15486842019-04-25 17:33:42 +0100137import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100195import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700196import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700197import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700198import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700199import android.os.SystemClock;
200import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700201import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700202import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700203import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700204import android.os.UserManager;
205import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700206import android.os.storage.IStorageManager;
207import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.provider.Settings;
209import android.service.voice.IVoiceInteractionSession;
210import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900211import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
lumark5df49512019-04-02 14:56:46 +0800228import android.view.inputmethod.InputMethodSystemProperty;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700229
Evan Rosky4505b352018-09-06 11:20:40 -0700230import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700231import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700235import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700238import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
239import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700240import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700241import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700242import com.android.internal.policy.IKeyguardDismissCallback;
243import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700244import com.android.internal.util.ArrayUtils;
245import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700246import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700247import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100249import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900264import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700265import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700266import com.android.server.pm.UserManagerService;
267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800278import java.lang.annotation.ElementType;
279import java.lang.annotation.Retention;
280import java.lang.annotation.RetentionPolicy;
281import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700283import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700285import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400287import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700290import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Map;
292import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293
294/**
295 * System service for managing activities and their containers (task, stacks, displays,... ).
296 *
297 * {@hide}
298 */
299public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700300 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700302 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
303 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
304 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
305 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
306 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700307 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313
Wale Ogunwale98875612018-10-12 07:53:02 -0700314 /** Used to indicate that an app transition should be animated. */
315 static final boolean ANIMATE = true;
316
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700317 /** Hardware-reported OpenGLES version. */
318 final int GL_ES_VERSION;
319
Wale Ogunwale31913b52018-10-13 08:29:31 -0700320 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
321 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
322 public static final String DUMP_LASTANR_CMD = "lastanr" ;
323 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
324 public static final String DUMP_STARTER_CMD = "starter" ;
325 public static final String DUMP_CONTAINERS_CMD = "containers" ;
326 public static final String DUMP_RECENTS_CMD = "recents" ;
327 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
328
Wale Ogunwale64258362018-10-16 15:13:37 -0700329 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
330 public static final int RELAUNCH_REASON_NONE = 0;
331 /** This activity is being relaunched due to windowing mode change. */
332 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
333 /** This activity is being relaunched due to a free-resize operation. */
334 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
335
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700336 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700337
Wale Ogunwalef6733932018-06-27 05:14:34 -0700338 /**
339 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
340 * change at runtime. Use mContext for non-UI purposes.
341 */
342 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700343 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700344 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700345 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700346 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700347 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700348 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800349 @VisibleForTesting
350 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700351 PowerManagerInternal mPowerManagerInternal;
352 private UsageStatsManagerInternal mUsageStatsInternal;
353
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700354 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700355 IntentFirewall mIntentFirewall;
356
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700357 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800358 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800359 /**
360 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
361 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
362 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
363 *
364 * @see WindowManagerThreadPriorityBooster
365 */
366 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700367 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800368 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700369 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700370 private UserManagerService mUserManager;
371 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700372 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800373 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700374 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700375 /** All processes currently running that might have a window organized by name. */
376 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100377 /** All processes we currently have running mapped by pid and uid */
378 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700379 /** This is the process holding what we currently consider to be the "home" activity. */
380 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700381 /** The currently running heavy-weight process, if any. */
382 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700383 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700384 /**
385 * This is the process holding the activity the user last visited that is in a different process
386 * from the one they are currently in.
387 */
388 WindowProcessController mPreviousProcess;
389 /** The time at which the previous process was last visible. */
390 long mPreviousProcessVisibleTime;
391
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700392 /** List of intents that were used to start the most recent tasks. */
393 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700394 /** State of external calls telling us if the device is awake or asleep. */
395 private boolean mKeyguardShown = false;
396
397 // Wrapper around VoiceInteractionServiceManager
398 private AssistUtils mAssistUtils;
399
400 // VoiceInteraction session ID that changes for each new request except when
401 // being called for multi-window assist in a single session.
402 private int mViSessionId = 1000;
403
404 // How long to wait in getAssistContextExtras for the activity and foreground services
405 // to respond with the result.
406 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
407
408 // How long top wait when going through the modern assist (which doesn't need to block
409 // on getting this result before starting to launch its UI).
410 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
411
412 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
413 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
414
Alison Cichowlas3e340502018-08-07 17:15:01 -0400415 // Permission tokens are used to temporarily granted a trusted app the ability to call
416 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
417 // showing any appropriate error messages to the user.
418 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
419 10 * MINUTE_IN_MILLIS;
420
421 // How long before the service actually expires a token. This is slightly longer than
422 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
423 // expiration exception.
424 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
425 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
426
427 // How long the service will remember expired tokens, for the purpose of providing error
428 // messaging when a client uses an expired token.
429 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
430 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
431
Marvin Ramin830d4e32019-03-12 13:16:58 +0100432 // How long to whitelist the Services for when requested.
433 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
434
Alison Cichowlas3e340502018-08-07 17:15:01 -0400435 // Activity tokens of system activities that are delegating their call to
436 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
437 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
438
439 // Permission tokens that have expired, but we remember for error reporting.
440 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
441
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700442 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
443
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700444 // Keeps track of the active voice interaction service component, notified from
445 // VoiceInteractionManagerService
446 ComponentName mActiveVoiceInteractionServiceComponent;
447
Michal Karpinskida34cd42019-04-02 19:46:52 +0100448 // A map userId and all its companion app uids
449 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000450
Wale Ogunwalee2172292018-10-25 10:11:10 -0700451 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700452 KeyguardController mKeyguardController;
453 private final ClientLifecycleManager mLifecycleManager;
454 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700455 /** The controller for all operations related to locktask. */
456 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700457 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700459 boolean mSuppressResizeConfigChanges;
460
461 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
462 new UpdateConfigurationResult();
463
464 static final class UpdateConfigurationResult {
465 // Configuration changes that were updated.
466 int changes;
467 // If the activity was relaunched to match the new configuration.
468 boolean activityRelaunched;
469
470 void reset() {
471 changes = 0;
472 activityRelaunched = false;
473 }
474 }
475
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700476 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700477 private int mConfigurationSeq;
478 // To cache the list of supported system locales
479 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700480
481 /**
482 * Temp object used when global and/or display override configuration is updated. It is also
483 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
484 * anyone...
485 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 private Configuration mTempConfig = new Configuration();
487
Wale Ogunwalef6733932018-06-27 05:14:34 -0700488 /** Temporary to avoid allocations. */
489 final StringBuilder mStringBuilder = new StringBuilder(256);
490
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700491 // Amount of time after a call to stopAppSwitches() during which we will
492 // prevent further untrusted switches from happening.
493 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
494
495 /**
496 * The time at which we will allow normal application switches again,
497 * after a call to {@link #stopAppSwitches()}.
498 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
501 * This is set to true after the first switch after mAppSwitchesAllowedTime
502 * is set; any switches after that will clear the time.
503 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700504 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700505
506 IActivityController mController = null;
507 boolean mControllerIsAMonkey = false;
508
Wale Ogunwale214f3482018-10-04 11:00:47 -0700509 final int mFactoryTest;
510
511 /** Used to control how we initialize the service. */
512 ComponentName mTopComponent;
513 String mTopAction = Intent.ACTION_MAIN;
514 String mTopData;
515
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800516 /** Profiling app information. */
517 String mProfileApp = null;
518 WindowProcessController mProfileProc = null;
519 ProfilerInfo mProfilerInfo = null;
520
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700521 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700522 * Dump of the activity state at the time of the last ANR. Cleared after
523 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
524 */
525 String mLastANRState;
526
527 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700528 * Used to retain an update lock when the foreground activity is in
529 * immersive mode.
530 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700531 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700532
533 /**
534 * Packages that are being allowed to perform unrestricted app switches. Mapping is
535 * User -> Type -> uid.
536 */
537 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
538
539 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700540 private int mThumbnailWidth;
541 private int mThumbnailHeight;
542 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700543
544 /**
545 * Flag that indicates if multi-window is enabled.
546 *
547 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
548 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
549 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
550 * At least one of the forms of multi-window must be enabled in order for this flag to be
551 * initialized to 'true'.
552 *
553 * @see #mSupportsSplitScreenMultiWindow
554 * @see #mSupportsFreeformWindowManagement
555 * @see #mSupportsPictureInPicture
556 * @see #mSupportsMultiDisplay
557 */
558 boolean mSupportsMultiWindow;
559 boolean mSupportsSplitScreenMultiWindow;
560 boolean mSupportsFreeformWindowManagement;
561 boolean mSupportsPictureInPicture;
562 boolean mSupportsMultiDisplay;
563 boolean mForceResizableActivities;
564
565 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
566
567 // VR Vr2d Display Id.
568 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700569
Wale Ogunwalef6733932018-06-27 05:14:34 -0700570 /**
571 * Set while we are wanting to sleep, to prevent any
572 * activities from being started/resumed.
573 *
574 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
575 *
576 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
577 * while in the sleep state until there is a pending transition out of sleep, in which case
578 * mSleeping is set to false, and remains false while awake.
579 *
580 * Whether mSleeping can quickly toggled between true/false without the device actually
581 * display changing states is undefined.
582 */
583 private boolean mSleeping = false;
584
585 /**
586 * The process state used for processes that are running the top activities.
587 * This changes between TOP and TOP_SLEEPING to following mSleeping.
588 */
589 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
590
591 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
592 // automatically. Important for devices without direct input devices.
593 private boolean mShowDialogs = true;
594
595 /** Set if we are shutting down the system, similar to sleeping. */
596 boolean mShuttingDown = false;
597
598 /**
599 * We want to hold a wake lock while running a voice interaction session, since
600 * this may happen with the screen off and we need to keep the CPU running to
601 * be able to continue to interact with the user.
602 */
603 PowerManager.WakeLock mVoiceWakeLock;
604
605 /**
606 * Set while we are running a voice interaction. This overrides sleeping while it is active.
607 */
608 IVoiceInteractionSession mRunningVoice;
609
610 /**
611 * The last resumed activity. This is identical to the current resumed activity most
612 * of the time but could be different when we're pausing one activity before we resume
613 * another activity.
614 */
615 ActivityRecord mLastResumedActivity;
616
617 /**
618 * The activity that is currently being traced as the active resumed activity.
619 *
620 * @see #updateResumedAppTrace
621 */
622 private @Nullable ActivityRecord mTracedResumedActivity;
623
624 /** If non-null, we are tracking the time the user spends in the currently focused app. */
625 AppTimeTracker mCurAppTimeTracker;
626
Wale Ogunwale008163e2018-07-23 23:11:08 -0700627 private AppWarnings mAppWarnings;
628
Wale Ogunwale53783742018-09-16 10:21:51 -0700629 /**
630 * Packages that the user has asked to have run in screen size
631 * compatibility mode instead of filling the screen.
632 */
633 CompatModePackages mCompatModePackages;
634
Wale Ogunwalef6733932018-06-27 05:14:34 -0700635 private FontScaleSettingObserver mFontScaleSettingObserver;
636
Ricky Wai96f5c352019-04-10 18:40:17 +0100637 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000638
Wale Ogunwalef6733932018-06-27 05:14:34 -0700639 private final class FontScaleSettingObserver extends ContentObserver {
640 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
641 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
642
643 public FontScaleSettingObserver() {
644 super(mH);
645 final ContentResolver resolver = mContext.getContentResolver();
646 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
647 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
648 UserHandle.USER_ALL);
649 }
650
651 @Override
652 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
653 if (mFontScaleUri.equals(uri)) {
654 updateFontScaleIfNeeded(userId);
655 } else if (mHideErrorDialogsUri.equals(uri)) {
656 synchronized (mGlobalLock) {
657 updateShouldShowDialogsLocked(getGlobalConfiguration());
658 }
659 }
660 }
661 }
662
Riddle Hsua0536432019-02-16 00:38:59 +0800663 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
664 @Target(ElementType.METHOD)
665 @Retention(RetentionPolicy.SOURCE)
666 @interface HotPath {
667 int NONE = 0;
668 int OOM_ADJUSTMENT = 1;
669 int LRU_UPDATE = 2;
670 int PROCESS_CHANGE = 3;
671 int caller() default NONE;
672 }
673
Charles Chen8d98dd22018-12-26 17:36:54 +0800674 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
675 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700676 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700677 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700678 mSystemThread = ActivityThread.currentActivityThread();
679 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700680 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800681 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700682 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700683 }
684
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700685 public void onSystemReady() {
686 synchronized (mGlobalLock) {
687 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
688 PackageManager.FEATURE_CANT_SAVE_STATE);
689 mAssistUtils = new AssistUtils(mContext);
690 mVrController.onSystemReady();
691 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700692 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700693 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700694 }
695
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700696 public void onInitPowerManagement() {
697 synchronized (mGlobalLock) {
698 mStackSupervisor.initPowerManagement();
699 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
700 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
701 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
702 mVoiceWakeLock.setReferenceCounted(false);
703 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700704 }
705
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700706 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700707 mFontScaleSettingObserver = new FontScaleSettingObserver();
708 }
709
Wale Ogunwale59507092018-10-29 09:00:30 -0700710 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700711 final boolean freeformWindowManagement =
712 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
713 || Settings.Global.getInt(
714 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
715
716 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
717 final boolean supportsPictureInPicture = supportsMultiWindow &&
718 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
719 final boolean supportsSplitScreenMultiWindow =
720 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
721 final boolean supportsMultiDisplay = mContext.getPackageManager()
722 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700723 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
724 final boolean forceResizable = Settings.Global.getInt(
725 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700726 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700727
728 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900729 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700730
731 final Configuration configuration = new Configuration();
732 Settings.System.getConfiguration(resolver, configuration);
733 if (forceRtl) {
734 // This will take care of setting the correct layout direction flags
735 configuration.setLayoutDirection(configuration.locale);
736 }
737
738 synchronized (mGlobalLock) {
739 mForceResizableActivities = forceResizable;
740 final boolean multiWindowFormEnabled = freeformWindowManagement
741 || supportsSplitScreenMultiWindow
742 || supportsPictureInPicture
743 || supportsMultiDisplay;
744 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
745 mSupportsMultiWindow = true;
746 mSupportsFreeformWindowManagement = freeformWindowManagement;
747 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
748 mSupportsPictureInPicture = supportsPictureInPicture;
749 mSupportsMultiDisplay = supportsMultiDisplay;
750 } else {
751 mSupportsMultiWindow = false;
752 mSupportsFreeformWindowManagement = false;
753 mSupportsSplitScreenMultiWindow = false;
754 mSupportsPictureInPicture = false;
755 mSupportsMultiDisplay = false;
756 }
757 mWindowManager.setForceResizableTasks(mForceResizableActivities);
758 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700759 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
760 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700761 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700762 // This happens before any activities are started, so we can change global configuration
763 // in-place.
764 updateConfigurationLocked(configuration, null, true);
765 final Configuration globalConfig = getGlobalConfiguration();
766 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
767
768 // Load resources only after the current configuration has been set.
769 final Resources res = mContext.getResources();
770 mThumbnailWidth = res.getDimensionPixelSize(
771 com.android.internal.R.dimen.thumbnail_width);
772 mThumbnailHeight = res.getDimensionPixelSize(
773 com.android.internal.R.dimen.thumbnail_height);
774
775 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
776 mFullscreenThumbnailScale = (float) res
777 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
778 (float) globalConfig.screenWidthDp;
779 } else {
780 mFullscreenThumbnailScale = res.getFraction(
781 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
782 }
783 }
784 }
785
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800786 public WindowManagerGlobalLock getGlobalLock() {
787 return mGlobalLock;
788 }
789
Yunfan Chen585f2932019-01-29 16:04:45 +0900790 /** For test purpose only. */
791 @VisibleForTesting
792 public ActivityTaskManagerInternal getAtmInternal() {
793 return mInternal;
794 }
795
Riddle Hsud93a6c42018-11-29 21:50:06 +0800796 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
797 Looper looper) {
798 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700799 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700800 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700801 final File systemDir = SystemServiceManager.ensureSystemDir();
802 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
803 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700804 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700805
806 mTempConfig.setToDefaults();
807 mTempConfig.setLocales(LocaleList.getDefault());
808 mConfigurationSeq = mTempConfig.seq = 1;
809 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800810 mRootActivityContainer = new RootActivityContainer(this);
811 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700812
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700813 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700814 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700815 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700816 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700817 mRecentTasks = createRecentTasks();
818 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700819 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mKeyguardController = mStackSupervisor.getKeyguardController();
821 }
822
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700823 public void onActivityManagerInternalAdded() {
824 synchronized (mGlobalLock) {
825 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
826 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
827 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700828 }
829
Yunfan Chen75157d72018-07-27 14:47:21 +0900830 int increaseConfigurationSeqLocked() {
831 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
832 return mConfigurationSeq;
833 }
834
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700835 protected ActivityStackSupervisor createStackSupervisor() {
836 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
837 supervisor.initialize();
838 return supervisor;
839 }
840
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700841 public void setWindowManager(WindowManagerService wm) {
842 synchronized (mGlobalLock) {
843 mWindowManager = wm;
844 mLockTaskController.setWindowManager(wm);
845 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800846 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700847 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700848 }
849
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700850 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
851 synchronized (mGlobalLock) {
852 mUsageStatsInternal = usageStatsManager;
853 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700854 }
855
Wale Ogunwalef6733932018-06-27 05:14:34 -0700856 UserManagerService getUserManager() {
857 if (mUserManager == null) {
858 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
859 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
860 }
861 return mUserManager;
862 }
863
864 AppOpsService getAppOpsService() {
865 if (mAppOpsService == null) {
866 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
867 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
868 }
869 return mAppOpsService;
870 }
871
872 boolean hasUserRestriction(String restriction, int userId) {
873 return getUserManager().hasUserRestriction(restriction, userId);
874 }
875
Michal Karpinski15486842019-04-25 17:33:42 +0100876 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
877 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
878 callingUid, callingPackage);
879 if (mode == AppOpsManager.MODE_DEFAULT) {
880 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
881 == PERMISSION_GRANTED;
882 }
883 return mode == AppOpsManager.MODE_ALLOWED;
884 }
885
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700886 protected RecentTasks createRecentTasks() {
887 return new RecentTasks(this, mStackSupervisor);
888 }
889
890 RecentTasks getRecentTasks() {
891 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700892 }
893
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700894 ClientLifecycleManager getLifecycleManager() {
895 return mLifecycleManager;
896 }
897
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700898 ActivityStartController getActivityStartController() {
899 return mActivityStartController;
900 }
901
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700902 TaskChangeNotificationController getTaskChangeNotificationController() {
903 return mTaskChangeNotificationController;
904 }
905
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700906 LockTaskController getLockTaskController() {
907 return mLockTaskController;
908 }
909
Yunfan Chen75157d72018-07-27 14:47:21 +0900910 /**
911 * Return the global configuration used by the process corresponding to the input pid. This is
912 * usually the global configuration with some overrides specific to that process.
913 */
914 Configuration getGlobalConfigurationForCallingPid() {
915 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800916 return getGlobalConfigurationForPid(pid);
917 }
918
919 /**
920 * Return the global configuration used by the process corresponding to the given pid.
921 */
922 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900923 if (pid == MY_PID || pid < 0) {
924 return getGlobalConfiguration();
925 }
926 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100927 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900928 return app != null ? app.getConfiguration() : getGlobalConfiguration();
929 }
930 }
931
932 /**
933 * Return the device configuration info used by the process corresponding to the input pid.
934 * The value is consistent with the global configuration for the process.
935 */
936 @Override
937 public ConfigurationInfo getDeviceConfigurationInfo() {
938 ConfigurationInfo config = new ConfigurationInfo();
939 synchronized (mGlobalLock) {
940 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
941 config.reqTouchScreen = globalConfig.touchscreen;
942 config.reqKeyboardType = globalConfig.keyboard;
943 config.reqNavigation = globalConfig.navigation;
944 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
945 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
946 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
947 }
948 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
949 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
950 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
951 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700952 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900953 }
954 return config;
955 }
956
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700957 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700958 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700959 }
960
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700961 public static final class Lifecycle extends SystemService {
962 private final ActivityTaskManagerService mService;
963
964 public Lifecycle(Context context) {
965 super(context);
966 mService = new ActivityTaskManagerService(context);
967 }
968
969 @Override
970 public void onStart() {
971 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700972 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700973 }
974
Garfield Tan891146c2018-10-09 12:14:00 -0700975 @Override
976 public void onUnlockUser(int userId) {
977 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800978 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700979 }
980 }
981
982 @Override
983 public void onCleanupUser(int userId) {
984 synchronized (mService.getGlobalLock()) {
985 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
986 }
987 }
988
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700989 public ActivityTaskManagerService getService() {
990 return mService;
991 }
992 }
993
994 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700995 public final int startActivity(IApplicationThread caller, String callingPackage,
996 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
997 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
998 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
999 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1000 UserHandle.getCallingUserId());
1001 }
1002
1003 @Override
1004 public final int startActivities(IApplicationThread caller, String callingPackage,
1005 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1006 int userId) {
1007 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001008 enforceNotIsolatedCaller(reason);
1009 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001010 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001011 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1012 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1013 reason, null /* originatingPendingIntent */,
1014 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 }
1016
1017 @Override
1018 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1019 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1020 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1021 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1022 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1023 true /*validateIncomingUser*/);
1024 }
1025
1026 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1027 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1028 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1029 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001030 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001031
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001032 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1034
1035 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001036 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 .setCaller(caller)
1038 .setCallingPackage(callingPackage)
1039 .setResolvedType(resolvedType)
1040 .setResultTo(resultTo)
1041 .setResultWho(resultWho)
1042 .setRequestCode(requestCode)
1043 .setStartFlags(startFlags)
1044 .setProfilerInfo(profilerInfo)
1045 .setActivityOptions(bOptions)
1046 .setMayWait(userId)
1047 .execute();
1048
1049 }
1050
1051 @Override
1052 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1053 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001054 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1055 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001056 // Refuse possible leaked file descriptors
1057 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1058 throw new IllegalArgumentException("File descriptors passed in Intent");
1059 }
1060
1061 if (!(target instanceof PendingIntentRecord)) {
1062 throw new IllegalArgumentException("Bad PendingIntent object");
1063 }
1064
1065 PendingIntentRecord pir = (PendingIntentRecord)target;
1066
1067 synchronized (mGlobalLock) {
1068 // If this is coming from the currently resumed activity, it is
1069 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001070 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001071 if (stack.mResumedActivity != null &&
1072 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001073 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001074 }
1075 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001076 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001077 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 }
1079
1080 @Override
1081 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1082 Bundle bOptions) {
1083 // Refuse possible leaked file descriptors
1084 if (intent != null && intent.hasFileDescriptors()) {
1085 throw new IllegalArgumentException("File descriptors passed in Intent");
1086 }
1087 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1088
1089 synchronized (mGlobalLock) {
1090 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1091 if (r == null) {
1092 SafeActivityOptions.abort(options);
1093 return false;
1094 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001095 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 // The caller is not running... d'oh!
1097 SafeActivityOptions.abort(options);
1098 return false;
1099 }
1100 intent = new Intent(intent);
1101 // The caller is not allowed to change the data.
1102 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1103 // And we are resetting to find the next component...
1104 intent.setComponent(null);
1105
1106 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1107
1108 ActivityInfo aInfo = null;
1109 try {
1110 List<ResolveInfo> resolves =
1111 AppGlobals.getPackageManager().queryIntentActivities(
1112 intent, r.resolvedType,
1113 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1114 UserHandle.getCallingUserId()).getList();
1115
1116 // Look for the original activity in the list...
1117 final int N = resolves != null ? resolves.size() : 0;
1118 for (int i=0; i<N; i++) {
1119 ResolveInfo rInfo = resolves.get(i);
1120 if (rInfo.activityInfo.packageName.equals(r.packageName)
1121 && rInfo.activityInfo.name.equals(r.info.name)) {
1122 // We found the current one... the next matching is
1123 // after it.
1124 i++;
1125 if (i<N) {
1126 aInfo = resolves.get(i).activityInfo;
1127 }
1128 if (debug) {
1129 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1130 + "/" + r.info.name);
1131 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1132 ? "null" : aInfo.packageName + "/" + aInfo.name));
1133 }
1134 break;
1135 }
1136 }
1137 } catch (RemoteException e) {
1138 }
1139
1140 if (aInfo == null) {
1141 // Nobody who is next!
1142 SafeActivityOptions.abort(options);
1143 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1144 return false;
1145 }
1146
1147 intent.setComponent(new ComponentName(
1148 aInfo.applicationInfo.packageName, aInfo.name));
1149 intent.setFlags(intent.getFlags()&~(
1150 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1151 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1152 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1153 FLAG_ACTIVITY_NEW_TASK));
1154
1155 // Okay now we need to start the new activity, replacing the currently running activity.
1156 // This is a little tricky because we want to start the new one as if the current one is
1157 // finished, but not finish the current one first so that there is no flicker.
1158 // And thus...
1159 final boolean wasFinishing = r.finishing;
1160 r.finishing = true;
1161
1162 // Propagate reply information over to the new activity.
1163 final ActivityRecord resultTo = r.resultTo;
1164 final String resultWho = r.resultWho;
1165 final int requestCode = r.requestCode;
1166 r.resultTo = null;
1167 if (resultTo != null) {
1168 resultTo.removeResultsLocked(r, resultWho, requestCode);
1169 }
1170
1171 final long origId = Binder.clearCallingIdentity();
1172 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001173 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001174 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001175 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001176 .setResolvedType(r.resolvedType)
1177 .setActivityInfo(aInfo)
1178 .setResultTo(resultTo != null ? resultTo.appToken : null)
1179 .setResultWho(resultWho)
1180 .setRequestCode(requestCode)
1181 .setCallingPid(-1)
1182 .setCallingUid(r.launchedFromUid)
1183 .setCallingPackage(r.launchedFromPackage)
1184 .setRealCallingPid(-1)
1185 .setRealCallingUid(r.launchedFromUid)
1186 .setActivityOptions(options)
1187 .execute();
1188 Binder.restoreCallingIdentity(origId);
1189
1190 r.finishing = wasFinishing;
1191 if (res != ActivityManager.START_SUCCESS) {
1192 return false;
1193 }
1194 return true;
1195 }
1196 }
1197
1198 @Override
1199 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1200 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1201 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1202 final WaitResult res = new WaitResult();
1203 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001204 enforceNotIsolatedCaller("startActivityAndWait");
1205 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1206 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001207 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001208 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001209 .setCaller(caller)
1210 .setCallingPackage(callingPackage)
1211 .setResolvedType(resolvedType)
1212 .setResultTo(resultTo)
1213 .setResultWho(resultWho)
1214 .setRequestCode(requestCode)
1215 .setStartFlags(startFlags)
1216 .setActivityOptions(bOptions)
1217 .setMayWait(userId)
1218 .setProfilerInfo(profilerInfo)
1219 .setWaitResult(res)
1220 .execute();
1221 }
1222 return res;
1223 }
1224
1225 @Override
1226 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1227 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1228 int startFlags, Configuration config, Bundle bOptions, int userId) {
1229 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001230 enforceNotIsolatedCaller("startActivityWithConfig");
1231 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1232 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001233 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001234 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 .setCaller(caller)
1236 .setCallingPackage(callingPackage)
1237 .setResolvedType(resolvedType)
1238 .setResultTo(resultTo)
1239 .setResultWho(resultWho)
1240 .setRequestCode(requestCode)
1241 .setStartFlags(startFlags)
1242 .setGlobalConfiguration(config)
1243 .setActivityOptions(bOptions)
1244 .setMayWait(userId)
1245 .execute();
1246 }
1247 }
1248
Alison Cichowlas3e340502018-08-07 17:15:01 -04001249
1250 @Override
1251 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1252 int callingUid = Binder.getCallingUid();
1253 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1254 throw new SecurityException("Only the system process can request a permission token, "
1255 + "received request from uid: " + callingUid);
1256 }
1257 IBinder permissionToken = new Binder();
1258 synchronized (mGlobalLock) {
1259 mStartActivitySources.put(permissionToken, delegatorToken);
1260 }
1261
1262 Message expireMsg = PooledLambda.obtainMessage(
1263 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1264 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1265
1266 Message forgetMsg = PooledLambda.obtainMessage(
1267 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1268 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1269
1270 return permissionToken;
1271 }
1272
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001273 @Override
1274 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1275 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001276 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1277 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 // permission grants) as any app that may launch one of your own activities. So we only
1280 // allow this in two cases:
1281 // 1) The caller is an activity that is part of the core framework, and then only when it
1282 // is running as the system.
1283 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1284 // can only be requested by a system activity, which may then delegate this call to
1285 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001286 final ActivityRecord sourceRecord;
1287 final int targetUid;
1288 final String targetPackage;
1289 final boolean isResolver;
1290 synchronized (mGlobalLock) {
1291 if (resultTo == null) {
1292 throw new SecurityException("Must be called from an activity");
1293 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001294 final IBinder sourceToken;
1295 if (permissionToken != null) {
1296 // To even attempt to use a permissionToken, an app must also have this signature
1297 // permission.
1298 mAmInternal.enforceCallingPermission(
1299 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1300 "startActivityAsCaller");
1301 // If called with a permissionToken, we want the sourceRecord from the delegator
1302 // activity that requested this token.
1303 sourceToken = mStartActivitySources.remove(permissionToken);
1304 if (sourceToken == null) {
1305 // Invalid permissionToken, check if it recently expired.
1306 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1307 throw new SecurityException("Called with expired permission token: "
1308 + permissionToken);
1309 } else {
1310 throw new SecurityException("Called with invalid permission token: "
1311 + permissionToken);
1312 }
1313 }
1314 } else {
1315 // This method was called directly by the source.
1316 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001317 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001318
Wale Ogunwaled32da472018-11-16 07:19:28 -08001319 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001320 if (sourceRecord == null) {
1321 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001322 }
1323 if (sourceRecord.app == null) {
1324 throw new SecurityException("Called without a process attached to activity");
1325 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001326
1327 // Whether called directly or from a delegate, the source activity must be from the
1328 // android package.
1329 if (!sourceRecord.info.packageName.equals("android")) {
1330 throw new SecurityException("Must be called from an activity that is "
1331 + "declared in the android package");
1332 }
1333
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001334 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001335 // This is still okay, as long as this activity is running under the
1336 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001337 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001339 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001340 + " must be system uid or original calling uid "
1341 + sourceRecord.launchedFromUid);
1342 }
1343 }
1344 if (ignoreTargetSecurity) {
1345 if (intent.getComponent() == null) {
1346 throw new SecurityException(
1347 "Component must be specified with ignoreTargetSecurity");
1348 }
1349 if (intent.getSelector() != null) {
1350 throw new SecurityException(
1351 "Selector not allowed with ignoreTargetSecurity");
1352 }
1353 }
1354 targetUid = sourceRecord.launchedFromUid;
1355 targetPackage = sourceRecord.launchedFromPackage;
1356 isResolver = sourceRecord.isResolverOrChildActivity();
1357 }
1358
1359 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001360 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001361 }
1362
1363 // TODO: Switch to user app stacks here.
1364 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001365 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366 .setCallingUid(targetUid)
1367 .setCallingPackage(targetPackage)
1368 .setResolvedType(resolvedType)
1369 .setResultTo(resultTo)
1370 .setResultWho(resultWho)
1371 .setRequestCode(requestCode)
1372 .setStartFlags(startFlags)
1373 .setActivityOptions(bOptions)
1374 .setMayWait(userId)
1375 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1376 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1377 .execute();
1378 } catch (SecurityException e) {
1379 // XXX need to figure out how to propagate to original app.
1380 // A SecurityException here is generally actually a fault of the original
1381 // calling activity (such as a fairly granting permissions), so propagate it
1382 // back to them.
1383 /*
1384 StringBuilder msg = new StringBuilder();
1385 msg.append("While launching");
1386 msg.append(intent.toString());
1387 msg.append(": ");
1388 msg.append(e.getMessage());
1389 */
1390 throw e;
1391 }
1392 }
1393
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001394 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1395 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1396 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1397 }
1398
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001399 @Override
1400 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1401 Intent intent, String resolvedType, IVoiceInteractionSession session,
1402 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1403 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001404 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 if (session == null || interactor == null) {
1406 throw new NullPointerException("null session or interactor");
1407 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001408 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001410 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 .setCallingUid(callingUid)
1412 .setCallingPackage(callingPackage)
1413 .setResolvedType(resolvedType)
1414 .setVoiceSession(session)
1415 .setVoiceInteractor(interactor)
1416 .setStartFlags(startFlags)
1417 .setProfilerInfo(profilerInfo)
1418 .setActivityOptions(bOptions)
1419 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001420 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 .execute();
1422 }
1423
1424 @Override
1425 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1426 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001427 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1428 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001429
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001430 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 .setCallingUid(callingUid)
1432 .setCallingPackage(callingPackage)
1433 .setResolvedType(resolvedType)
1434 .setActivityOptions(bOptions)
1435 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001436 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001437 .execute();
1438 }
1439
1440 @Override
1441 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1442 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001443 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444 final int callingPid = Binder.getCallingPid();
1445 final long origId = Binder.clearCallingIdentity();
1446 try {
1447 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001448 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1449 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450
1451 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001452 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1453 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1455 recentsUid, assistDataReceiver);
1456 }
1457 } finally {
1458 Binder.restoreCallingIdentity(origId);
1459 }
1460 }
1461
1462 @Override
1463 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001464 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 "startActivityFromRecents()");
1466
1467 final int callingPid = Binder.getCallingPid();
1468 final int callingUid = Binder.getCallingUid();
1469 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1470 final long origId = Binder.clearCallingIdentity();
1471 try {
1472 synchronized (mGlobalLock) {
1473 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1474 safeOptions);
1475 }
1476 } finally {
1477 Binder.restoreCallingIdentity(origId);
1478 }
1479 }
1480
1481 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001482 * Public API to check if the client is allowed to start an activity on specified display.
1483 *
1484 * If the target display is private or virtual, some restrictions will apply.
1485 *
1486 * @param displayId Target display id.
1487 * @param intent Intent used to launch the activity.
1488 * @param resolvedType The MIME type of the intent.
1489 * @param userId The id of the user for whom the call is made.
1490 * @return {@code true} if a call to start an activity on the target display should succeed and
1491 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1492 */
1493 @Override
1494 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1495 String resolvedType, int userId) {
1496 final int callingUid = Binder.getCallingUid();
1497 final int callingPid = Binder.getCallingPid();
1498 final long origId = Binder.clearCallingIdentity();
1499
1500 try {
1501 // Collect information about the target of the Intent.
1502 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1503 0 /* startFlags */, null /* profilerInfo */, userId,
1504 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1505 UserHandle.USER_NULL));
1506 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1507
1508 synchronized (mGlobalLock) {
1509 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1510 aInfo);
1511 }
1512 } finally {
1513 Binder.restoreCallingIdentity(origId);
1514 }
1515 }
1516
1517 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001518 * This is the internal entry point for handling Activity.finish().
1519 *
1520 * @param token The Binder token referencing the Activity we want to finish.
1521 * @param resultCode Result code, if any, from this Activity.
1522 * @param resultData Result data (Intent), if any, from this Activity.
1523 * @param finishTask Whether to finish the task associated with this Activity.
1524 *
1525 * @return Returns true if the activity successfully finished, or false if it is still running.
1526 */
1527 @Override
1528 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1529 int finishTask) {
1530 // Refuse possible leaked file descriptors
1531 if (resultData != null && resultData.hasFileDescriptors()) {
1532 throw new IllegalArgumentException("File descriptors passed in Intent");
1533 }
1534
1535 synchronized (mGlobalLock) {
1536 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1537 if (r == null) {
1538 return true;
1539 }
1540 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001541 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001542 ActivityRecord rootR = tr.getRootActivity();
1543 if (rootR == null) {
1544 Slog.w(TAG, "Finishing task with all activities already finished");
1545 }
1546 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1547 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001548 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001549 return false;
1550 }
1551
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001552 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1553 // We should consolidate.
1554 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001555 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001556 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001557 if (next != null) {
1558 // ask watcher if this is allowed
1559 boolean resumeOK = true;
1560 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001561 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001562 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001563 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001564 Watchdog.getInstance().setActivityController(null);
1565 }
1566
1567 if (!resumeOK) {
1568 Slog.i(TAG, "Not finishing activity because controller resumed");
1569 return false;
1570 }
1571 }
1572 }
1573 final long origId = Binder.clearCallingIdentity();
1574 try {
1575 boolean res;
1576 final boolean finishWithRootActivity =
1577 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1578 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1579 || (finishWithRootActivity && r == rootR)) {
1580 // If requested, remove the task that is associated to this activity only if it
1581 // was the root activity in the task. The result code and data is ignored
1582 // because we don't support returning them across task boundaries. Also, to
1583 // keep backwards compatibility we remove the task from recents when finishing
1584 // task with root activity.
1585 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1586 finishWithRootActivity, "finish-activity");
1587 if (!res) {
1588 Slog.i(TAG, "Removing task failed to finish activity");
1589 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001590 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001591 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 } else {
1593 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1594 resultData, "app-request", true);
1595 if (!res) {
1596 Slog.i(TAG, "Failed to finish by app-request");
1597 }
1598 }
1599 return res;
1600 } finally {
1601 Binder.restoreCallingIdentity(origId);
1602 }
1603 }
1604 }
1605
1606 @Override
1607 public boolean finishActivityAffinity(IBinder token) {
1608 synchronized (mGlobalLock) {
1609 final long origId = Binder.clearCallingIdentity();
1610 try {
1611 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1612 if (r == null) {
1613 return false;
1614 }
1615
1616 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1617 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001618 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001619 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001620 return false;
1621 }
1622 return task.getStack().finishActivityAffinityLocked(r);
1623 } finally {
1624 Binder.restoreCallingIdentity(origId);
1625 }
1626 }
1627 }
1628
1629 @Override
1630 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1631 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001632 try {
1633 WindowProcessController proc = null;
1634 synchronized (mGlobalLock) {
1635 ActivityStack stack = ActivityRecord.getStackLocked(token);
1636 if (stack == null) {
1637 return;
1638 }
1639 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1640 false /* fromTimeout */, false /* processPausingActivities */, config);
1641 if (r != null) {
1642 proc = r.app;
1643 }
1644 if (stopProfiling && proc != null) {
1645 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001646 }
1647 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001648 } finally {
1649 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001651 }
1652
1653 @Override
1654 public final void activityResumed(IBinder token) {
1655 final long origId = Binder.clearCallingIdentity();
1656 synchronized (mGlobalLock) {
1657 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001658 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001659 }
1660 Binder.restoreCallingIdentity(origId);
1661 }
1662
1663 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001664 public final void activityTopResumedStateLost() {
1665 final long origId = Binder.clearCallingIdentity();
1666 synchronized (mGlobalLock) {
1667 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1668 }
1669 Binder.restoreCallingIdentity(origId);
1670 }
1671
1672 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 public final void activityPaused(IBinder token) {
1674 final long origId = Binder.clearCallingIdentity();
1675 synchronized (mGlobalLock) {
1676 ActivityStack stack = ActivityRecord.getStackLocked(token);
1677 if (stack != null) {
1678 stack.activityPausedLocked(token, false);
1679 }
1680 }
1681 Binder.restoreCallingIdentity(origId);
1682 }
1683
1684 @Override
1685 public final void activityStopped(IBinder token, Bundle icicle,
1686 PersistableBundle persistentState, CharSequence description) {
1687 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1688
1689 // Refuse possible leaked file descriptors
1690 if (icicle != null && icicle.hasFileDescriptors()) {
1691 throw new IllegalArgumentException("File descriptors passed in Bundle");
1692 }
1693
1694 final long origId = Binder.clearCallingIdentity();
1695
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001696 String restartingName = null;
1697 int restartingUid = 0;
1698 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001699 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001700 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001701 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001702 if (r.attachedToProcess()
1703 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1704 // The activity was requested to restart from
1705 // {@link #restartActivityProcessIfVisible}.
1706 restartingName = r.app.mName;
1707 restartingUid = r.app.mUid;
1708 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001709 r.activityStoppedLocked(icicle, persistentState, description);
1710 }
1711 }
1712
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001713 if (restartingName != null) {
1714 // In order to let the foreground activity can be restarted with its saved state from
1715 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1716 // until the activity reports stopped with the state. And the activity record will be
1717 // kept because the record state is restarting, then the activity will be restarted
1718 // immediately if it is still the top one.
1719 mStackSupervisor.removeRestartTimeouts(r);
1720 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1721 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001722 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001723
1724 Binder.restoreCallingIdentity(origId);
1725 }
1726
1727 @Override
1728 public final void activityDestroyed(IBinder token) {
1729 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1730 synchronized (mGlobalLock) {
1731 ActivityStack stack = ActivityRecord.getStackLocked(token);
1732 if (stack != null) {
1733 stack.activityDestroyedLocked(token, "activityDestroyed");
1734 }
1735 }
1736 }
1737
1738 @Override
1739 public final void activityRelaunched(IBinder token) {
1740 final long origId = Binder.clearCallingIdentity();
1741 synchronized (mGlobalLock) {
1742 mStackSupervisor.activityRelaunchedLocked(token);
1743 }
1744 Binder.restoreCallingIdentity(origId);
1745 }
1746
1747 public final void activitySlept(IBinder token) {
1748 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1749
1750 final long origId = Binder.clearCallingIdentity();
1751
1752 synchronized (mGlobalLock) {
1753 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1754 if (r != null) {
1755 mStackSupervisor.activitySleptLocked(r);
1756 }
1757 }
1758
1759 Binder.restoreCallingIdentity(origId);
1760 }
1761
1762 @Override
1763 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1764 synchronized (mGlobalLock) {
1765 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1766 if (r == null) {
1767 return;
1768 }
1769 final long origId = Binder.clearCallingIdentity();
1770 try {
1771 r.setRequestedOrientation(requestedOrientation);
1772 } finally {
1773 Binder.restoreCallingIdentity(origId);
1774 }
1775 }
1776 }
1777
1778 @Override
1779 public int getRequestedOrientation(IBinder token) {
1780 synchronized (mGlobalLock) {
1781 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1782 if (r == null) {
1783 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1784 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001785 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001786 }
1787 }
1788
1789 @Override
1790 public void setImmersive(IBinder token, boolean immersive) {
1791 synchronized (mGlobalLock) {
1792 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1793 if (r == null) {
1794 throw new IllegalArgumentException();
1795 }
1796 r.immersive = immersive;
1797
1798 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001799 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001801 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 }
1803 }
1804 }
1805
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001806 void applyUpdateLockStateLocked(ActivityRecord r) {
1807 // Modifications to the UpdateLock state are done on our handler, outside
1808 // the activity manager's locks. The new state is determined based on the
1809 // state *now* of the relevant activity record. The object is passed to
1810 // the handler solely for logging detail, not to be consulted/modified.
1811 final boolean nextState = r != null && r.immersive;
1812 mH.post(() -> {
1813 if (mUpdateLock.isHeld() != nextState) {
1814 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1815 "Applying new update lock state '" + nextState + "' for " + r);
1816 if (nextState) {
1817 mUpdateLock.acquire();
1818 } else {
1819 mUpdateLock.release();
1820 }
1821 }
1822 });
1823 }
1824
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001825 @Override
1826 public boolean isImmersive(IBinder token) {
1827 synchronized (mGlobalLock) {
1828 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1829 if (r == null) {
1830 throw new IllegalArgumentException();
1831 }
1832 return r.immersive;
1833 }
1834 }
1835
1836 @Override
1837 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001838 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001839 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001840 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001841 return (r != null) ? r.immersive : false;
1842 }
1843 }
1844
1845 @Override
1846 public void overridePendingTransition(IBinder token, String packageName,
1847 int enterAnim, int exitAnim) {
1848 synchronized (mGlobalLock) {
1849 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1850 if (self == null) {
1851 return;
1852 }
1853
1854 final long origId = Binder.clearCallingIdentity();
1855
1856 if (self.isState(
1857 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001858 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001859 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001860 }
1861
1862 Binder.restoreCallingIdentity(origId);
1863 }
1864 }
1865
1866 @Override
1867 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001868 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001870 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 if (r == null) {
1872 return ActivityManager.COMPAT_MODE_UNKNOWN;
1873 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001874 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
1876 }
1877
1878 @Override
1879 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001880 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001882 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001883 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001884 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 if (r == null) {
1886 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1887 return;
1888 }
1889 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001890 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001891 }
1892 }
1893
1894 @Override
1895 public int getLaunchedFromUid(IBinder activityToken) {
1896 ActivityRecord srec;
1897 synchronized (mGlobalLock) {
1898 srec = ActivityRecord.forTokenLocked(activityToken);
1899 }
1900 if (srec == null) {
1901 return -1;
1902 }
1903 return srec.launchedFromUid;
1904 }
1905
1906 @Override
1907 public String getLaunchedFromPackage(IBinder activityToken) {
1908 ActivityRecord srec;
1909 synchronized (mGlobalLock) {
1910 srec = ActivityRecord.forTokenLocked(activityToken);
1911 }
1912 if (srec == null) {
1913 return null;
1914 }
1915 return srec.launchedFromPackage;
1916 }
1917
1918 @Override
1919 public boolean convertFromTranslucent(IBinder token) {
1920 final long origId = Binder.clearCallingIdentity();
1921 try {
1922 synchronized (mGlobalLock) {
1923 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1924 if (r == null) {
1925 return false;
1926 }
1927 final boolean translucentChanged = r.changeWindowTranslucency(true);
1928 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001929 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001930 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001931 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001932 return translucentChanged;
1933 }
1934 } finally {
1935 Binder.restoreCallingIdentity(origId);
1936 }
1937 }
1938
1939 @Override
1940 public boolean convertToTranslucent(IBinder token, Bundle options) {
1941 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1942 final long origId = Binder.clearCallingIdentity();
1943 try {
1944 synchronized (mGlobalLock) {
1945 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1946 if (r == null) {
1947 return false;
1948 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001949 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 int index = task.mActivities.lastIndexOf(r);
1951 if (index > 0) {
1952 ActivityRecord under = task.mActivities.get(index - 1);
1953 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1954 }
1955 final boolean translucentChanged = r.changeWindowTranslucency(false);
1956 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001957 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001958 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001959 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001960 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 return translucentChanged;
1962 }
1963 } finally {
1964 Binder.restoreCallingIdentity(origId);
1965 }
1966 }
1967
1968 @Override
1969 public void notifyActivityDrawn(IBinder token) {
1970 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1971 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001972 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001973 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001974 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 }
1976 }
1977 }
1978
1979 @Override
1980 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1981 synchronized (mGlobalLock) {
1982 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1983 if (r == null) {
1984 return;
1985 }
1986 r.reportFullyDrawnLocked(restoredFromBundle);
1987 }
1988 }
1989
1990 @Override
1991 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1992 synchronized (mGlobalLock) {
1993 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1994 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1995 return stack.mDisplayId;
1996 }
1997 return DEFAULT_DISPLAY;
1998 }
1999 }
2000
2001 @Override
2002 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002003 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002004 long ident = Binder.clearCallingIdentity();
2005 try {
2006 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002007 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002009 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 }
2011 return null;
2012 }
2013 } finally {
2014 Binder.restoreCallingIdentity(ident);
2015 }
2016 }
2017
2018 @Override
2019 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002020 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2022 final long callingId = Binder.clearCallingIdentity();
2023 try {
2024 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002025 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 if (stack == null) {
2027 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2028 return;
2029 }
2030 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002031 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002032 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 }
2034 }
2035 } finally {
2036 Binder.restoreCallingIdentity(callingId);
2037 }
2038 }
2039
2040 @Override
2041 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002042 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2044 final long callingId = Binder.clearCallingIdentity();
2045 try {
2046 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002047 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002048 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 if (task == null) {
2050 return;
2051 }
2052 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002053 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002054 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 }
2056 }
2057 } finally {
2058 Binder.restoreCallingIdentity(callingId);
2059 }
2060 }
2061
2062 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002063 public void restartActivityProcessIfVisible(IBinder activityToken) {
2064 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2065 final long callingId = Binder.clearCallingIdentity();
2066 try {
2067 synchronized (mGlobalLock) {
2068 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2069 if (r == null) {
2070 return;
2071 }
2072 r.restartProcessIfVisible();
2073 }
2074 } finally {
2075 Binder.restoreCallingIdentity(callingId);
2076 }
2077 }
2078
2079 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002080 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002081 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002082 synchronized (mGlobalLock) {
2083 final long ident = Binder.clearCallingIdentity();
2084 try {
2085 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2086 "remove-task");
2087 } finally {
2088 Binder.restoreCallingIdentity(ident);
2089 }
2090 }
2091 }
2092
2093 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002094 public void removeAllVisibleRecentTasks() {
2095 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2096 synchronized (mGlobalLock) {
2097 final long ident = Binder.clearCallingIdentity();
2098 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002099 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002100 } finally {
2101 Binder.restoreCallingIdentity(ident);
2102 }
2103 }
2104 }
2105
2106 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2108 synchronized (mGlobalLock) {
2109 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2110 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002111 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 }
2113 }
2114 return false;
2115 }
2116
2117 @Override
2118 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2119 Intent resultData) {
2120
2121 synchronized (mGlobalLock) {
2122 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2123 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002124 return r.getActivityStack().navigateUpToLocked(
2125 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002126 }
2127 return false;
2128 }
2129 }
2130
2131 /**
2132 * Attempts to move a task backwards in z-order (the order of activities within the task is
2133 * unchanged).
2134 *
2135 * There are several possible results of this call:
2136 * - if the task is locked, then we will show the lock toast
2137 * - if there is a task behind the provided task, then that task is made visible and resumed as
2138 * this task is moved to the back
2139 * - otherwise, if there are no other tasks in the stack:
2140 * - if this task is in the pinned stack, then we remove the stack completely, which will
2141 * have the effect of moving the task to the top or bottom of the fullscreen stack
2142 * (depending on whether it is visible)
2143 * - otherwise, we simply return home and hide this task
2144 *
2145 * @param token A reference to the activity we wish to move
2146 * @param nonRoot If false then this only works if the activity is the root
2147 * of a task; if true it will work for any activity in a task.
2148 * @return Returns true if the move completed, false if not.
2149 */
2150 @Override
2151 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002152 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002153 synchronized (mGlobalLock) {
2154 final long origId = Binder.clearCallingIdentity();
2155 try {
2156 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002157 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 if (task != null) {
2159 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2160 }
2161 } finally {
2162 Binder.restoreCallingIdentity(origId);
2163 }
2164 }
2165 return false;
2166 }
2167
2168 @Override
2169 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002170 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002171 long ident = Binder.clearCallingIdentity();
2172 Rect rect = new Rect();
2173 try {
2174 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002175 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2177 if (task == null) {
2178 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2179 return rect;
2180 }
2181 if (task.getStack() != null) {
2182 // Return the bounds from window manager since it will be adjusted for various
2183 // things like the presense of a docked stack for tasks that aren't resizeable.
2184 task.getWindowContainerBounds(rect);
2185 } else {
2186 // Task isn't in window manager yet since it isn't associated with a stack.
2187 // Return the persist value from activity manager
2188 if (!task.matchParentBounds()) {
2189 rect.set(task.getBounds());
2190 } else if (task.mLastNonFullscreenBounds != null) {
2191 rect.set(task.mLastNonFullscreenBounds);
2192 }
2193 }
2194 }
2195 } finally {
2196 Binder.restoreCallingIdentity(ident);
2197 }
2198 return rect;
2199 }
2200
2201 @Override
2202 public ActivityManager.TaskDescription getTaskDescription(int id) {
2203 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002204 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002205 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002206 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002207 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2208 if (tr != null) {
2209 return tr.lastTaskDescription;
2210 }
2211 }
2212 return null;
2213 }
2214
2215 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002216 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2217 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2218 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2219 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2220 return;
2221 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002223 synchronized (mGlobalLock) {
2224 final long ident = Binder.clearCallingIdentity();
2225 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002226 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002227 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002228 if (task == null) {
2229 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2230 return;
2231 }
2232
2233 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2234 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2235
2236 if (!task.isActivityTypeStandardOrUndefined()) {
2237 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2238 + " non-standard task " + taskId + " to windowing mode="
2239 + windowingMode);
2240 }
2241
2242 final ActivityStack stack = task.getStack();
2243 if (toTop) {
2244 stack.moveToFront("setTaskWindowingMode", task);
2245 }
2246 stack.setWindowingMode(windowingMode);
2247 } finally {
2248 Binder.restoreCallingIdentity(ident);
2249 }
2250 }
2251 }
2252
2253 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002254 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002255 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002256 ActivityRecord r = getCallingRecordLocked(token);
2257 return r != null ? r.info.packageName : null;
2258 }
2259 }
2260
2261 @Override
2262 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002263 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002264 ActivityRecord r = getCallingRecordLocked(token);
2265 return r != null ? r.intent.getComponent() : null;
2266 }
2267 }
2268
2269 private ActivityRecord getCallingRecordLocked(IBinder token) {
2270 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2271 if (r == null) {
2272 return null;
2273 }
2274 return r.resultTo;
2275 }
2276
2277 @Override
2278 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002279 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002280
2281 synchronized (mGlobalLock) {
2282 final long origId = Binder.clearCallingIdentity();
2283 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002284 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002285 } finally {
2286 Binder.restoreCallingIdentity(origId);
2287 }
2288 }
2289 }
2290
2291 /**
2292 * TODO: Add mController hook
2293 */
2294 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002295 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2296 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002297 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002298
2299 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2300 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002301 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2302 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002303 }
2304 }
2305
Ricky Waiaca8a772019-04-04 16:01:06 +01002306 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2307 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 boolean fromRecents) {
2309
Ricky Waiaca8a772019-04-04 16:01:06 +01002310 final int callingPid = Binder.getCallingPid();
2311 final int callingUid = Binder.getCallingUid();
2312 if (!isSameApp(callingUid, callingPackage)) {
2313 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2314 + Binder.getCallingPid() + " as package " + callingPackage;
2315 Slog.w(TAG, msg);
2316 throw new SecurityException(msg);
2317 }
2318 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319 SafeActivityOptions.abort(options);
2320 return;
2321 }
2322 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002323 WindowProcessController callerApp = null;
2324 if (appThread != null) {
2325 callerApp = getProcessController(appThread);
2326 }
2327 final ActivityStarter starter = getActivityStartController().obtainStarter(
2328 null /* intent */, "moveTaskToFront");
2329 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2330 -1, callerApp, null, false, null)) {
2331 boolean abort = !isBackgroundActivityStartsEnabled();
2332 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2333 if (abort) {
2334 return;
2335 }
2336 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002337 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002338 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002339 if (task == null) {
2340 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002341 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002342 return;
2343 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002344 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002345 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002346 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002347 return;
2348 }
2349 ActivityOptions realOptions = options != null
2350 ? options.getOptions(mStackSupervisor)
2351 : null;
2352 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2353 false /* forceNonResizable */);
2354
2355 final ActivityRecord topActivity = task.getTopActivity();
2356 if (topActivity != null) {
2357
2358 // We are reshowing a task, use a starting window to hide the initial draw delay
2359 // so the transition can start earlier.
2360 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2361 true /* taskSwitch */, fromRecents);
2362 }
2363 } finally {
2364 Binder.restoreCallingIdentity(origId);
2365 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002366 }
2367
Ricky Waiaca8a772019-04-04 16:01:06 +01002368 /**
2369 * Return true if callingUid is system, or packageName belongs to that callingUid.
2370 */
2371 boolean isSameApp(int callingUid, @Nullable String packageName) {
2372 try {
2373 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2374 if (packageName == null) {
2375 return false;
2376 }
2377 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2378 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2379 UserHandle.getUserId(callingUid));
2380 return UserHandle.isSameApp(callingUid, uid);
2381 }
2382 } catch (RemoteException e) {
2383 // Should not happen
2384 }
2385 return true;
2386 }
2387
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002388 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2389 int callingPid, int callingUid, String name) {
2390 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2391 return true;
2392 }
2393
2394 if (getRecentTasks().isCallerRecents(sourceUid)) {
2395 return true;
2396 }
2397
2398 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2399 if (perm == PackageManager.PERMISSION_GRANTED) {
2400 return true;
2401 }
2402 if (checkAllowAppSwitchUid(sourceUid)) {
2403 return true;
2404 }
2405
2406 // If the actual IPC caller is different from the logical source, then
2407 // also see if they are allowed to control app switches.
2408 if (callingUid != -1 && callingUid != sourceUid) {
2409 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2410 if (perm == PackageManager.PERMISSION_GRANTED) {
2411 return true;
2412 }
2413 if (checkAllowAppSwitchUid(callingUid)) {
2414 return true;
2415 }
2416 }
2417
2418 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2419 return false;
2420 }
2421
2422 private boolean checkAllowAppSwitchUid(int uid) {
2423 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2424 if (types != null) {
2425 for (int i = types.size() - 1; i >= 0; i--) {
2426 if (types.valueAt(i).intValue() == uid) {
2427 return true;
2428 }
2429 }
2430 }
2431 return false;
2432 }
2433
2434 @Override
2435 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2436 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2437 "setActivityController()");
2438 synchronized (mGlobalLock) {
2439 mController = controller;
2440 mControllerIsAMonkey = imAMonkey;
2441 Watchdog.getInstance().setActivityController(controller);
2442 }
2443 }
2444
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002445 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002446 synchronized (mGlobalLock) {
2447 return mController != null && mControllerIsAMonkey;
2448 }
2449 }
2450
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002451 @Override
2452 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2453 synchronized (mGlobalLock) {
2454 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2455 }
2456 }
2457
2458 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002459 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2460 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2461 }
2462
2463 @Override
2464 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2465 @WindowConfiguration.ActivityType int ignoreActivityType,
2466 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2467 final int callingUid = Binder.getCallingUid();
2468 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2469
2470 synchronized (mGlobalLock) {
2471 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2472
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002473 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002474 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002475 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002476 ignoreWindowingMode, callingUid, allowed);
2477 }
2478
2479 return list;
2480 }
2481
2482 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002483 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2484 synchronized (mGlobalLock) {
2485 final long origId = Binder.clearCallingIdentity();
2486 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2487 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002488 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002489 }
2490 Binder.restoreCallingIdentity(origId);
2491 }
2492 }
2493
2494 @Override
2495 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002497 ActivityStack stack = ActivityRecord.getStackLocked(token);
2498 if (stack != null) {
2499 return stack.willActivityBeVisibleLocked(token);
2500 }
2501 return false;
2502 }
2503 }
2504
2505 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002506 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002507 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 synchronized (mGlobalLock) {
2509 final long ident = Binder.clearCallingIdentity();
2510 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002511 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002512 if (task == null) {
2513 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2514 return;
2515 }
2516
2517 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2518 + " to stackId=" + stackId + " toTop=" + toTop);
2519
Wale Ogunwaled32da472018-11-16 07:19:28 -08002520 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002521 if (stack == null) {
2522 throw new IllegalStateException(
2523 "moveTaskToStack: No stack for stackId=" + stackId);
2524 }
2525 if (!stack.isActivityTypeStandardOrUndefined()) {
2526 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2527 + taskId + " to stack " + stackId);
2528 }
2529 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002530 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002531 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2532 }
2533 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2534 "moveTaskToStack");
2535 } finally {
2536 Binder.restoreCallingIdentity(ident);
2537 }
2538 }
2539 }
2540
2541 @Override
2542 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2543 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002544 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002545
2546 final long ident = Binder.clearCallingIdentity();
2547 try {
2548 synchronized (mGlobalLock) {
2549 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002550 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002551 if (stack == null) {
2552 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2553 return;
2554 }
2555 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2556 throw new IllegalArgumentException("Stack: " + stackId
2557 + " doesn't support animated resize.");
2558 }
2559 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2560 animationDuration, false /* fromFullscreen */);
2561 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002562 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002563 if (stack == null) {
2564 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2565 return;
2566 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002567 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002568 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2569 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2570 }
2571 }
2572 } finally {
2573 Binder.restoreCallingIdentity(ident);
2574 }
2575 }
2576
wilsonshih5c4cf522019-01-25 09:03:47 +08002577 @Override
2578 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2579 int animationDuration) {
2580 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2581
2582 final long ident = Binder.clearCallingIdentity();
2583 try {
2584 synchronized (mGlobalLock) {
2585 if (xOffset == 0 && yOffset == 0) {
2586 return;
2587 }
2588 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2589 if (stack == null) {
2590 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2591 return;
2592 }
2593 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2594 throw new IllegalArgumentException("Stack: " + stackId
2595 + " doesn't support animated resize.");
2596 }
2597 final Rect destBounds = new Rect();
2598 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002599 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002600 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2601 return;
2602 }
2603 destBounds.offset(xOffset, yOffset);
2604 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2605 animationDuration, false /* fromFullscreen */);
2606 }
2607 } finally {
2608 Binder.restoreCallingIdentity(ident);
2609 }
2610 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002611 /**
2612 * Moves the specified task to the primary-split-screen stack.
2613 *
2614 * @param taskId Id of task to move.
2615 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2616 * exist already. See
2617 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2618 * and
2619 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2620 * @param toTop If the task and stack should be moved to the top.
2621 * @param animate Whether we should play an animation for the moving the task.
2622 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2623 * stack. Pass {@code null} to use default bounds.
2624 * @param showRecents If the recents activity should be shown on the other side of the task
2625 * going into split-screen mode.
2626 */
2627 @Override
2628 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2629 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002630 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002631 "setTaskWindowingModeSplitScreenPrimary()");
2632 synchronized (mGlobalLock) {
2633 final long ident = Binder.clearCallingIdentity();
2634 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002635 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002636 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002637 if (task == null) {
2638 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2639 return false;
2640 }
2641 if (DEBUG_STACK) Slog.d(TAG_STACK,
2642 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2643 + " to createMode=" + createMode + " toTop=" + toTop);
2644 if (!task.isActivityTypeStandardOrUndefined()) {
2645 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2646 + " non-standard task " + taskId + " to split-screen windowing mode");
2647 }
2648
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002649 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002650 final int windowingMode = task.getWindowingMode();
2651 final ActivityStack stack = task.getStack();
2652 if (toTop) {
2653 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2654 }
2655 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002656 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2657 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002658 return windowingMode != task.getWindowingMode();
2659 } finally {
2660 Binder.restoreCallingIdentity(ident);
2661 }
2662 }
2663 }
2664
2665 /**
2666 * Removes stacks in the input windowing modes from the system if they are of activity type
2667 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2668 */
2669 @Override
2670 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002671 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002672 "removeStacksInWindowingModes()");
2673
2674 synchronized (mGlobalLock) {
2675 final long ident = Binder.clearCallingIdentity();
2676 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002677 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 } finally {
2679 Binder.restoreCallingIdentity(ident);
2680 }
2681 }
2682 }
2683
2684 @Override
2685 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002686 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002687 "removeStacksWithActivityTypes()");
2688
2689 synchronized (mGlobalLock) {
2690 final long ident = Binder.clearCallingIdentity();
2691 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002692 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002693 } finally {
2694 Binder.restoreCallingIdentity(ident);
2695 }
2696 }
2697 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002698
2699 @Override
2700 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2701 int userId) {
2702 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002703 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2704 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002705 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002706 final boolean detailed = checkGetTasksPermission(
2707 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2708 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 == PackageManager.PERMISSION_GRANTED;
2710
2711 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002712 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713 callingUid);
2714 }
2715 }
2716
2717 @Override
2718 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002719 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 long ident = Binder.clearCallingIdentity();
2721 try {
2722 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002723 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002724 }
2725 } finally {
2726 Binder.restoreCallingIdentity(ident);
2727 }
2728 }
2729
2730 @Override
2731 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002732 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002733 long ident = Binder.clearCallingIdentity();
2734 try {
2735 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002736 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002737 }
2738 } finally {
2739 Binder.restoreCallingIdentity(ident);
2740 }
2741 }
2742
2743 @Override
2744 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002745 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002746 final long callingUid = Binder.getCallingUid();
2747 final long origId = Binder.clearCallingIdentity();
2748 try {
2749 synchronized (mGlobalLock) {
2750 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002751 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2753 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2754 }
2755 } finally {
2756 Binder.restoreCallingIdentity(origId);
2757 }
2758 }
2759
2760 @Override
2761 public void startLockTaskModeByToken(IBinder token) {
2762 synchronized (mGlobalLock) {
2763 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2764 if (r == null) {
2765 return;
2766 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002767 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 }
2769 }
2770
2771 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002772 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002773 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 // This makes inner call to look as if it was initiated by system.
2775 long ident = Binder.clearCallingIdentity();
2776 try {
2777 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002778 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002779 MATCH_TASK_IN_STACKS_ONLY);
2780 if (task == null) {
2781 return;
2782 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783
2784 // When starting lock task mode the stack must be in front and focused
2785 task.getStack().moveToFront("startSystemLockTaskMode");
2786 startLockTaskModeLocked(task, true /* isSystemCaller */);
2787 }
2788 } finally {
2789 Binder.restoreCallingIdentity(ident);
2790 }
2791 }
2792
2793 @Override
2794 public void stopLockTaskModeByToken(IBinder token) {
2795 synchronized (mGlobalLock) {
2796 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2797 if (r == null) {
2798 return;
2799 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002800 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002801 }
2802 }
2803
2804 /**
2805 * This API should be called by SystemUI only when user perform certain action to dismiss
2806 * lock task mode. We should only dismiss pinned lock task mode in this case.
2807 */
2808 @Override
2809 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002810 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2812 }
2813
2814 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2815 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2816 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2817 return;
2818 }
2819
Wale Ogunwaled32da472018-11-16 07:19:28 -08002820 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 if (stack == null || task != stack.topTask()) {
2822 throw new IllegalArgumentException("Invalid task, not in foreground");
2823 }
2824
2825 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2826 // system or a specific app.
2827 // * System-initiated requests will only start the pinned mode (screen pinning)
2828 // * App-initiated requests
2829 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2830 // - will start the pinned mode, otherwise
2831 final int callingUid = Binder.getCallingUid();
2832 long ident = Binder.clearCallingIdentity();
2833 try {
2834 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002835 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002837 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002838 } finally {
2839 Binder.restoreCallingIdentity(ident);
2840 }
2841 }
2842
2843 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2844 final int callingUid = Binder.getCallingUid();
2845 long ident = Binder.clearCallingIdentity();
2846 try {
2847 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002848 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 }
2850 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2851 // task and jumping straight into a call in the case of emergency call back.
2852 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2853 if (tm != null) {
2854 tm.showInCallScreen(false);
2855 }
2856 } finally {
2857 Binder.restoreCallingIdentity(ident);
2858 }
2859 }
2860
2861 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002862 public void updateLockTaskPackages(int userId, String[] packages) {
2863 final int callingUid = Binder.getCallingUid();
2864 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2865 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2866 "updateLockTaskPackages()");
2867 }
2868 synchronized (this) {
2869 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2870 + Arrays.toString(packages));
2871 getLockTaskController().updateLockTaskPackages(userId, packages);
2872 }
2873 }
2874
2875 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 public boolean isInLockTaskMode() {
2877 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2878 }
2879
2880 @Override
2881 public int getLockTaskModeState() {
2882 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002883 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002884 }
2885 }
2886
2887 @Override
2888 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2889 synchronized (mGlobalLock) {
2890 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2891 if (r != null) {
2892 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002893 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002894 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002895 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002896 }
2897 }
2898 }
2899
2900 @Override
2901 public Bundle getActivityOptions(IBinder token) {
2902 final long origId = Binder.clearCallingIdentity();
2903 try {
2904 synchronized (mGlobalLock) {
2905 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2906 if (r != null) {
2907 final ActivityOptions activityOptions = r.takeOptionsLocked();
2908 return activityOptions == null ? null : activityOptions.toBundle();
2909 }
2910 return null;
2911 }
2912 } finally {
2913 Binder.restoreCallingIdentity(origId);
2914 }
2915 }
2916
2917 @Override
2918 public List<IBinder> getAppTasks(String callingPackage) {
2919 int callingUid = Binder.getCallingUid();
2920 long ident = Binder.clearCallingIdentity();
2921 try {
2922 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002923 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924 }
2925 } finally {
2926 Binder.restoreCallingIdentity(ident);
2927 }
2928 }
2929
2930 @Override
2931 public void finishVoiceTask(IVoiceInteractionSession session) {
2932 synchronized (mGlobalLock) {
2933 final long origId = Binder.clearCallingIdentity();
2934 try {
2935 // TODO: VI Consider treating local voice interactions and voice tasks
2936 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002937 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 } finally {
2939 Binder.restoreCallingIdentity(origId);
2940 }
2941 }
2942
2943 }
2944
2945 @Override
2946 public boolean isTopOfTask(IBinder token) {
2947 synchronized (mGlobalLock) {
2948 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002949 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 }
2951 }
2952
2953 @Override
2954 public void notifyLaunchTaskBehindComplete(IBinder token) {
2955 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2956 }
2957
2958 @Override
2959 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002960 mH.post(() -> {
2961 synchronized (mGlobalLock) {
2962 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002963 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002964 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002965 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002966 } catch (RemoteException e) {
2967 }
2968 }
2969 }
2970
2971 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002972 }
2973
2974 /** Called from an app when assist data is ready. */
2975 @Override
2976 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2977 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002978 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002979 synchronized (pae) {
2980 pae.result = extras;
2981 pae.structure = structure;
2982 pae.content = content;
2983 if (referrer != null) {
2984 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2985 }
2986 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002987 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002988 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2989 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 structure.setHomeActivity(pae.isHome);
2991 }
2992 pae.haveResult = true;
2993 pae.notifyAll();
2994 if (pae.intent == null && pae.receiver == null) {
2995 // Caller is just waiting for the result.
2996 return;
2997 }
2998 }
2999 // We are now ready to launch the assist activity.
3000 IAssistDataReceiver sendReceiver = null;
3001 Bundle sendBundle = null;
3002 synchronized (mGlobalLock) {
3003 buildAssistBundleLocked(pae, extras);
3004 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003005 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003006 if (!exists) {
3007 // Timed out.
3008 return;
3009 }
3010
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003011 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003012 // Caller wants result sent back to them.
3013 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003014 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3015 pae.activity.getTaskRecord().taskId);
3016 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3017 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003018 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3019 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3020 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3021 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3022 }
3023 }
3024 if (sendReceiver != null) {
3025 try {
3026 sendReceiver.onHandleAssistData(sendBundle);
3027 } catch (RemoteException e) {
3028 }
3029 return;
3030 }
3031
3032 final long ident = Binder.clearCallingIdentity();
3033 try {
3034 if (TextUtils.equals(pae.intent.getAction(),
3035 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3036 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003037
3038 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003039 } else {
3040 pae.intent.replaceExtras(pae.extras);
3041 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3042 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3043 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003044 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045
3046 try {
3047 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3048 } catch (ActivityNotFoundException e) {
3049 Slog.w(TAG, "No activity to handle assist action.", e);
3050 }
3051 }
3052 } finally {
3053 Binder.restoreCallingIdentity(ident);
3054 }
3055 }
3056
Marvin Ramin830d4e32019-03-12 13:16:58 +01003057 /**
3058 * Workaround for historical API which starts the Assist service with a non-foreground
3059 * {@code startService()} call.
3060 */
3061 private void startVoiceInteractionServiceAsUser(
3062 Intent intent, int userHandle, String reason) {
3063 // Resolve the intent to find out which package we need to whitelist.
3064 ResolveInfo resolveInfo =
3065 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3066 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3067 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3068 return;
3069 }
3070 intent.setPackage(resolveInfo.serviceInfo.packageName);
3071
3072 // Whitelist background services temporarily.
3073 LocalServices.getService(DeviceIdleController.LocalService.class)
3074 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3075 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3076
3077 // Finally, try to start the service.
3078 try {
3079 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3080 } catch (RuntimeException e) {
3081 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3082 }
3083 }
3084
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085 @Override
3086 public int addAppTask(IBinder activityToken, Intent intent,
3087 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3088 final int callingUid = Binder.getCallingUid();
3089 final long callingIdent = Binder.clearCallingIdentity();
3090
3091 try {
3092 synchronized (mGlobalLock) {
3093 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3094 if (r == null) {
3095 throw new IllegalArgumentException("Activity does not exist; token="
3096 + activityToken);
3097 }
3098 ComponentName comp = intent.getComponent();
3099 if (comp == null) {
3100 throw new IllegalArgumentException("Intent " + intent
3101 + " must specify explicit component");
3102 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003103 if (thumbnail.getWidth() != mThumbnailWidth
3104 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003105 throw new IllegalArgumentException("Bad thumbnail size: got "
3106 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003107 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003108 }
3109 if (intent.getSelector() != null) {
3110 intent.setSelector(null);
3111 }
3112 if (intent.getSourceBounds() != null) {
3113 intent.setSourceBounds(null);
3114 }
3115 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3116 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3117 // The caller has added this as an auto-remove task... that makes no
3118 // sense, so turn off auto-remove.
3119 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3120 }
3121 }
3122 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3123 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3124 if (ainfo.applicationInfo.uid != callingUid) {
3125 throw new SecurityException(
3126 "Can't add task for another application: target uid="
3127 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3128 }
3129
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003130 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003132 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003133 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003134 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 // The app has too many tasks already and we can't add any more
3136 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3137 return INVALID_TASK_ID;
3138 }
3139 task.lastTaskDescription.copyFrom(description);
3140
3141 // TODO: Send the thumbnail to WM to store it.
3142
3143 return task.taskId;
3144 }
3145 } finally {
3146 Binder.restoreCallingIdentity(callingIdent);
3147 }
3148 }
3149
3150 @Override
3151 public Point getAppTaskThumbnailSize() {
3152 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003153 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 }
3155 }
3156
3157 @Override
3158 public void setTaskResizeable(int taskId, int resizeableMode) {
3159 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003160 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003161 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3162 if (task == null) {
3163 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3164 return;
3165 }
3166 task.setResizeMode(resizeableMode);
3167 }
3168 }
3169
3170 @Override
3171 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003172 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 long ident = Binder.clearCallingIdentity();
3174 try {
3175 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003176 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003177 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 if (task == null) {
3179 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3180 return;
3181 }
3182 // Place the task in the right stack if it isn't there already based on
3183 // the requested bounds.
3184 // The stack transition logic is:
3185 // - a null bounds on a freeform task moves that task to fullscreen
3186 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3187 // that task to freeform
3188 // - otherwise the task is not moved
3189 ActivityStack stack = task.getStack();
3190 if (!task.getWindowConfiguration().canResizeTask()) {
3191 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3192 }
3193 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3194 stack = stack.getDisplay().getOrCreateStack(
3195 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3196 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3197 stack = stack.getDisplay().getOrCreateStack(
3198 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3199 }
3200
3201 // Reparent the task to the right stack if necessary
3202 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3203 if (stack != task.getStack()) {
3204 // Defer resume until the task is resized below
3205 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3206 DEFER_RESUME, "resizeTask");
3207 preserveWindow = false;
3208 }
3209
3210 // After reparenting (which only resizes the task to the stack bounds), resize the
3211 // task to the actual bounds provided
3212 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3213 }
3214 } finally {
3215 Binder.restoreCallingIdentity(ident);
3216 }
3217 }
3218
3219 @Override
3220 public boolean releaseActivityInstance(IBinder token) {
3221 synchronized (mGlobalLock) {
3222 final long origId = Binder.clearCallingIdentity();
3223 try {
3224 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3225 if (r == null) {
3226 return false;
3227 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003228 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003229 } finally {
3230 Binder.restoreCallingIdentity(origId);
3231 }
3232 }
3233 }
3234
3235 @Override
3236 public void releaseSomeActivities(IApplicationThread appInt) {
3237 synchronized (mGlobalLock) {
3238 final long origId = Binder.clearCallingIdentity();
3239 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003240 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003241 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 } finally {
3243 Binder.restoreCallingIdentity(origId);
3244 }
3245 }
3246 }
3247
3248 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003249 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003250 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 != PackageManager.PERMISSION_GRANTED) {
3252 throw new SecurityException("Requires permission "
3253 + android.Manifest.permission.DEVICE_POWER);
3254 }
3255
3256 synchronized (mGlobalLock) {
3257 long ident = Binder.clearCallingIdentity();
3258 if (mKeyguardShown != keyguardShowing) {
3259 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003260 final Message msg = PooledLambda.obtainMessage(
3261 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3262 keyguardShowing);
3263 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 }
3265 try {
wilsonshih177261f2019-02-22 12:02:18 +08003266 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003267 } finally {
3268 Binder.restoreCallingIdentity(ident);
3269 }
3270 }
3271
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003272 mH.post(() -> {
3273 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3274 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3275 }
3276 });
3277 }
3278
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003279 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003280 mH.post(() -> {
3281 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3282 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3283 }
3284 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 }
3286
3287 @Override
3288 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003289 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3290 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003291
3292 final File passedIconFile = new File(filePath);
3293 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3294 passedIconFile.getName());
3295 if (!legitIconFile.getPath().equals(filePath)
3296 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3297 throw new IllegalArgumentException("Bad file path: " + filePath
3298 + " passed for userId " + userId);
3299 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003300 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003301 }
3302
3303 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003304 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003305 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3306 final ActivityOptions activityOptions = safeOptions != null
3307 ? safeOptions.getOptions(mStackSupervisor)
3308 : null;
3309 if (activityOptions == null
3310 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3311 || activityOptions.getCustomInPlaceResId() == 0) {
3312 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3313 "with valid animation");
3314 }
lumark588a3e82018-07-20 18:53:54 +08003315 // Get top display of front most application.
3316 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3317 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003318 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3319 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3320 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003321 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003322 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003323 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 }
3325
3326 @Override
3327 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003328 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003329 synchronized (mGlobalLock) {
3330 final long ident = Binder.clearCallingIdentity();
3331 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003332 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 if (stack == null) {
3334 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3335 return;
3336 }
3337 if (!stack.isActivityTypeStandardOrUndefined()) {
3338 throw new IllegalArgumentException(
3339 "Removing non-standard stack is not allowed.");
3340 }
3341 mStackSupervisor.removeStack(stack);
3342 } finally {
3343 Binder.restoreCallingIdentity(ident);
3344 }
3345 }
3346 }
3347
3348 @Override
3349 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003350 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351
3352 synchronized (mGlobalLock) {
3353 final long ident = Binder.clearCallingIdentity();
3354 try {
3355 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3356 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003357 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003358 } finally {
3359 Binder.restoreCallingIdentity(ident);
3360 }
3361 }
3362 }
3363
3364 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003365 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003366 synchronized (mGlobalLock) {
3367 long ident = Binder.clearCallingIdentity();
3368 try {
3369 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3370 if (r == null) {
3371 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003372 "toggleFreeformWindowingMode: No activity record matching token="
3373 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 }
3375
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003376 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003377 if (stack == null) {
3378 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3379 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380 }
3381
Yunfan Chend967af82019-01-17 18:30:18 +09003382 if (!stack.inFreeformWindowingMode()
3383 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3384 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3385 + "toggle between fullscreen and freeform.");
3386 }
3387
3388 if (stack.inFreeformWindowingMode()) {
3389 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003390 } else if (stack.getParent().inFreeformWindowingMode()) {
3391 // If the window is on a freeform display, set it to undefined. It will be
3392 // resolved to freeform and it can adjust windowing mode when the display mode
3393 // changes in runtime.
3394 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003395 } else {
3396 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3397 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003398 } finally {
3399 Binder.restoreCallingIdentity(ident);
3400 }
3401 }
3402 }
3403
3404 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3405 @Override
3406 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003407 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003408 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003409 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003410 }
3411
3412 /** Unregister a task stack listener so that it stops receiving callbacks. */
3413 @Override
3414 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003415 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003416 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003417 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003418 }
3419
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 @Override
3421 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3422 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3423 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3424 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3425 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3426 }
3427
3428 @Override
3429 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3430 IBinder activityToken, int flags) {
3431 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3432 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3433 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3434 }
3435
3436 @Override
3437 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3438 Bundle args) {
3439 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3440 true /* focused */, true /* newSessionId */, userHandle, args,
3441 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3442 }
3443
3444 @Override
3445 public Bundle getAssistContextExtras(int requestType) {
3446 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3447 null, null, true /* focused */, true /* newSessionId */,
3448 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3449 if (pae == null) {
3450 return null;
3451 }
3452 synchronized (pae) {
3453 while (!pae.haveResult) {
3454 try {
3455 pae.wait();
3456 } catch (InterruptedException e) {
3457 }
3458 }
3459 }
3460 synchronized (mGlobalLock) {
3461 buildAssistBundleLocked(pae, pae.result);
3462 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003463 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 }
3465 return pae.extras;
3466 }
3467
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003468 /**
3469 * Binder IPC calls go through the public entry point.
3470 * This can be called with or without the global lock held.
3471 */
3472 private static int checkCallingPermission(String permission) {
3473 return checkPermission(
3474 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3475 }
3476
3477 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003478 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003479 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3480 mAmInternal.enforceCallingPermission(permission, func);
3481 }
3482 }
3483
3484 @VisibleForTesting
3485 int checkGetTasksPermission(String permission, int pid, int uid) {
3486 return checkPermission(permission, pid, uid);
3487 }
3488
3489 static int checkPermission(String permission, int pid, int uid) {
3490 if (permission == null) {
3491 return PackageManager.PERMISSION_DENIED;
3492 }
3493 return checkComponentPermission(permission, pid, uid, -1, true);
3494 }
3495
Wale Ogunwale214f3482018-10-04 11:00:47 -07003496 public static int checkComponentPermission(String permission, int pid, int uid,
3497 int owningUid, boolean exported) {
3498 return ActivityManagerService.checkComponentPermission(
3499 permission, pid, uid, owningUid, exported);
3500 }
3501
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003502 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3503 if (getRecentTasks().isCallerRecents(callingUid)) {
3504 // Always allow the recents component to get tasks
3505 return true;
3506 }
3507
3508 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3509 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3510 if (!allowed) {
3511 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3512 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3513 // Temporary compatibility: some existing apps on the system image may
3514 // still be requesting the old permission and not switched to the new
3515 // one; if so, we'll still allow them full access. This means we need
3516 // to see if they are holding the old permission and are a system app.
3517 try {
3518 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3519 allowed = true;
3520 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3521 + " is using old GET_TASKS but privileged; allowing");
3522 }
3523 } catch (RemoteException e) {
3524 }
3525 }
3526 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3527 + " does not hold REAL_GET_TASKS; limiting output");
3528 }
3529 return allowed;
3530 }
3531
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003532 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3533 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3534 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3535 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003536 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003537 "enqueueAssistContext()");
3538
3539 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003540 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003541 if (activity == null) {
3542 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
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, "getAssistContextExtras failed: no process for " + activity);
3547 return null;
3548 }
3549 if (focused) {
3550 if (activityToken != null) {
3551 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3552 if (activity != caller) {
3553 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3554 + " is not current top " + activity);
3555 return null;
3556 }
3557 }
3558 } else {
3559 activity = ActivityRecord.forTokenLocked(activityToken);
3560 if (activity == null) {
3561 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3562 + " couldn't be found");
3563 return null;
3564 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003565 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3567 return null;
3568 }
3569 }
3570
3571 PendingAssistExtras pae;
3572 Bundle extras = new Bundle();
3573 if (args != null) {
3574 extras.putAll(args);
3575 }
3576 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003577 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003578
3579 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3580 userHandle);
3581 pae.isHome = activity.isActivityTypeHome();
3582
3583 // Increment the sessionId if necessary
3584 if (newSessionId) {
3585 mViSessionId++;
3586 }
3587 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003588 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3589 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003591 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003592 } catch (RemoteException e) {
3593 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3594 return null;
3595 }
3596 return pae;
3597 }
3598 }
3599
3600 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3601 if (result != null) {
3602 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3603 }
3604 if (pae.hint != null) {
3605 pae.extras.putBoolean(pae.hint, true);
3606 }
3607 }
3608
3609 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3610 IAssistDataReceiver receiver;
3611 synchronized (mGlobalLock) {
3612 mPendingAssistExtras.remove(pae);
3613 receiver = pae.receiver;
3614 }
3615 if (receiver != null) {
3616 // Caller wants result sent back to them.
3617 Bundle sendBundle = new Bundle();
3618 // At least return the receiver extras
3619 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3620 try {
3621 pae.receiver.onHandleAssistData(sendBundle);
3622 } catch (RemoteException e) {
3623 }
3624 }
3625 }
3626
3627 public class PendingAssistExtras extends Binder implements Runnable {
3628 public final ActivityRecord activity;
3629 public boolean isHome;
3630 public final Bundle extras;
3631 public final Intent intent;
3632 public final String hint;
3633 public final IAssistDataReceiver receiver;
3634 public final int userHandle;
3635 public boolean haveResult = false;
3636 public Bundle result = null;
3637 public AssistStructure structure = null;
3638 public AssistContent content = null;
3639 public Bundle receiverExtras;
3640
3641 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3642 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3643 int _userHandle) {
3644 activity = _activity;
3645 extras = _extras;
3646 intent = _intent;
3647 hint = _hint;
3648 receiver = _receiver;
3649 receiverExtras = _receiverExtras;
3650 userHandle = _userHandle;
3651 }
3652
3653 @Override
3654 public void run() {
3655 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3656 synchronized (this) {
3657 haveResult = true;
3658 notifyAll();
3659 }
3660 pendingAssistExtrasTimedOut(this);
3661 }
3662 }
3663
3664 @Override
3665 public boolean isAssistDataAllowedOnCurrentActivity() {
3666 int userId;
3667 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003668 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3670 return false;
3671 }
3672
3673 final ActivityRecord activity = focusedStack.getTopActivity();
3674 if (activity == null) {
3675 return false;
3676 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003677 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003678 }
3679 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3680 }
3681
3682 @Override
3683 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3684 long ident = Binder.clearCallingIdentity();
3685 try {
3686 synchronized (mGlobalLock) {
3687 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003688 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003689 if (top != caller) {
3690 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3691 + " is not current top " + top);
3692 return false;
3693 }
3694 if (!top.nowVisible) {
3695 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3696 + " is not visible");
3697 return false;
3698 }
3699 }
3700 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3701 token);
3702 } finally {
3703 Binder.restoreCallingIdentity(ident);
3704 }
3705 }
3706
3707 @Override
3708 public boolean isRootVoiceInteraction(IBinder token) {
3709 synchronized (mGlobalLock) {
3710 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3711 if (r == null) {
3712 return false;
3713 }
3714 return r.rootVoiceInteraction;
3715 }
3716 }
3717
Wale Ogunwalef6733932018-06-27 05:14:34 -07003718 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3719 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3720 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3721 if (activityToCallback == null) return;
3722 activityToCallback.setVoiceSessionLocked(voiceSession);
3723
3724 // Inform the activity
3725 try {
3726 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3727 voiceInteractor);
3728 long token = Binder.clearCallingIdentity();
3729 try {
3730 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3731 } finally {
3732 Binder.restoreCallingIdentity(token);
3733 }
3734 // TODO: VI Should we cache the activity so that it's easier to find later
3735 // rather than scan through all the stacks and activities?
3736 } catch (RemoteException re) {
3737 activityToCallback.clearVoiceSessionLocked();
3738 // TODO: VI Should this terminate the voice session?
3739 }
3740 }
3741
3742 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3743 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3744 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3745 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3746 boolean wasRunningVoice = mRunningVoice != null;
3747 mRunningVoice = session;
3748 if (!wasRunningVoice) {
3749 mVoiceWakeLock.acquire();
3750 updateSleepIfNeededLocked();
3751 }
3752 }
3753 }
3754
3755 void finishRunningVoiceLocked() {
3756 if (mRunningVoice != null) {
3757 mRunningVoice = null;
3758 mVoiceWakeLock.release();
3759 updateSleepIfNeededLocked();
3760 }
3761 }
3762
3763 @Override
3764 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3765 synchronized (mGlobalLock) {
3766 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3767 if (keepAwake) {
3768 mVoiceWakeLock.acquire();
3769 } else {
3770 mVoiceWakeLock.release();
3771 }
3772 }
3773 }
3774 }
3775
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003776 @Override
3777 public ComponentName getActivityClassForToken(IBinder token) {
3778 synchronized (mGlobalLock) {
3779 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3780 if (r == null) {
3781 return null;
3782 }
3783 return r.intent.getComponent();
3784 }
3785 }
3786
3787 @Override
3788 public String getPackageForToken(IBinder token) {
3789 synchronized (mGlobalLock) {
3790 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3791 if (r == null) {
3792 return null;
3793 }
3794 return r.packageName;
3795 }
3796 }
3797
3798 @Override
3799 public void showLockTaskEscapeMessage(IBinder token) {
3800 synchronized (mGlobalLock) {
3801 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3802 if (r == null) {
3803 return;
3804 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003805 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003806 }
3807 }
3808
3809 @Override
3810 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003811 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003812 final long token = Binder.clearCallingIdentity();
3813 try {
3814 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003815 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003816 }
3817 } finally {
3818 Binder.restoreCallingIdentity(token);
3819 }
3820 }
3821
3822 /**
3823 * Try to place task to provided position. The final position might be different depending on
3824 * current user and stacks state. The task will be moved to target stack if it's currently in
3825 * different stack.
3826 */
3827 @Override
3828 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003829 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003830 synchronized (mGlobalLock) {
3831 long ident = Binder.clearCallingIdentity();
3832 try {
3833 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3834 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003835 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 if (task == null) {
3837 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3838 + taskId);
3839 }
3840
Wale Ogunwaled32da472018-11-16 07:19:28 -08003841 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003842
3843 if (stack == null) {
3844 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3845 + stackId);
3846 }
3847 if (!stack.isActivityTypeStandardOrUndefined()) {
3848 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3849 + " the position of task " + taskId + " in/to non-standard stack");
3850 }
3851
3852 // TODO: Have the callers of this API call a separate reparent method if that is
3853 // what they intended to do vs. having this method also do reparenting.
3854 if (task.getStack() == stack) {
3855 // Change position in current stack.
3856 stack.positionChildAt(task, position);
3857 } else {
3858 // Reparent to new stack.
3859 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3860 !DEFER_RESUME, "positionTaskInStack");
3861 }
3862 } finally {
3863 Binder.restoreCallingIdentity(ident);
3864 }
3865 }
3866 }
3867
3868 @Override
3869 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3870 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3871 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3872 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3873 synchronized (mGlobalLock) {
3874 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3875 if (record == null) {
3876 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3877 + "found for: " + token);
3878 }
3879 record.setSizeConfigurations(horizontalSizeConfiguration,
3880 verticalSizeConfigurations, smallestSizeConfigurations);
3881 }
3882 }
3883
3884 /**
3885 * Dismisses split-screen multi-window mode.
3886 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3887 */
3888 @Override
3889 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003890 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003891 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3892 final long ident = Binder.clearCallingIdentity();
3893 try {
3894 synchronized (mGlobalLock) {
3895 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003896 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003897 if (stack == null) {
3898 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3899 return;
3900 }
3901
3902 if (toTop) {
3903 // Caller wants the current split-screen primary stack to be the top stack after
3904 // it goes fullscreen, so move it to the front.
3905 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003906 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003907 // In this case the current split-screen primary stack shouldn't be the top
3908 // stack after it goes fullscreen, but it current has focus, so we move the
3909 // focus to the top-most split-screen secondary stack next to it.
3910 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3911 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3912 if (otherStack != null) {
3913 otherStack.moveToFront("dismissSplitScreenMode_other");
3914 }
3915 }
3916
Evan Rosky10475742018-09-05 19:02:48 -07003917 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918 }
3919 } finally {
3920 Binder.restoreCallingIdentity(ident);
3921 }
3922 }
3923
3924 /**
3925 * Dismisses Pip
3926 * @param animate True if the dismissal should be animated.
3927 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3928 * default animation duration should be used.
3929 */
3930 @Override
3931 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003932 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 final long ident = Binder.clearCallingIdentity();
3934 try {
3935 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003936 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003937 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 if (stack == null) {
3939 Slog.w(TAG, "dismissPip: pinned stack not found.");
3940 return;
3941 }
3942 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3943 throw new IllegalArgumentException("Stack: " + stack
3944 + " doesn't support animated resize.");
3945 }
3946 if (animate) {
3947 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3948 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3949 } else {
3950 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3951 }
3952 }
3953 } finally {
3954 Binder.restoreCallingIdentity(ident);
3955 }
3956 }
3957
3958 @Override
3959 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003960 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003961 synchronized (mGlobalLock) {
3962 mSuppressResizeConfigChanges = suppress;
3963 }
3964 }
3965
3966 /**
3967 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3968 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3969 * activity and clearing the task at the same time.
3970 */
3971 @Override
3972 // TODO: API should just be about changing windowing modes...
3973 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003974 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 "moveTasksToFullscreenStack()");
3976 synchronized (mGlobalLock) {
3977 final long origId = Binder.clearCallingIdentity();
3978 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003979 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003980 if (stack != null){
3981 if (!stack.isActivityTypeStandardOrUndefined()) {
3982 throw new IllegalArgumentException(
3983 "You can't move tasks from non-standard stacks.");
3984 }
3985 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3986 }
3987 } finally {
3988 Binder.restoreCallingIdentity(origId);
3989 }
3990 }
3991 }
3992
3993 /**
3994 * Moves the top activity in the input stackId to the pinned stack.
3995 *
3996 * @param stackId Id of stack to move the top activity to pinned stack.
3997 * @param bounds Bounds to use for pinned stack.
3998 *
3999 * @return True if the top activity of the input stack was successfully moved to the pinned
4000 * stack.
4001 */
4002 @Override
4003 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004004 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 "moveTopActivityToPinnedStack()");
4006 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004007 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4009 + "Device doesn't support picture-in-picture mode");
4010 }
4011
4012 long ident = Binder.clearCallingIdentity();
4013 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004014 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004015 } finally {
4016 Binder.restoreCallingIdentity(ident);
4017 }
4018 }
4019 }
4020
4021 @Override
4022 public boolean isInMultiWindowMode(IBinder token) {
4023 final long origId = Binder.clearCallingIdentity();
4024 try {
4025 synchronized (mGlobalLock) {
4026 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4027 if (r == null) {
4028 return false;
4029 }
4030 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4031 return r.inMultiWindowMode();
4032 }
4033 } finally {
4034 Binder.restoreCallingIdentity(origId);
4035 }
4036 }
4037
4038 @Override
4039 public boolean isInPictureInPictureMode(IBinder token) {
4040 final long origId = Binder.clearCallingIdentity();
4041 try {
4042 synchronized (mGlobalLock) {
4043 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4044 }
4045 } finally {
4046 Binder.restoreCallingIdentity(origId);
4047 }
4048 }
4049
4050 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004051 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4052 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004053 return false;
4054 }
4055
4056 // If we are animating to fullscreen then we have already dispatched the PIP mode
4057 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004058 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4059 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 }
4061
4062 @Override
4063 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4064 final long origId = Binder.clearCallingIdentity();
4065 try {
4066 synchronized (mGlobalLock) {
4067 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4068 "enterPictureInPictureMode", token, params);
4069
4070 // If the activity is already in picture in picture mode, then just return early
4071 if (isInPictureInPictureMode(r)) {
4072 return true;
4073 }
4074
4075 // Activity supports picture-in-picture, now check that we can enter PiP at this
4076 // point, if it is
4077 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4078 false /* beforeStopping */)) {
4079 return false;
4080 }
4081
4082 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004083 synchronized (mGlobalLock) {
4084 // Only update the saved args from the args that are set
4085 r.pictureInPictureArgs.copyOnlySet(params);
4086 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4087 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4088 // Adjust the source bounds by the insets for the transition down
4089 final Rect sourceBounds = new Rect(
4090 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004091 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004092 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004093 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004094 stack.setPictureInPictureAspectRatio(aspectRatio);
4095 stack.setPictureInPictureActions(actions);
4096 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4097 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4098 logPictureInPictureArgs(params);
4099 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004100 };
4101
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004102 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103 // If the keyguard is showing or occluded, then try and dismiss it before
4104 // entering picture-in-picture (this will prompt the user to authenticate if the
4105 // device is currently locked).
4106 dismissKeyguard(token, new KeyguardDismissCallback() {
4107 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004108 public void onDismissSucceeded() {
4109 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004110 }
4111 }, null /* message */);
4112 } else {
4113 // Enter picture in picture immediately otherwise
4114 enterPipRunnable.run();
4115 }
4116 return true;
4117 }
4118 } finally {
4119 Binder.restoreCallingIdentity(origId);
4120 }
4121 }
4122
4123 @Override
4124 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4125 final long origId = Binder.clearCallingIdentity();
4126 try {
4127 synchronized (mGlobalLock) {
4128 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4129 "setPictureInPictureParams", token, params);
4130
4131 // Only update the saved args from the args that are set
4132 r.pictureInPictureArgs.copyOnlySet(params);
4133 if (r.inPinnedWindowingMode()) {
4134 // If the activity is already in picture-in-picture, update the pinned stack now
4135 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4136 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004137 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004138 if (!stack.isAnimatingBoundsToFullscreen()) {
4139 stack.setPictureInPictureAspectRatio(
4140 r.pictureInPictureArgs.getAspectRatio());
4141 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4142 }
4143 }
4144 logPictureInPictureArgs(params);
4145 }
4146 } finally {
4147 Binder.restoreCallingIdentity(origId);
4148 }
4149 }
4150
4151 @Override
4152 public int getMaxNumPictureInPictureActions(IBinder token) {
4153 // Currently, this is a static constant, but later, we may change this to be dependent on
4154 // the context of the activity
4155 return 3;
4156 }
4157
4158 private void logPictureInPictureArgs(PictureInPictureParams params) {
4159 if (params.hasSetActions()) {
4160 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4161 params.getActions().size());
4162 }
4163 if (params.hasSetAspectRatio()) {
4164 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4165 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4166 MetricsLogger.action(lm);
4167 }
4168 }
4169
4170 /**
4171 * Checks the state of the system and the activity associated with the given {@param token} to
4172 * verify that picture-in-picture is supported for that activity.
4173 *
4174 * @return the activity record for the given {@param token} if all the checks pass.
4175 */
4176 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4177 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004178 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004179 throw new IllegalStateException(caller
4180 + ": Device doesn't support picture-in-picture mode.");
4181 }
4182
4183 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4184 if (r == null) {
4185 throw new IllegalStateException(caller
4186 + ": Can't find activity for token=" + token);
4187 }
4188
4189 if (!r.supportsPictureInPicture()) {
4190 throw new IllegalStateException(caller
4191 + ": Current activity does not support picture-in-picture.");
4192 }
4193
4194 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004195 && !mWindowManager.isValidPictureInPictureAspectRatio(
4196 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197 final float minAspectRatio = mContext.getResources().getFloat(
4198 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4199 final float maxAspectRatio = mContext.getResources().getFloat(
4200 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4201 throw new IllegalArgumentException(String.format(caller
4202 + ": Aspect ratio is too extreme (must be between %f and %f).",
4203 minAspectRatio, maxAspectRatio));
4204 }
4205
4206 // Truncate the number of actions if necessary
4207 params.truncateActions(getMaxNumPictureInPictureActions(token));
4208
4209 return r;
4210 }
4211
4212 @Override
4213 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004214 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 synchronized (mGlobalLock) {
4216 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4217 if (r == null) {
4218 throw new IllegalArgumentException("Activity does not exist; token="
4219 + activityToken);
4220 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004221 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004222 }
4223 }
4224
4225 @Override
4226 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4227 Rect tempDockedTaskInsetBounds,
4228 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004229 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004230 long ident = Binder.clearCallingIdentity();
4231 try {
4232 synchronized (mGlobalLock) {
4233 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4234 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4235 PRESERVE_WINDOWS);
4236 }
4237 } finally {
4238 Binder.restoreCallingIdentity(ident);
4239 }
4240 }
4241
4242 @Override
4243 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 final long ident = Binder.clearCallingIdentity();
4246 try {
4247 synchronized (mGlobalLock) {
4248 mStackSupervisor.setSplitScreenResizing(resizing);
4249 }
4250 } finally {
4251 Binder.restoreCallingIdentity(ident);
4252 }
4253 }
4254
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004255 /**
4256 * Check that we have the features required for VR-related API calls, and throw an exception if
4257 * not.
4258 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004259 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004260 if (!mContext.getPackageManager().hasSystemFeature(
4261 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4262 throw new UnsupportedOperationException("VR mode not supported on this device!");
4263 }
4264 }
4265
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 @Override
4267 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004268 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269
4270 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4271
4272 ActivityRecord r;
4273 synchronized (mGlobalLock) {
4274 r = ActivityRecord.isInStackLocked(token);
4275 }
4276
4277 if (r == null) {
4278 throw new IllegalArgumentException();
4279 }
4280
4281 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004282 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004283 VrManagerInternal.NO_ERROR) {
4284 return err;
4285 }
4286
4287 // Clear the binder calling uid since this path may call moveToTask().
4288 final long callingId = Binder.clearCallingIdentity();
4289 try {
4290 synchronized (mGlobalLock) {
4291 r.requestedVrComponent = (enabled) ? packageName : null;
4292
4293 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004294 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004295 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 }
4297 return 0;
4298 }
4299 } finally {
4300 Binder.restoreCallingIdentity(callingId);
4301 }
4302 }
4303
4304 @Override
4305 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4306 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4307 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004308 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4310 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4311 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004312 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313 || activity.voiceSession != null) {
4314 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4315 return;
4316 }
4317 if (activity.pendingVoiceInteractionStart) {
4318 Slog.w(TAG, "Pending start of voice interaction already.");
4319 return;
4320 }
4321 activity.pendingVoiceInteractionStart = true;
4322 }
4323 LocalServices.getService(VoiceInteractionManagerInternal.class)
4324 .startLocalVoiceInteraction(callingActivity, options);
4325 }
4326
4327 @Override
4328 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4329 LocalServices.getService(VoiceInteractionManagerInternal.class)
4330 .stopLocalVoiceInteraction(callingActivity);
4331 }
4332
4333 @Override
4334 public boolean supportsLocalVoiceInteraction() {
4335 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4336 .supportsLocalVoiceInteraction();
4337 }
4338
4339 /** Notifies all listeners when the pinned stack animation starts. */
4340 @Override
4341 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004342 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004343 }
4344
4345 /** Notifies all listeners when the pinned stack animation ends. */
4346 @Override
4347 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004348 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 }
4350
4351 @Override
4352 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004353 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004354 final long ident = Binder.clearCallingIdentity();
4355 try {
4356 synchronized (mGlobalLock) {
4357 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4358 }
4359 } finally {
4360 Binder.restoreCallingIdentity(ident);
4361 }
4362 }
4363
4364 @Override
4365 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004367
4368 synchronized (mGlobalLock) {
4369 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004370 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004371 // Call might come when display is not yet added or has already been removed.
4372 if (DEBUG_CONFIGURATION) {
4373 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4374 + displayId);
4375 }
4376 return false;
4377 }
4378
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004379 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004380 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004381 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004382 }
4383
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004384 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004385 final Message msg = PooledLambda.obtainMessage(
4386 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4387 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 }
4389
4390 final long origId = Binder.clearCallingIdentity();
4391 try {
4392 if (values != null) {
4393 Settings.System.clearConfiguration(values);
4394 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004395 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4397 return mTmpUpdateConfigurationResult.changes != 0;
4398 } finally {
4399 Binder.restoreCallingIdentity(origId);
4400 }
4401 }
4402 }
4403
4404 @Override
4405 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004406 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407
4408 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004409 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004410 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 }
4413
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004414 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004415 final Message msg = PooledLambda.obtainMessage(
4416 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4417 DEFAULT_DISPLAY);
4418 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004419 }
4420
4421 final long origId = Binder.clearCallingIdentity();
4422 try {
4423 if (values != null) {
4424 Settings.System.clearConfiguration(values);
4425 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004427 UserHandle.USER_NULL, false /* deferResume */,
4428 mTmpUpdateConfigurationResult);
4429 return mTmpUpdateConfigurationResult.changes != 0;
4430 } finally {
4431 Binder.restoreCallingIdentity(origId);
4432 }
4433 }
4434 }
4435
4436 @Override
4437 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4438 CharSequence message) {
4439 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004440 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004441 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4442 }
4443 final long callingId = Binder.clearCallingIdentity();
4444 try {
4445 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004446 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004447 }
4448 } finally {
4449 Binder.restoreCallingIdentity(callingId);
4450 }
4451 }
4452
4453 @Override
4454 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004456 "cancelTaskWindowTransition()");
4457 final long ident = Binder.clearCallingIdentity();
4458 try {
4459 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004460 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004461 MATCH_TASK_IN_STACKS_ONLY);
4462 if (task == null) {
4463 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4464 return;
4465 }
4466 task.cancelWindowTransition();
4467 }
4468 } finally {
4469 Binder.restoreCallingIdentity(ident);
4470 }
4471 }
4472
4473 @Override
4474 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004475 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004476 final long ident = Binder.clearCallingIdentity();
4477 try {
4478 final TaskRecord task;
4479 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004480 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004481 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4482 if (task == null) {
4483 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4484 return null;
4485 }
4486 }
4487 // Don't call this while holding the lock as this operation might hit the disk.
4488 return task.getSnapshot(reducedResolution);
4489 } finally {
4490 Binder.restoreCallingIdentity(ident);
4491 }
4492 }
4493
4494 @Override
4495 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4496 synchronized (mGlobalLock) {
4497 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4498 if (r == null) {
4499 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4500 + token);
4501 return;
4502 }
4503 final long origId = Binder.clearCallingIdentity();
4504 try {
4505 r.setDisablePreviewScreenshots(disable);
4506 } finally {
4507 Binder.restoreCallingIdentity(origId);
4508 }
4509 }
4510 }
4511
4512 /** Return the user id of the last resumed activity. */
4513 @Override
4514 public @UserIdInt
4515 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004516 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004517 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4518 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004519 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004520 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004521 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004522 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 }
4524 }
4525
4526 @Override
4527 public void updateLockTaskFeatures(int userId, int flags) {
4528 final int callingUid = Binder.getCallingUid();
4529 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004530 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004531 "updateLockTaskFeatures()");
4532 }
4533 synchronized (mGlobalLock) {
4534 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4535 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004536 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004537 }
4538 }
4539
4540 @Override
4541 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4542 synchronized (mGlobalLock) {
4543 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4544 if (r == null) {
4545 return;
4546 }
4547 final long origId = Binder.clearCallingIdentity();
4548 try {
4549 r.setShowWhenLocked(showWhenLocked);
4550 } finally {
4551 Binder.restoreCallingIdentity(origId);
4552 }
4553 }
4554 }
4555
4556 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004557 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4558 synchronized (mGlobalLock) {
4559 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4560 if (r == null) {
4561 return;
4562 }
4563 final long origId = Binder.clearCallingIdentity();
4564 try {
4565 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4566 } finally {
4567 Binder.restoreCallingIdentity(origId);
4568 }
4569 }
4570 }
4571
4572 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004573 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4574 synchronized (mGlobalLock) {
4575 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4576 if (r == null) {
4577 return;
4578 }
4579 final long origId = Binder.clearCallingIdentity();
4580 try {
4581 r.setTurnScreenOn(turnScreenOn);
4582 } finally {
4583 Binder.restoreCallingIdentity(origId);
4584 }
4585 }
4586 }
4587
4588 @Override
4589 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004590 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004591 "registerRemoteAnimations");
4592 definition.setCallingPid(Binder.getCallingPid());
4593 synchronized (mGlobalLock) {
4594 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4595 if (r == null) {
4596 return;
4597 }
4598 final long origId = Binder.clearCallingIdentity();
4599 try {
4600 r.registerRemoteAnimations(definition);
4601 } finally {
4602 Binder.restoreCallingIdentity(origId);
4603 }
4604 }
4605 }
4606
4607 @Override
4608 public void registerRemoteAnimationForNextActivityStart(String packageName,
4609 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004610 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004611 "registerRemoteAnimationForNextActivityStart");
4612 adapter.setCallingPid(Binder.getCallingPid());
4613 synchronized (mGlobalLock) {
4614 final long origId = Binder.clearCallingIdentity();
4615 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004616 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004617 packageName, adapter);
4618 } finally {
4619 Binder.restoreCallingIdentity(origId);
4620 }
4621 }
4622 }
4623
Evan Rosky966759f2019-01-15 10:33:58 -08004624 @Override
4625 public void registerRemoteAnimationsForDisplay(int displayId,
4626 RemoteAnimationDefinition definition) {
4627 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4628 "registerRemoteAnimations");
4629 definition.setCallingPid(Binder.getCallingPid());
4630 synchronized (mGlobalLock) {
4631 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4632 if (display == null) {
4633 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4634 return;
4635 }
4636 final long origId = Binder.clearCallingIdentity();
4637 try {
4638 display.mDisplayContent.registerRemoteAnimations(definition);
4639 } finally {
4640 Binder.restoreCallingIdentity(origId);
4641 }
4642 }
4643 }
4644
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004645 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4646 @Override
4647 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4648 synchronized (mGlobalLock) {
4649 final long origId = Binder.clearCallingIdentity();
4650 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004651 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004652 } finally {
4653 Binder.restoreCallingIdentity(origId);
4654 }
4655 }
4656 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004657
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004658 @Override
4659 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004660 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004661 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004662 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004663 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004664 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004665 }
4666 }
4667
4668 @Override
4669 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004670 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004671 != PERMISSION_GRANTED) {
4672 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4673 + Binder.getCallingPid()
4674 + ", uid=" + Binder.getCallingUid()
4675 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4676 Slog.w(TAG, msg);
4677 throw new SecurityException(msg);
4678 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004679 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004680 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004681 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004682 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004683 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004684 }
4685 }
4686
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004687 @Override
4688 public void stopAppSwitches() {
4689 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4690 synchronized (mGlobalLock) {
4691 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4692 mDidAppSwitch = false;
4693 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4694 }
4695 }
4696
4697 @Override
4698 public void resumeAppSwitches() {
4699 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4700 synchronized (mGlobalLock) {
4701 // Note that we don't execute any pending app switches... we will
4702 // let those wait until either the timeout, or the next start
4703 // activity request.
4704 mAppSwitchesAllowedTime = 0;
4705 }
4706 }
4707
4708 void onStartActivitySetDidAppSwitch() {
4709 if (mDidAppSwitch) {
4710 // This is the second allowed switch since we stopped switches, so now just generally
4711 // allow switches. Use case:
4712 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4713 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4714 // anyone to switch again).
4715 mAppSwitchesAllowedTime = 0;
4716 } else {
4717 mDidAppSwitch = true;
4718 }
4719 }
4720
4721 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004722 boolean shouldDisableNonVrUiLocked() {
4723 return mVrController.shouldDisableNonVrUiLocked();
4724 }
4725
Wale Ogunwale53783742018-09-16 10:21:51 -07004726 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004727 // VR apps are expected to run in a main display. If an app is turning on VR for
4728 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4729 // fullscreen stack before enabling VR Mode.
4730 // TODO: The goal of this code is to keep the VR app on the main display. When the
4731 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4732 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4733 // option would be a better choice here.
4734 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4735 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4736 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004737 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004739 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004740 }
4741 mH.post(() -> {
4742 if (!mVrController.onVrModeChanged(r)) {
4743 return;
4744 }
4745 synchronized (mGlobalLock) {
4746 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4747 mWindowManager.disableNonVrUi(disableNonVrUi);
4748 if (disableNonVrUi) {
4749 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4750 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004751 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004752 }
4753 }
4754 });
4755 }
4756
Wale Ogunwale53783742018-09-16 10:21:51 -07004757 @Override
4758 public int getPackageScreenCompatMode(String packageName) {
4759 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4760 synchronized (mGlobalLock) {
4761 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4762 }
4763 }
4764
4765 @Override
4766 public void setPackageScreenCompatMode(String packageName, int mode) {
4767 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4768 "setPackageScreenCompatMode");
4769 synchronized (mGlobalLock) {
4770 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4771 }
4772 }
4773
4774 @Override
4775 public boolean getPackageAskScreenCompat(String packageName) {
4776 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4777 synchronized (mGlobalLock) {
4778 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4779 }
4780 }
4781
4782 @Override
4783 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4784 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4785 "setPackageAskScreenCompat");
4786 synchronized (mGlobalLock) {
4787 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4788 }
4789 }
4790
Wale Ogunwale64258362018-10-16 15:13:37 -07004791 public static String relaunchReasonToString(int relaunchReason) {
4792 switch (relaunchReason) {
4793 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4794 return "window_resize";
4795 case RELAUNCH_REASON_FREE_RESIZE:
4796 return "free_resize";
4797 default:
4798 return null;
4799 }
4800 }
4801
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004802 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004803 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004804 }
4805
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004806 /** Pokes the task persister. */
4807 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4808 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4809 }
4810
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004811 boolean isKeyguardLocked() {
4812 return mKeyguardController.isKeyguardLocked();
4813 }
4814
Garfield Tan01548632018-11-27 10:15:48 -08004815 /**
4816 * Clears launch params for the given package.
4817 * @param packageNames the names of the packages of which the launch params are to be cleared
4818 */
4819 @Override
4820 public void clearLaunchParamsForPackages(List<String> packageNames) {
4821 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4822 "clearLaunchParamsForPackages");
4823 synchronized (mGlobalLock) {
4824 for (int i = 0; i < packageNames.size(); ++i) {
4825 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4826 }
4827 }
4828 }
4829
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004830 /**
4831 * Makes the display with the given id a single task instance display. I.e the display can only
4832 * contain one task.
4833 */
4834 @Override
4835 public void setDisplayToSingleTaskInstance(int displayId) {
4836 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4837 "setDisplayToSingleTaskInstance");
4838 final long origId = Binder.clearCallingIdentity();
4839 try {
4840 final ActivityDisplay display =
4841 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4842 if (display != null) {
4843 display.setDisplayToSingleTaskInstance();
4844 }
4845 } finally {
4846 Binder.restoreCallingIdentity(origId);
4847 }
4848 }
4849
Wale Ogunwale31913b52018-10-13 08:29:31 -07004850 void dumpLastANRLocked(PrintWriter pw) {
4851 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4852 if (mLastANRState == null) {
4853 pw.println(" <no ANR has occurred since boot>");
4854 } else {
4855 pw.println(mLastANRState);
4856 }
4857 }
4858
4859 void dumpLastANRTracesLocked(PrintWriter pw) {
4860 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4861
4862 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4863 if (ArrayUtils.isEmpty(files)) {
4864 pw.println(" <no ANR has occurred since boot>");
4865 return;
4866 }
4867 // Find the latest file.
4868 File latest = null;
4869 for (File f : files) {
4870 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4871 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004872 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004873 }
4874 pw.print("File: ");
4875 pw.print(latest.getName());
4876 pw.println();
4877 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4878 String line;
4879 while ((line = in.readLine()) != null) {
4880 pw.println(line);
4881 }
4882 } catch (IOException e) {
4883 pw.print("Unable to read: ");
4884 pw.print(e);
4885 pw.println();
4886 }
4887 }
4888
4889 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4890 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4891 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4892 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4893 }
4894
4895 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4896 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4897 pw.println(header);
4898
Wale Ogunwaled32da472018-11-16 07:19:28 -08004899 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004900 dumpPackage);
4901 boolean needSep = printedAnything;
4902
4903 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004904 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004905 " ResumedActivity: ");
4906 if (printed) {
4907 printedAnything = true;
4908 needSep = false;
4909 }
4910
4911 if (dumpPackage == null) {
4912 if (needSep) {
4913 pw.println();
4914 }
4915 printedAnything = true;
4916 mStackSupervisor.dump(pw, " ");
4917 }
4918
4919 if (!printedAnything) {
4920 pw.println(" (nothing)");
4921 }
4922 }
4923
4924 void dumpActivityContainersLocked(PrintWriter pw) {
4925 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004926 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004927 pw.println(" ");
4928 }
4929
4930 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4931 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4932 getActivityStartController().dump(pw, "", dumpPackage);
4933 }
4934
4935 /**
4936 * There are three things that cmd can be:
4937 * - a flattened component name that matches an existing activity
4938 * - the cmd arg isn't the flattened component name of an existing activity:
4939 * dump all activity whose component contains the cmd as a substring
4940 * - A hex number of the ActivityRecord object instance.
4941 *
4942 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4943 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4944 */
4945 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4946 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4947 ArrayList<ActivityRecord> activities;
4948
4949 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004950 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004951 dumpFocusedStackOnly);
4952 }
4953
4954 if (activities.size() <= 0) {
4955 return false;
4956 }
4957
4958 String[] newArgs = new String[args.length - opti];
4959 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4960
4961 TaskRecord lastTask = null;
4962 boolean needSep = false;
4963 for (int i = activities.size() - 1; i >= 0; i--) {
4964 ActivityRecord r = activities.get(i);
4965 if (needSep) {
4966 pw.println();
4967 }
4968 needSep = true;
4969 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004970 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004971 if (lastTask != task) {
4972 lastTask = task;
4973 pw.print("TASK "); pw.print(lastTask.affinity);
4974 pw.print(" id="); pw.print(lastTask.taskId);
4975 pw.print(" userId="); pw.println(lastTask.userId);
4976 if (dumpAll) {
4977 lastTask.dump(pw, " ");
4978 }
4979 }
4980 }
4981 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4982 }
4983 return true;
4984 }
4985
4986 /**
4987 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4988 * there is a thread associated with the activity.
4989 */
4990 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4991 final ActivityRecord r, String[] args, boolean dumpAll) {
4992 String innerPrefix = prefix + " ";
4993 synchronized (mGlobalLock) {
4994 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4995 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4996 pw.print(" pid=");
4997 if (r.hasProcess()) pw.println(r.app.getPid());
4998 else pw.println("(not running)");
4999 if (dumpAll) {
5000 r.dump(pw, innerPrefix);
5001 }
5002 }
5003 if (r.attachedToProcess()) {
5004 // flush anything that is already in the PrintWriter since the thread is going
5005 // to write to the file descriptor directly
5006 pw.flush();
5007 try {
5008 TransferPipe tp = new TransferPipe();
5009 try {
5010 r.app.getThread().dumpActivity(tp.getWriteFd(),
5011 r.appToken, innerPrefix, args);
5012 tp.go(fd);
5013 } finally {
5014 tp.kill();
5015 }
5016 } catch (IOException e) {
5017 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5018 } catch (RemoteException e) {
5019 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5020 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005021 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005022 }
5023
sanryhuang498e77e2018-12-06 14:57:01 +08005024 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5025 boolean testPssMode) {
5026 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5027 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5028 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005029 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005030 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5031 st.toString());
5032 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005033 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5034 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5035 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005036 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5037 testPssMode);
5038 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005039 }
5040
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005041 int getCurrentUserId() {
5042 return mAmInternal.getCurrentUserId();
5043 }
5044
5045 private void enforceNotIsolatedCaller(String caller) {
5046 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5047 throw new SecurityException("Isolated process not allowed to call " + caller);
5048 }
5049 }
5050
Wale Ogunwalef6733932018-06-27 05:14:34 -07005051 public Configuration getConfiguration() {
5052 Configuration ci;
5053 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005054 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005055 ci.userSetLocale = false;
5056 }
5057 return ci;
5058 }
5059
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005060 /**
5061 * Current global configuration information. Contains general settings for the entire system,
5062 * also corresponds to the merged configuration of the default display.
5063 */
5064 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005065 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005066 }
5067
5068 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5069 boolean initLocale) {
5070 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5071 }
5072
5073 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5074 boolean initLocale, boolean deferResume) {
5075 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5076 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5077 UserHandle.USER_NULL, deferResume);
5078 }
5079
Wale Ogunwale59507092018-10-29 09:00:30 -07005080 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005081 final long origId = Binder.clearCallingIdentity();
5082 try {
5083 synchronized (mGlobalLock) {
5084 updateConfigurationLocked(values, null, false, true, userId,
5085 false /* deferResume */);
5086 }
5087 } finally {
5088 Binder.restoreCallingIdentity(origId);
5089 }
5090 }
5091
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005092 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5093 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5094 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5095 deferResume, null /* result */);
5096 }
5097
5098 /**
5099 * Do either or both things: (1) change the current configuration, and (2)
5100 * make sure the given activity is running with the (now) current
5101 * configuration. Returns true if the activity has been left running, or
5102 * false if <var>starting</var> is being destroyed to match the new
5103 * configuration.
5104 *
5105 * @param userId is only used when persistent parameter is set to true to persist configuration
5106 * for that particular user
5107 */
5108 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5109 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5110 ActivityTaskManagerService.UpdateConfigurationResult result) {
5111 int changes = 0;
5112 boolean kept = true;
5113
5114 if (mWindowManager != null) {
5115 mWindowManager.deferSurfaceLayout();
5116 }
5117 try {
5118 if (values != null) {
5119 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5120 deferResume);
5121 }
5122
5123 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5124 } finally {
5125 if (mWindowManager != null) {
5126 mWindowManager.continueSurfaceLayout();
5127 }
5128 }
5129
5130 if (result != null) {
5131 result.changes = changes;
5132 result.activityRelaunched = !kept;
5133 }
5134 return kept;
5135 }
5136
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 /** Update default (global) configuration and notify listeners about changes. */
5138 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5139 boolean persistent, int userId, boolean deferResume) {
5140 mTempConfig.setTo(getGlobalConfiguration());
5141 final int changes = mTempConfig.updateFrom(values);
5142 if (changes == 0) {
5143 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5144 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5145 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5146 // (even if there are no actual changes) to unfreeze the window.
5147 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5148 return 0;
5149 }
5150
5151 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5152 "Updating global configuration to: " + values);
5153
5154 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5155 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5156 values.colorMode,
5157 values.densityDpi,
5158 values.fontScale,
5159 values.hardKeyboardHidden,
5160 values.keyboard,
5161 values.keyboardHidden,
5162 values.mcc,
5163 values.mnc,
5164 values.navigation,
5165 values.navigationHidden,
5166 values.orientation,
5167 values.screenHeightDp,
5168 values.screenLayout,
5169 values.screenWidthDp,
5170 values.smallestScreenWidthDp,
5171 values.touchscreen,
5172 values.uiMode);
5173
5174
5175 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5176 final LocaleList locales = values.getLocales();
5177 int bestLocaleIndex = 0;
5178 if (locales.size() > 1) {
5179 if (mSupportedSystemLocales == null) {
5180 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5181 }
5182 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5183 }
5184 SystemProperties.set("persist.sys.locale",
5185 locales.get(bestLocaleIndex).toLanguageTag());
5186 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005187
5188 final Message m = PooledLambda.obtainMessage(
5189 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5190 locales.get(bestLocaleIndex));
5191 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005192 }
5193
Yunfan Chen75157d72018-07-27 14:47:21 +09005194 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005195
5196 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005197 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005198
5199 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5200 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005201 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005202
5203 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005204 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005205
5206 AttributeCache ac = AttributeCache.instance();
5207 if (ac != null) {
5208 ac.updateConfiguration(mTempConfig);
5209 }
5210
5211 // Make sure all resources in our process are updated right now, so that anyone who is going
5212 // to retrieve resource values after we return will be sure to get the new ones. This is
5213 // especially important during boot, where the first config change needs to guarantee all
5214 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005215 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005216
5217 // We need another copy of global config because we're scheduling some calls instead of
5218 // running them in place. We need to be sure that object we send will be handled unchanged.
5219 final Configuration configCopy = new Configuration(mTempConfig);
5220 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005221 final Message msg = PooledLambda.obtainMessage(
5222 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5223 this, userId, configCopy);
5224 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005225 }
5226
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005227 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5228 for (int i = pidMap.size() - 1; i >= 0; i--) {
5229 final int pid = pidMap.keyAt(i);
5230 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005231 if (DEBUG_CONFIGURATION) {
5232 Slog.v(TAG_CONFIGURATION, "Update process config of "
5233 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005234 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005235 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236 }
5237
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005238 final Message msg = PooledLambda.obtainMessage(
5239 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5240 mAmInternal, changes, initLocale);
5241 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242
5243 // Override configuration of the default display duplicates global config, so we need to
5244 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005245 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005246 DEFAULT_DISPLAY);
5247
5248 return changes;
5249 }
5250
5251 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5252 boolean deferResume, int displayId) {
5253 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5254 displayId, null /* result */);
5255 }
5256
5257 /**
5258 * Updates override configuration specific for the selected display. If no config is provided,
5259 * new one will be computed in WM based on current display info.
5260 */
5261 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5262 ActivityRecord starting, boolean deferResume, int displayId,
5263 ActivityTaskManagerService.UpdateConfigurationResult result) {
5264 int changes = 0;
5265 boolean kept = true;
5266
5267 if (mWindowManager != null) {
5268 mWindowManager.deferSurfaceLayout();
5269 }
5270 try {
5271 if (values != null) {
5272 if (displayId == DEFAULT_DISPLAY) {
5273 // Override configuration of the default display duplicates global config, so
5274 // we're calling global config update instead for default display. It will also
5275 // apply the correct override config.
5276 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5277 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5278 } else {
5279 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5280 }
5281 }
5282
5283 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5284 } finally {
5285 if (mWindowManager != null) {
5286 mWindowManager.continueSurfaceLayout();
5287 }
5288 }
5289
5290 if (result != null) {
5291 result.changes = changes;
5292 result.activityRelaunched = !kept;
5293 }
5294 return kept;
5295 }
5296
5297 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5298 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005299 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005300 final int changes = mTempConfig.updateFrom(values);
5301 if (changes != 0) {
5302 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5303 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005304 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005305
5306 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5307 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005308 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005309
Wale Ogunwale5c918702018-10-18 11:06:33 -07005310 // Post message to start process to avoid possible deadlock of calling into AMS with
5311 // the ATMS lock held.
5312 final Message msg = PooledLambda.obtainMessage(
5313 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005314 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005315 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005316 }
5317 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005318 return changes;
5319 }
5320
Wale Ogunwalef6733932018-06-27 05:14:34 -07005321 private void updateEventDispatchingLocked(boolean booted) {
5322 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5323 }
5324
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005325 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5326 final ContentResolver resolver = mContext.getContentResolver();
5327 Settings.System.putConfigurationForUser(resolver, config, userId);
5328 }
5329
5330 private void sendLocaleToMountDaemonMsg(Locale l) {
5331 try {
5332 IBinder service = ServiceManager.getService("mount");
5333 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5334 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5335 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5336 } catch (RemoteException e) {
5337 Log.e(TAG, "Error storing locale for decryption UI", e);
5338 }
5339 }
5340
Alison Cichowlas3e340502018-08-07 17:15:01 -04005341 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5342 mStartActivitySources.remove(permissionToken);
5343 mExpiredStartAsCallerTokens.add(permissionToken);
5344 }
5345
5346 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5347 mExpiredStartAsCallerTokens.remove(permissionToken);
5348 }
5349
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005350 boolean isActivityStartsLoggingEnabled() {
5351 return mAmInternal.isActivityStartsLoggingEnabled();
5352 }
5353
Michal Karpinski8596ded2018-11-14 14:43:48 +00005354 boolean isBackgroundActivityStartsEnabled() {
5355 return mAmInternal.isBackgroundActivityStartsEnabled();
5356 }
5357
Ricky Waiaca8a772019-04-04 16:01:06 +01005358 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5359 if (packageName == null) {
5360 return false;
5361 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005362 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5363 }
5364
Wale Ogunwalef6733932018-06-27 05:14:34 -07005365 void enableScreenAfterBoot(boolean booted) {
5366 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5367 SystemClock.uptimeMillis());
5368 mWindowManager.enableScreenAfterBoot();
5369
5370 synchronized (mGlobalLock) {
5371 updateEventDispatchingLocked(booted);
5372 }
5373 }
5374
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005375 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5376 if (r == null || !r.hasProcess()) {
5377 return KEY_DISPATCHING_TIMEOUT_MS;
5378 }
5379 return getInputDispatchingTimeoutLocked(r.app);
5380 }
5381
5382 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005383 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005384 }
5385
Wale Ogunwalef6733932018-06-27 05:14:34 -07005386 /**
5387 * Decide based on the configuration whether we should show the ANR,
5388 * crash, etc dialogs. The idea is that if there is no affordance to
5389 * press the on-screen buttons, or the user experience would be more
5390 * greatly impacted than the crash itself, we shouldn't show the dialog.
5391 *
5392 * A thought: SystemUI might also want to get told about this, the Power
5393 * dialog / global actions also might want different behaviors.
5394 */
5395 private void updateShouldShowDialogsLocked(Configuration config) {
5396 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5397 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5398 && config.navigation == Configuration.NAVIGATION_NONAV);
5399 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5400 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5401 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5402 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5403 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5404 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5405 HIDE_ERROR_DIALOGS, 0) != 0;
5406 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5407 }
5408
5409 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5410 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5411 FONT_SCALE, 1.0f, userId);
5412
5413 synchronized (this) {
5414 if (getGlobalConfiguration().fontScale == scaleFactor) {
5415 return;
5416 }
5417
5418 final Configuration configuration
5419 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5420 configuration.fontScale = scaleFactor;
5421 updatePersistentConfiguration(configuration, userId);
5422 }
5423 }
5424
5425 // Actually is sleeping or shutting down or whatever else in the future
5426 // is an inactive state.
5427 boolean isSleepingOrShuttingDownLocked() {
5428 return isSleepingLocked() || mShuttingDown;
5429 }
5430
5431 boolean isSleepingLocked() {
5432 return mSleeping;
5433 }
5434
Riddle Hsu16567132018-08-16 21:37:47 +08005435 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005436 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005437 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005438 if (task.isActivityTypeStandard()) {
5439 if (mCurAppTimeTracker != r.appTimeTracker) {
5440 // We are switching app tracking. Complete the current one.
5441 if (mCurAppTimeTracker != null) {
5442 mCurAppTimeTracker.stop();
5443 mH.obtainMessage(
5444 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005445 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005446 mCurAppTimeTracker = null;
5447 }
5448 if (r.appTimeTracker != null) {
5449 mCurAppTimeTracker = r.appTimeTracker;
5450 startTimeTrackingFocusedActivityLocked();
5451 }
5452 } else {
5453 startTimeTrackingFocusedActivityLocked();
5454 }
5455 } else {
5456 r.appTimeTracker = null;
5457 }
5458 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5459 // TODO: Probably not, because we don't want to resume voice on switching
5460 // back to this activity
5461 if (task.voiceInteractor != null) {
5462 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5463 } else {
5464 finishRunningVoiceLocked();
5465
5466 if (mLastResumedActivity != null) {
5467 final IVoiceInteractionSession session;
5468
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005469 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005470 if (lastResumedActivityTask != null
5471 && lastResumedActivityTask.voiceSession != null) {
5472 session = lastResumedActivityTask.voiceSession;
5473 } else {
5474 session = mLastResumedActivity.voiceSession;
5475 }
5476
5477 if (session != null) {
5478 // We had been in a voice interaction session, but now focused has
5479 // move to something different. Just finish the session, we can't
5480 // return to it and retain the proper state and synchronization with
5481 // the voice interaction service.
5482 finishVoiceTask(session);
5483 }
5484 }
5485 }
5486
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005487 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5488 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 }
5490 updateResumedAppTrace(r);
5491 mLastResumedActivity = r;
5492
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005493 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005494
5495 applyUpdateLockStateLocked(r);
5496 applyUpdateVrModeLocked(r);
5497
5498 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005499 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005500 r == null ? "NULL" : r.shortComponentName,
5501 reason);
5502 }
5503
5504 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5505 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005506 final ActivityTaskManagerInternal.SleepToken token =
5507 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508 updateSleepIfNeededLocked();
5509 return token;
5510 }
5511 }
5512
5513 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005514 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005515 final boolean wasSleeping = mSleeping;
5516 boolean updateOomAdj = false;
5517
5518 if (!shouldSleep) {
5519 // If wasSleeping is true, we need to wake up activity manager state from when
5520 // we started sleeping. In either case, we need to apply the sleep tokens, which
5521 // will wake up stacks or put them to sleep as appropriate.
5522 if (wasSleeping) {
5523 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005524 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5525 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005526 startTimeTrackingFocusedActivityLocked();
5527 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005528 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005529 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5530 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005531 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005532 if (wasSleeping) {
5533 updateOomAdj = true;
5534 }
5535 } else if (!mSleeping && shouldSleep) {
5536 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005537 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5538 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005539 if (mCurAppTimeTracker != null) {
5540 mCurAppTimeTracker.stop();
5541 }
5542 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005543 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005544 mStackSupervisor.goingToSleepLocked();
5545 updateResumedAppTrace(null /* resumed */);
5546 updateOomAdj = true;
5547 }
5548 if (updateOomAdj) {
5549 mH.post(mAmInternal::updateOomAdj);
5550 }
5551 }
5552
5553 void updateOomAdj() {
5554 mH.post(mAmInternal::updateOomAdj);
5555 }
5556
Wale Ogunwale53783742018-09-16 10:21:51 -07005557 void updateCpuStats() {
5558 mH.post(mAmInternal::updateCpuStats);
5559 }
5560
Hui Yu03d12402018-12-06 18:00:37 -08005561 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5562 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005563 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5564 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005565 mH.sendMessage(m);
5566 }
5567
Hui Yu03d12402018-12-06 18:00:37 -08005568 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005569 ComponentName taskRoot = null;
5570 final TaskRecord task = activity.getTaskRecord();
5571 if (task != null) {
5572 final ActivityRecord rootActivity = task.getRootActivity();
5573 if (rootActivity != null) {
5574 taskRoot = rootActivity.mActivityComponent;
5575 }
5576 }
5577
Hui Yu03d12402018-12-06 18:00:37 -08005578 final Message m = PooledLambda.obtainMessage(
5579 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005580 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005581 mH.sendMessage(m);
5582 }
5583
Wale Ogunwale53783742018-09-16 10:21:51 -07005584 void setBooting(boolean booting) {
5585 mAmInternal.setBooting(booting);
5586 }
5587
5588 boolean isBooting() {
5589 return mAmInternal.isBooting();
5590 }
5591
5592 void setBooted(boolean booted) {
5593 mAmInternal.setBooted(booted);
5594 }
5595
5596 boolean isBooted() {
5597 return mAmInternal.isBooted();
5598 }
5599
5600 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5601 mH.post(() -> {
5602 if (finishBooting) {
5603 mAmInternal.finishBooting();
5604 }
5605 if (enableScreen) {
5606 mInternal.enableScreenAfterBoot(isBooted());
5607 }
5608 });
5609 }
5610
5611 void setHeavyWeightProcess(ActivityRecord root) {
5612 mHeavyWeightProcess = root.app;
5613 final Message m = PooledLambda.obtainMessage(
5614 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005615 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005616 mH.sendMessage(m);
5617 }
5618
5619 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5620 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5621 return;
5622 }
5623
5624 mHeavyWeightProcess = null;
5625 final Message m = PooledLambda.obtainMessage(
5626 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5627 proc.mUserId);
5628 mH.sendMessage(m);
5629 }
5630
5631 private void cancelHeavyWeightProcessNotification(int userId) {
5632 final INotificationManager inm = NotificationManager.getService();
5633 if (inm == null) {
5634 return;
5635 }
5636 try {
5637 inm.cancelNotificationWithTag("android", null,
5638 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5639 } catch (RuntimeException e) {
5640 Slog.w(TAG, "Error canceling notification for service", e);
5641 } catch (RemoteException e) {
5642 }
5643
5644 }
5645
5646 private void postHeavyWeightProcessNotification(
5647 WindowProcessController proc, Intent intent, int userId) {
5648 if (proc == null) {
5649 return;
5650 }
5651
5652 final INotificationManager inm = NotificationManager.getService();
5653 if (inm == null) {
5654 return;
5655 }
5656
5657 try {
5658 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5659 String text = mContext.getString(R.string.heavy_weight_notification,
5660 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5661 Notification notification =
5662 new Notification.Builder(context,
5663 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5664 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5665 .setWhen(0)
5666 .setOngoing(true)
5667 .setTicker(text)
5668 .setColor(mContext.getColor(
5669 com.android.internal.R.color.system_notification_accent_color))
5670 .setContentTitle(text)
5671 .setContentText(
5672 mContext.getText(R.string.heavy_weight_notification_detail))
5673 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5674 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5675 new UserHandle(userId)))
5676 .build();
5677 try {
5678 inm.enqueueNotificationWithTag("android", "android", null,
5679 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5680 } catch (RuntimeException e) {
5681 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5682 } catch (RemoteException e) {
5683 }
5684 } catch (PackageManager.NameNotFoundException e) {
5685 Slog.w(TAG, "Unable to create context for heavy notification", e);
5686 }
5687
5688 }
5689
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005690 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5691 IBinder token, String resultWho, int requestCode, Intent[] intents,
5692 String[] resolvedTypes, int flags, Bundle bOptions) {
5693
5694 ActivityRecord activity = null;
5695 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5696 activity = ActivityRecord.isInStackLocked(token);
5697 if (activity == null) {
5698 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5699 return null;
5700 }
5701 if (activity.finishing) {
5702 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5703 return null;
5704 }
5705 }
5706
5707 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5708 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5709 bOptions);
5710 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5711 if (noCreate) {
5712 return rec;
5713 }
5714 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5715 if (activity.pendingResults == null) {
5716 activity.pendingResults = new HashSet<>();
5717 }
5718 activity.pendingResults.add(rec.ref);
5719 }
5720 return rec;
5721 }
5722
Andrii Kulian52d255c2018-07-13 11:32:19 -07005723 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005724 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005725 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005726 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5727 mCurAppTimeTracker.start(resumedActivity.packageName);
5728 }
5729 }
5730
5731 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5732 if (mTracedResumedActivity != null) {
5733 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5734 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5735 }
5736 if (resumed != null) {
5737 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5738 constructResumedTraceName(resumed.packageName), 0);
5739 }
5740 mTracedResumedActivity = resumed;
5741 }
5742
5743 private String constructResumedTraceName(String packageName) {
5744 return "focused app: " + packageName;
5745 }
5746
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005747 /** Applies latest configuration and/or visibility updates if needed. */
5748 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5749 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005750 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005751 // mainStack is null during startup.
5752 if (mainStack != null) {
5753 if (changes != 0 && starting == null) {
5754 // If the configuration changed, and the caller is not already
5755 // in the process of starting an activity, then find the top
5756 // activity to check if its configuration needs to change.
5757 starting = mainStack.topRunningActivityLocked();
5758 }
5759
5760 if (starting != null) {
5761 kept = starting.ensureActivityConfiguration(changes,
5762 false /* preserveWindow */);
5763 // And we need to make sure at this point that all other activities
5764 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005765 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005766 !PRESERVE_WINDOWS);
5767 }
5768 }
5769
5770 return kept;
5771 }
5772
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005773 void scheduleAppGcsLocked() {
5774 mH.post(() -> mAmInternal.scheduleAppGcs());
5775 }
5776
Wale Ogunwale53783742018-09-16 10:21:51 -07005777 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5778 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5779 }
5780
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005781 /**
5782 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5783 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5784 * on demand.
5785 */
5786 IPackageManager getPackageManager() {
5787 return AppGlobals.getPackageManager();
5788 }
5789
5790 PackageManagerInternal getPackageManagerInternalLocked() {
5791 if (mPmInternal == null) {
5792 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5793 }
5794 return mPmInternal;
5795 }
5796
Wale Ogunwale008163e2018-07-23 23:11:08 -07005797 AppWarnings getAppWarningsLocked() {
5798 return mAppWarnings;
5799 }
5800
Wale Ogunwale214f3482018-10-04 11:00:47 -07005801 Intent getHomeIntent() {
5802 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5803 intent.setComponent(mTopComponent);
5804 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5805 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5806 intent.addCategory(Intent.CATEGORY_HOME);
5807 }
5808 return intent;
5809 }
5810
Chilun2ef71f72018-11-16 17:57:15 +08005811 /**
5812 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5813 * activities.
5814 *
5815 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5816 * component defined in config_secondaryHomeComponent.
5817 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5818 */
5819 Intent getSecondaryHomeIntent(String preferredPackage) {
5820 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Wale Ogunwalef8724952019-04-30 21:51:47 +00005821 if (preferredPackage == null) {
5822 // Using the component stored in config if no package name.
Chilun2ef71f72018-11-16 17:57:15 +08005823 final String secondaryHomeComponent = mContext.getResources().getString(
5824 com.android.internal.R.string.config_secondaryHomeComponent);
5825 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5826 } else {
5827 intent.setPackage(preferredPackage);
5828 }
5829 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5830 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5831 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5832 }
5833 return intent;
5834 }
5835
Wale Ogunwale214f3482018-10-04 11:00:47 -07005836 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5837 if (info == null) return null;
5838 ApplicationInfo newInfo = new ApplicationInfo(info);
5839 newInfo.initForUser(userId);
5840 return newInfo;
5841 }
5842
Wale Ogunwale9c103022018-10-18 07:44:54 -07005843 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005844 if (uid == SYSTEM_UID) {
5845 // The system gets to run in any process. If there are multiple processes with the same
5846 // uid, just pick the first (this should never happen).
5847 final SparseArray<WindowProcessController> procs =
5848 mProcessNames.getMap().get(processName);
5849 if (procs == null) return null;
5850 final int procCount = procs.size();
5851 for (int i = 0; i < procCount; i++) {
5852 final int procUid = procs.keyAt(i);
5853 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5854 // Don't use an app process or different user process for system component.
5855 continue;
5856 }
5857 return procs.valueAt(i);
5858 }
5859 }
5860
5861 return mProcessNames.get(processName, uid);
5862 }
5863
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005864 WindowProcessController getProcessController(IApplicationThread thread) {
5865 if (thread == null) {
5866 return null;
5867 }
5868
5869 final IBinder threadBinder = thread.asBinder();
5870 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5871 for (int i = pmap.size()-1; i >= 0; i--) {
5872 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5873 for (int j = procs.size() - 1; j >= 0; j--) {
5874 final WindowProcessController proc = procs.valueAt(j);
5875 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5876 return proc;
5877 }
5878 }
5879 }
5880
5881 return null;
5882 }
5883
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005884 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005885 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005886 if (proc == null) return null;
5887 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5888 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005889 }
5890 return null;
5891 }
5892
Riddle Hsua0536432019-02-16 00:38:59 +08005893 int getUidState(int uid) {
5894 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005895 }
5896
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005897 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005898 // A uid is considered to be foreground if it has a visible non-toast window.
5899 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005900 }
5901
Ricky Wai96f5c352019-04-10 18:40:17 +01005902 boolean isDeviceOwner(int uid) {
5903 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005904 }
5905
Ricky Wai96f5c352019-04-10 18:40:17 +01005906 void setDeviceOwnerUid(int uid) {
5907 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005908 }
5909
Wale Ogunwale9de19442018-10-18 19:05:03 -07005910 /**
5911 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5912 * the whitelist
5913 */
5914 String getPendingTempWhitelistTagForUidLocked(int uid) {
5915 return mPendingTempWhitelist.get(uid);
5916 }
5917
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005918 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5919 if (true || Build.IS_USER) {
5920 return;
5921 }
5922
5923 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5924 StrictMode.allowThreadDiskWrites();
5925 try {
5926 File tracesDir = new File("/data/anr");
5927 File tracesFile = null;
5928 try {
5929 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5930
5931 StringBuilder sb = new StringBuilder();
5932 Time tobj = new Time();
5933 tobj.set(System.currentTimeMillis());
5934 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5935 sb.append(": ");
5936 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5937 sb.append(" since ");
5938 sb.append(msg);
5939 FileOutputStream fos = new FileOutputStream(tracesFile);
5940 fos.write(sb.toString().getBytes());
5941 if (app == null) {
5942 fos.write("\n*** No application process!".getBytes());
5943 }
5944 fos.close();
5945 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5946 } catch (IOException e) {
5947 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5948 return;
5949 }
5950
5951 if (app != null && app.getPid() > 0) {
5952 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5953 firstPids.add(app.getPid());
5954 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5955 }
5956
5957 File lastTracesFile = null;
5958 File curTracesFile = null;
5959 for (int i=9; i>=0; i--) {
5960 String name = String.format(Locale.US, "slow%02d.txt", i);
5961 curTracesFile = new File(tracesDir, name);
5962 if (curTracesFile.exists()) {
5963 if (lastTracesFile != null) {
5964 curTracesFile.renameTo(lastTracesFile);
5965 } else {
5966 curTracesFile.delete();
5967 }
5968 }
5969 lastTracesFile = curTracesFile;
5970 }
5971 tracesFile.renameTo(curTracesFile);
5972 } finally {
5973 StrictMode.setThreadPolicy(oldPolicy);
5974 }
5975 }
5976
Michal Karpinskida34cd42019-04-02 19:46:52 +01005977 boolean isAssociatedCompanionApp(int userId, int uid) {
5978 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
5979 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00005980 return false;
5981 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01005982 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00005983 }
5984
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005985 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005986 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005987
5988
Wale Ogunwale98875612018-10-12 07:53:02 -07005989 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5990 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005991
Riddle Hsud93a6c42018-11-29 21:50:06 +08005992 H(Looper looper) {
5993 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005994 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005995
5996 @Override
5997 public void handleMessage(Message msg) {
5998 switch (msg.what) {
5999 case REPORT_TIME_TRACKER_MSG: {
6000 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6001 tracker.deliverResult(mContext);
6002 } break;
6003 }
6004 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006005 }
6006
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006007 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006008 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006009
6010 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006011 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006012 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006013
6014 @Override
6015 public void handleMessage(Message msg) {
6016 switch (msg.what) {
6017 case DISMISS_DIALOG_UI_MSG: {
6018 final Dialog d = (Dialog) msg.obj;
6019 d.dismiss();
6020 break;
6021 }
6022 }
6023 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006024 }
6025
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006026 final class LocalService extends ActivityTaskManagerInternal {
6027 @Override
6028 public SleepToken acquireSleepToken(String tag, int displayId) {
6029 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006030 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006031 }
6032
6033 @Override
6034 public ComponentName getHomeActivityForUser(int userId) {
6035 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006036 final ActivityRecord homeActivity =
6037 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006038 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006039 }
6040 }
6041
6042 @Override
6043 public void onLocalVoiceInteractionStarted(IBinder activity,
6044 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6045 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006046 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006047 }
6048 }
6049
6050 @Override
6051 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6052 synchronized (mGlobalLock) {
6053 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6054 reasons, timestamp);
6055 }
6056 }
6057
6058 @Override
6059 public void notifyAppTransitionFinished() {
6060 synchronized (mGlobalLock) {
6061 mStackSupervisor.notifyAppTransitionDone();
6062 }
6063 }
6064
6065 @Override
6066 public void notifyAppTransitionCancelled() {
6067 synchronized (mGlobalLock) {
6068 mStackSupervisor.notifyAppTransitionDone();
6069 }
6070 }
6071
6072 @Override
6073 public List<IBinder> getTopVisibleActivities() {
6074 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006075 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006076 }
6077 }
6078
6079 @Override
6080 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6081 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006082 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006083 }
6084 }
6085
6086 @Override
6087 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6088 Bundle bOptions) {
6089 Preconditions.checkNotNull(intents, "intents");
6090 final String[] resolvedTypes = new String[intents.length];
6091
6092 // UID of the package on user userId.
6093 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6094 // packageUid may not be initialized.
6095 int packageUid = 0;
6096 final long ident = Binder.clearCallingIdentity();
6097
6098 try {
6099 for (int i = 0; i < intents.length; i++) {
6100 resolvedTypes[i] =
6101 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6102 }
6103
6104 packageUid = AppGlobals.getPackageManager().getPackageUid(
6105 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6106 } catch (RemoteException e) {
6107 // Shouldn't happen.
6108 } finally {
6109 Binder.restoreCallingIdentity(ident);
6110 }
6111
Riddle Hsu591bf612019-02-14 17:55:31 +08006112 return getActivityStartController().startActivitiesInPackage(
6113 packageUid, packageName,
6114 intents, resolvedTypes, null /* resultTo */,
6115 SafeActivityOptions.fromBundle(bOptions), userId,
6116 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6117 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006118 }
6119
6120 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006121 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6122 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6123 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6124 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006125 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006126 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006127 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6128 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6129 userId, validateIncomingUser, originatingPendingIntent,
6130 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006131 }
6132 }
6133
6134 @Override
6135 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6136 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6137 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6138 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006139 PendingIntentRecord originatingPendingIntent,
6140 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006141 synchronized (mGlobalLock) {
6142 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6143 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6144 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006145 validateIncomingUser, originatingPendingIntent,
6146 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006147 }
6148 }
6149
6150 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006151 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6152 Intent intent, Bundle options, int userId) {
6153 return ActivityTaskManagerService.this.startActivityAsUser(
6154 caller, callerPacakge, intent,
6155 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6156 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6157 false /*validateIncomingUser*/);
6158 }
6159
6160 @Override
lumark588a3e82018-07-20 18:53:54 +08006161 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006162 synchronized (mGlobalLock) {
6163
6164 // We might change the visibilities here, so prepare an empty app transition which
6165 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006166 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006167 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006168 if (activityDisplay == null) {
6169 return;
6170 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006171 final DisplayContent dc = activityDisplay.mDisplayContent;
6172 final boolean wasTransitionSet =
6173 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006174 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006175 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006176 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006177 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006178
6179 // If there was a transition set already we don't want to interfere with it as we
6180 // might be starting it too early.
6181 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006182 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006183 }
6184 }
6185 if (callback != null) {
6186 callback.run();
6187 }
6188 }
6189
6190 @Override
6191 public void notifyKeyguardTrustedChanged() {
6192 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006193 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006194 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006195 }
6196 }
6197 }
6198
6199 /**
6200 * Called after virtual display Id is updated by
6201 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6202 * {@param vrVr2dDisplayId}.
6203 */
6204 @Override
6205 public void setVr2dDisplayId(int vr2dDisplayId) {
6206 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6207 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006208 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006209 }
6210 }
6211
6212 @Override
6213 public void setFocusedActivity(IBinder token) {
6214 synchronized (mGlobalLock) {
6215 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6216 if (r == null) {
6217 throw new IllegalArgumentException(
6218 "setFocusedActivity: No activity record matching token=" + token);
6219 }
Louis Chang19443452018-10-09 12:10:21 +08006220 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006221 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006222 }
6223 }
6224 }
6225
6226 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006227 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006228 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006229 }
6230
6231 @Override
6232 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006233 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006234 }
6235
6236 @Override
6237 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006238 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006239 }
6240
6241 @Override
6242 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6243 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6244 }
6245
6246 @Override
6247 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006248 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006249 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006250
6251 @Override
6252 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6253 synchronized (mGlobalLock) {
6254 mActiveVoiceInteractionServiceComponent = component;
6255 }
6256 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006257
6258 @Override
6259 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6260 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6261 return;
6262 }
6263 synchronized (mGlobalLock) {
6264 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6265 if (types == null) {
6266 if (uid < 0) {
6267 return;
6268 }
6269 types = new ArrayMap<>();
6270 mAllowAppSwitchUids.put(userId, types);
6271 }
6272 if (uid < 0) {
6273 types.remove(type);
6274 } else {
6275 types.put(type, uid);
6276 }
6277 }
6278 }
6279
6280 @Override
6281 public void onUserStopped(int userId) {
6282 synchronized (mGlobalLock) {
6283 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6284 mAllowAppSwitchUids.remove(userId);
6285 }
6286 }
6287
6288 @Override
6289 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6290 synchronized (mGlobalLock) {
6291 return ActivityTaskManagerService.this.isGetTasksAllowed(
6292 caller, callingPid, callingUid);
6293 }
6294 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006295
Riddle Hsua0536432019-02-16 00:38:59 +08006296 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006297 @Override
6298 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006299 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006300 mProcessNames.put(proc.mName, proc.mUid, proc);
6301 }
6302 }
6303
Riddle Hsua0536432019-02-16 00:38:59 +08006304 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006305 @Override
6306 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006307 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006308 mProcessNames.remove(name, uid);
6309 }
6310 }
6311
Riddle Hsua0536432019-02-16 00:38:59 +08006312 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006313 @Override
6314 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006315 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006316 if (proc == mHomeProcess) {
6317 mHomeProcess = null;
6318 }
6319 if (proc == mPreviousProcess) {
6320 mPreviousProcess = null;
6321 }
6322 }
6323 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006324
Riddle Hsua0536432019-02-16 00:38:59 +08006325 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006326 @Override
6327 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006328 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006329 return mTopProcessState;
6330 }
6331 }
6332
Riddle Hsua0536432019-02-16 00:38:59 +08006333 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006334 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006335 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006336 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006337 return proc == mHeavyWeightProcess;
6338 }
6339 }
6340
Riddle Hsua0536432019-02-16 00:38:59 +08006341 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006342 @Override
6343 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006344 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006345 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6346 }
6347 }
6348
6349 @Override
6350 public void finishHeavyWeightApp() {
6351 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006352 if (mHeavyWeightProcess != null) {
6353 mHeavyWeightProcess.finishActivities();
6354 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006355 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6356 mHeavyWeightProcess);
6357 }
6358 }
6359
Riddle Hsua0536432019-02-16 00:38:59 +08006360 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006361 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006362 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006363 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006364 return isSleepingLocked();
6365 }
6366 }
6367
6368 @Override
6369 public boolean isShuttingDown() {
6370 synchronized (mGlobalLock) {
6371 return mShuttingDown;
6372 }
6373 }
6374
6375 @Override
6376 public boolean shuttingDown(boolean booted, int timeout) {
6377 synchronized (mGlobalLock) {
6378 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006379 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006380 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006381 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006382 return mStackSupervisor.shutdownLocked(timeout);
6383 }
6384 }
6385
6386 @Override
6387 public void enableScreenAfterBoot(boolean booted) {
6388 synchronized (mGlobalLock) {
6389 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6390 SystemClock.uptimeMillis());
6391 mWindowManager.enableScreenAfterBoot();
6392 updateEventDispatchingLocked(booted);
6393 }
6394 }
6395
6396 @Override
6397 public boolean showStrictModeViolationDialog() {
6398 synchronized (mGlobalLock) {
6399 return mShowDialogs && !mSleeping && !mShuttingDown;
6400 }
6401 }
6402
6403 @Override
6404 public void showSystemReadyErrorDialogsIfNeeded() {
6405 synchronized (mGlobalLock) {
6406 try {
6407 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6408 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6409 + " data partition or your device will be unstable.");
6410 mUiHandler.post(() -> {
6411 if (mShowDialogs) {
6412 AlertDialog d = new BaseErrorDialog(mUiContext);
6413 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6414 d.setCancelable(false);
6415 d.setTitle(mUiContext.getText(R.string.android_system_label));
6416 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6417 d.setButton(DialogInterface.BUTTON_POSITIVE,
6418 mUiContext.getText(R.string.ok),
6419 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6420 d.show();
6421 }
6422 });
6423 }
6424 } catch (RemoteException e) {
6425 }
6426
6427 if (!Build.isBuildConsistent()) {
6428 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6429 mUiHandler.post(() -> {
6430 if (mShowDialogs) {
6431 AlertDialog d = new BaseErrorDialog(mUiContext);
6432 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6433 d.setCancelable(false);
6434 d.setTitle(mUiContext.getText(R.string.android_system_label));
6435 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6436 d.setButton(DialogInterface.BUTTON_POSITIVE,
6437 mUiContext.getText(R.string.ok),
6438 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6439 d.show();
6440 }
6441 });
6442 }
6443 }
6444 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006445
6446 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006447 public void onProcessMapped(int pid, WindowProcessController proc) {
6448 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006449 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006450 }
6451 }
6452
6453 @Override
6454 public void onProcessUnMapped(int pid) {
6455 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006456 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006457 }
6458 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006459
6460 @Override
6461 public void onPackageDataCleared(String name) {
6462 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006463 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006464 mAppWarnings.onPackageDataCleared(name);
6465 }
6466 }
6467
6468 @Override
6469 public void onPackageUninstalled(String name) {
6470 synchronized (mGlobalLock) {
6471 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006472 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006473 }
6474 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006475
6476 @Override
6477 public void onPackageAdded(String name, boolean replacing) {
6478 synchronized (mGlobalLock) {
6479 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6480 }
6481 }
6482
6483 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006484 public void onPackageReplaced(ApplicationInfo aInfo) {
6485 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006486 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006487 }
6488 }
6489
6490 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006491 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6492 synchronized (mGlobalLock) {
6493 return compatibilityInfoForPackageLocked(ai);
6494 }
6495 }
6496
Yunfan Chen75157d72018-07-27 14:47:21 +09006497 /**
6498 * Set the corresponding display information for the process global configuration. To be
6499 * called when we need to show IME on a different display.
6500 *
6501 * @param pid The process id associated with the IME window.
6502 * @param displayId The ID of the display showing the IME.
6503 */
6504 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006505 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006506 // Don't update process-level configuration for Multi-Client IME process since other
6507 // IMEs on other displays will also receive this configuration change due to IME
6508 // services use the same application config/context.
6509 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006510
Yunfan Chen75157d72018-07-27 14:47:21 +09006511 if (pid == MY_PID || pid < 0) {
6512 if (DEBUG_CONFIGURATION) {
6513 Slog.w(TAG,
6514 "Trying to update display configuration for system/invalid process.");
6515 }
6516 return;
6517 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006518 synchronized (mGlobalLock) {
6519 final ActivityDisplay activityDisplay =
6520 mRootActivityContainer.getActivityDisplay(displayId);
6521 if (activityDisplay == null) {
6522 // Call might come when display is not yet added or has been removed.
6523 if (DEBUG_CONFIGURATION) {
6524 Slog.w(TAG, "Trying to update display configuration for non-existing "
6525 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006526 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006527 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006528 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006529 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006530 if (process == null) {
6531 if (DEBUG_CONFIGURATION) {
6532 Slog.w(TAG, "Trying to update display configuration for invalid "
6533 + "process, pid=" + pid);
6534 }
6535 return;
6536 }
6537 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6538 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006539 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006540
6541 @Override
6542 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6543 int requestCode, int resultCode, Intent data) {
6544 synchronized (mGlobalLock) {
6545 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006546 if (r != null && r.getActivityStack() != null) {
6547 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6548 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006549 }
6550 }
6551 }
6552
6553 @Override
6554 public void clearPendingResultForActivity(IBinder activityToken,
6555 WeakReference<PendingIntentRecord> pir) {
6556 synchronized (mGlobalLock) {
6557 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6558 if (r != null && r.pendingResults != null) {
6559 r.pendingResults.remove(pir);
6560 }
6561 }
6562 }
6563
6564 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006565 public ActivityTokens getTopActivityForTask(int taskId) {
6566 synchronized (mGlobalLock) {
6567 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6568 if (taskRecord == null) {
6569 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6570 + " Requested task not found");
6571 return null;
6572 }
6573 final ActivityRecord activity = taskRecord.getTopActivity();
6574 if (activity == null) {
6575 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6576 + " Requested activity not found");
6577 return null;
6578 }
6579 if (!activity.attachedToProcess()) {
6580 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6581 + activity);
6582 return null;
6583 }
6584 return new ActivityTokens(activity.appToken, activity.assistToken,
6585 activity.app.getThread());
6586 }
6587 }
6588
6589 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006590 public IIntentSender getIntentSender(int type, String packageName,
6591 int callingUid, int userId, IBinder token, String resultWho,
6592 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6593 Bundle bOptions) {
6594 synchronized (mGlobalLock) {
6595 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6596 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6597 }
6598 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006599
6600 @Override
6601 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6602 synchronized (mGlobalLock) {
6603 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6604 if (r == null) {
6605 return null;
6606 }
6607 if (r.mServiceConnectionsHolder == null) {
6608 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6609 ActivityTaskManagerService.this, r);
6610 }
6611
6612 return r.mServiceConnectionsHolder;
6613 }
6614 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006615
6616 @Override
6617 public Intent getHomeIntent() {
6618 synchronized (mGlobalLock) {
6619 return ActivityTaskManagerService.this.getHomeIntent();
6620 }
6621 }
6622
6623 @Override
6624 public boolean startHomeActivity(int userId, String reason) {
6625 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006626 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006627 }
6628 }
6629
6630 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006631 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006632 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006633 synchronized (mGlobalLock) {
6634 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006635 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006636 }
Chilun8b1f1be2019-03-13 17:14:36 +08006637 }
6638
6639 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006640 public boolean startHomeOnAllDisplays(int userId, String reason) {
6641 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006642 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006643 }
6644 }
6645
Riddle Hsua0536432019-02-16 00:38:59 +08006646 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006647 @Override
6648 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006649 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006650 if (mFactoryTest == FACTORY_TEST_OFF) {
6651 return false;
6652 }
6653 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6654 && wpc.mName.equals(mTopComponent.getPackageName())) {
6655 return true;
6656 }
6657 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6658 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6659 }
6660 }
6661
6662 @Override
6663 public void updateTopComponentForFactoryTest() {
6664 synchronized (mGlobalLock) {
6665 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6666 return;
6667 }
6668 final ResolveInfo ri = mContext.getPackageManager()
6669 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6670 final CharSequence errorMsg;
6671 if (ri != null) {
6672 final ActivityInfo ai = ri.activityInfo;
6673 final ApplicationInfo app = ai.applicationInfo;
6674 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6675 mTopAction = Intent.ACTION_FACTORY_TEST;
6676 mTopData = null;
6677 mTopComponent = new ComponentName(app.packageName, ai.name);
6678 errorMsg = null;
6679 } else {
6680 errorMsg = mContext.getResources().getText(
6681 com.android.internal.R.string.factorytest_not_system);
6682 }
6683 } else {
6684 errorMsg = mContext.getResources().getText(
6685 com.android.internal.R.string.factorytest_no_action);
6686 }
6687 if (errorMsg == null) {
6688 return;
6689 }
6690
6691 mTopAction = null;
6692 mTopData = null;
6693 mTopComponent = null;
6694 mUiHandler.post(() -> {
6695 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6696 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006697 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006698 });
6699 }
6700 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701
Riddle Hsua0536432019-02-16 00:38:59 +08006702 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006703 @Override
6704 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6705 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006706 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006707 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006708 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006709
6710 wpc.clearRecentTasks();
6711 wpc.clearActivities();
6712
6713 if (wpc.isInstrumenting()) {
6714 finishInstrumentationCallback.run();
6715 }
6716
Jorim Jaggid0752812018-10-16 16:07:20 +02006717 if (!restarting && hasVisibleActivities) {
6718 mWindowManager.deferSurfaceLayout();
6719 try {
6720 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6721 // If there was nothing to resume, and we are not already restarting
6722 // this process, but there is a visible activity that is hosted by the
6723 // process...then make sure all visible activities are running, taking
6724 // care of restarting this process.
6725 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6726 !PRESERVE_WINDOWS);
6727 }
6728 } finally {
6729 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006731 }
6732 }
6733 }
6734
6735 @Override
6736 public void closeSystemDialogs(String reason) {
6737 enforceNotIsolatedCaller("closeSystemDialogs");
6738
6739 final int pid = Binder.getCallingPid();
6740 final int uid = Binder.getCallingUid();
6741 final long origId = Binder.clearCallingIdentity();
6742 try {
6743 synchronized (mGlobalLock) {
6744 // Only allow this from foreground processes, so that background
6745 // applications can't abuse it to prevent system UI from being shown.
6746 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006747 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006748 if (!proc.isPerceptible()) {
6749 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6750 + " from background process " + proc);
6751 return;
6752 }
6753 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006754 mWindowManager.closeSystemDialogs(reason);
6755
Wale Ogunwaled32da472018-11-16 07:19:28 -08006756 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006757 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006758 // Call into AM outside the synchronized block.
6759 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006760 } finally {
6761 Binder.restoreCallingIdentity(origId);
6762 }
6763 }
6764
6765 @Override
6766 public void cleanupDisabledPackageComponents(
6767 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6768 synchronized (mGlobalLock) {
6769 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006770 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006771 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006772 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773 mStackSupervisor.scheduleIdleLocked();
6774 }
6775
6776 // Clean-up disabled tasks
6777 getRecentTasks().cleanupDisabledPackageTasksLocked(
6778 packageName, disabledClasses, userId);
6779 }
6780 }
6781
6782 @Override
6783 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6784 int userId) {
6785 synchronized (mGlobalLock) {
6786
6787 boolean didSomething =
6788 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006789 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790 null, doit, evenPersistent, userId);
6791 return didSomething;
6792 }
6793 }
6794
6795 @Override
6796 public void resumeTopActivities(boolean scheduleIdle) {
6797 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006798 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006799 if (scheduleIdle) {
6800 mStackSupervisor.scheduleIdleLocked();
6801 }
6802 }
6803 }
6804
Riddle Hsua0536432019-02-16 00:38:59 +08006805 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 @Override
6807 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006808 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6810 }
6811 }
6812
Riddle Hsua0536432019-02-16 00:38:59 +08006813 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006814 @Override
6815 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006816 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006817 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006818 }
6819 }
6820
6821 @Override
6822 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6823 try {
6824 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6825 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6826 }
6827 } catch (RemoteException ex) {
6828 throw new SecurityException("Fail to check is caller a privileged app", ex);
6829 }
6830
6831 synchronized (mGlobalLock) {
6832 final long ident = Binder.clearCallingIdentity();
6833 try {
6834 if (mAmInternal.shouldConfirmCredentials(userId)) {
6835 if (mKeyguardController.isKeyguardLocked()) {
6836 // Showing launcher to avoid user entering credential twice.
6837 startHomeActivity(currentUserId, "notifyLockedProfile");
6838 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006839 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006840 }
6841 } finally {
6842 Binder.restoreCallingIdentity(ident);
6843 }
6844 }
6845 }
6846
6847 @Override
6848 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6849 mAmInternal.enforceCallingPermission(
6850 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6851
6852 synchronized (mGlobalLock) {
6853 final long ident = Binder.clearCallingIdentity();
6854 try {
6855 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6856 FLAG_ACTIVITY_TASK_ON_HOME);
6857 ActivityOptions activityOptions = options != null
6858 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006859 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006860 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006861 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006862 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006863 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6865 UserHandle.CURRENT);
6866 } finally {
6867 Binder.restoreCallingIdentity(ident);
6868 }
6869 }
6870 }
6871
6872 @Override
6873 public void writeActivitiesToProto(ProtoOutputStream proto) {
6874 synchronized (mGlobalLock) {
6875 // The output proto of "activity --proto activities"
6876 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006877 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006878 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6879 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 }
6881 }
6882
6883 @Override
6884 public void saveANRState(String reason) {
6885 synchronized (mGlobalLock) {
6886 final StringWriter sw = new StringWriter();
6887 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6888 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6889 if (reason != null) {
6890 pw.println(" Reason: " + reason);
6891 }
6892 pw.println();
6893 getActivityStartController().dump(pw, " ", null);
6894 pw.println();
6895 pw.println("-------------------------------------------------------------------------------");
6896 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6897 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6898 "" /* header */);
6899 pw.println();
6900 pw.close();
6901
6902 mLastANRState = sw.toString();
6903 }
6904 }
6905
6906 @Override
6907 public void clearSavedANRState() {
6908 synchronized (mGlobalLock) {
6909 mLastANRState = null;
6910 }
6911 }
6912
6913 @Override
6914 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6915 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6916 synchronized (mGlobalLock) {
6917 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6918 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6919 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6920 dumpLastANRLocked(pw);
6921 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6922 dumpLastANRTracesLocked(pw);
6923 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6924 dumpActivityStarterLocked(pw, dumpPackage);
6925 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6926 dumpActivityContainersLocked(pw);
6927 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6928 if (getRecentTasks() != null) {
6929 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6930 }
6931 }
6932 }
6933 }
6934
6935 @Override
6936 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6937 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6938 int wakefulness) {
6939 synchronized (mGlobalLock) {
6940 if (mHomeProcess != null && (dumpPackage == null
6941 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6942 if (needSep) {
6943 pw.println();
6944 needSep = false;
6945 }
6946 pw.println(" mHomeProcess: " + mHomeProcess);
6947 }
6948 if (mPreviousProcess != null && (dumpPackage == null
6949 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6950 if (needSep) {
6951 pw.println();
6952 needSep = false;
6953 }
6954 pw.println(" mPreviousProcess: " + mPreviousProcess);
6955 }
6956 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6957 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6958 StringBuilder sb = new StringBuilder(128);
6959 sb.append(" mPreviousProcessVisibleTime: ");
6960 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6961 pw.println(sb);
6962 }
6963 if (mHeavyWeightProcess != null && (dumpPackage == null
6964 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6965 if (needSep) {
6966 pw.println();
6967 needSep = false;
6968 }
6969 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6970 }
6971 if (dumpPackage == null) {
6972 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006973 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006974 }
6975 if (dumpAll) {
6976 if (dumpPackage == null) {
6977 pw.println(" mConfigWillChange: "
6978 + getTopDisplayFocusedStack().mConfigWillChange);
6979 }
6980 if (mCompatModePackages.getPackages().size() > 0) {
6981 boolean printed = false;
6982 for (Map.Entry<String, Integer> entry
6983 : mCompatModePackages.getPackages().entrySet()) {
6984 String pkg = entry.getKey();
6985 int mode = entry.getValue();
6986 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6987 continue;
6988 }
6989 if (!printed) {
6990 pw.println(" mScreenCompatPackages:");
6991 printed = true;
6992 }
6993 pw.println(" " + pkg + ": " + mode);
6994 }
6995 }
6996 }
6997
6998 if (dumpPackage == null) {
6999 pw.println(" mWakefulness="
7000 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007001 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007002 if (mRunningVoice != null) {
7003 pw.println(" mRunningVoice=" + mRunningVoice);
7004 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7005 }
7006 pw.println(" mSleeping=" + mSleeping);
7007 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7008 pw.println(" mVrController=" + mVrController);
7009 }
7010 if (mCurAppTimeTracker != null) {
7011 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7012 }
7013 if (mAllowAppSwitchUids.size() > 0) {
7014 boolean printed = false;
7015 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7016 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7017 for (int j = 0; j < types.size(); j++) {
7018 if (dumpPackage == null ||
7019 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7020 if (needSep) {
7021 pw.println();
7022 needSep = false;
7023 }
7024 if (!printed) {
7025 pw.println(" mAllowAppSwitchUids:");
7026 printed = true;
7027 }
7028 pw.print(" User ");
7029 pw.print(mAllowAppSwitchUids.keyAt(i));
7030 pw.print(": Type ");
7031 pw.print(types.keyAt(j));
7032 pw.print(" = ");
7033 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7034 pw.println();
7035 }
7036 }
7037 }
7038 }
7039 if (dumpPackage == null) {
7040 if (mController != null) {
7041 pw.println(" mController=" + mController
7042 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7043 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007044 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7045 pw.println(" mLaunchingActivityWakeLock="
7046 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007047 }
7048
7049 return needSep;
7050 }
7051 }
7052
7053 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007054 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7055 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007056 synchronized (mGlobalLock) {
7057 if (dumpPackage == null) {
7058 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7059 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007060 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7061 if (mRunningVoice != null) {
7062 final long vrToken = proto.start(
7063 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7064 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7065 mRunningVoice.toString());
7066 mVoiceWakeLock.writeToProto(
7067 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7068 proto.end(vrToken);
7069 }
7070 mVrController.writeToProto(proto,
7071 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007072 if (mController != null) {
7073 final long token = proto.start(CONTROLLER);
7074 proto.write(CONTROLLER, mController.toString());
7075 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7076 proto.end(token);
7077 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007078 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7079 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7080 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007081 }
7082
7083 if (mHomeProcess != null && (dumpPackage == null
7084 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007085 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007086 }
7087
7088 if (mPreviousProcess != null && (dumpPackage == null
7089 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007090 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007091 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7092 }
7093
7094 if (mHeavyWeightProcess != null && (dumpPackage == null
7095 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007096 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007097 }
7098
7099 for (Map.Entry<String, Integer> entry
7100 : mCompatModePackages.getPackages().entrySet()) {
7101 String pkg = entry.getKey();
7102 int mode = entry.getValue();
7103 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7104 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7105 proto.write(PACKAGE, pkg);
7106 proto.write(MODE, mode);
7107 proto.end(compatToken);
7108 }
7109 }
7110
7111 if (mCurAppTimeTracker != null) {
7112 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7113 }
7114
7115 }
7116 }
7117
7118 @Override
7119 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7120 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7121 boolean dumpFocusedStackOnly) {
7122 synchronized (mGlobalLock) {
7123 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7124 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7125 }
7126 }
7127
7128 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007129 public void dumpForOom(PrintWriter pw) {
7130 synchronized (mGlobalLock) {
7131 pw.println(" mHomeProcess: " + mHomeProcess);
7132 pw.println(" mPreviousProcess: " + mPreviousProcess);
7133 if (mHeavyWeightProcess != null) {
7134 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7135 }
7136 }
7137 }
7138
7139 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007140 public boolean canGcNow() {
7141 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007142 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007143 }
7144 }
7145
Riddle Hsua0536432019-02-16 00:38:59 +08007146 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007147 @Override
7148 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007149 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007150 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007151 return top != null ? top.app : null;
7152 }
7153 }
7154
Riddle Hsua0536432019-02-16 00:38:59 +08007155 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007156 @Override
7157 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007158 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007159 if (mRootActivityContainer != null) {
7160 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007161 }
7162 }
7163 }
7164
7165 @Override
7166 public void scheduleDestroyAllActivities(String reason) {
7167 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007168 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007169 }
7170 }
7171
7172 @Override
7173 public void removeUser(int userId) {
7174 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007175 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007176 }
7177 }
7178
7179 @Override
7180 public boolean switchUser(int userId, UserState userState) {
7181 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007182 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007183 }
7184 }
7185
7186 @Override
7187 public void onHandleAppCrash(WindowProcessController wpc) {
7188 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007189 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007190 }
7191 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007192
7193 @Override
7194 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7195 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007196 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007197 }
7198 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007199
Riddle Hsua0536432019-02-16 00:38:59 +08007200 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007201 @Override
7202 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007203 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007204 }
7205
Riddle Hsua0536432019-02-16 00:38:59 +08007206 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007207 @Override
7208 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007209 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007210 }
7211
Riddle Hsua0536432019-02-16 00:38:59 +08007212 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007213 @Override
7214 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007215 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007216 }
7217
Riddle Hsua0536432019-02-16 00:38:59 +08007218 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007219 @Override
7220 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007221 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007222 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007223
7224 @Override
7225 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007226 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007227 mPendingTempWhitelist.put(uid, tag);
7228 }
7229 }
7230
7231 @Override
7232 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007233 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007234 mPendingTempWhitelist.remove(uid);
7235 }
7236 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007237
7238 @Override
7239 public boolean handleAppCrashInActivityController(String processName, int pid,
7240 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7241 Runnable killCrashingAppCallback) {
7242 synchronized (mGlobalLock) {
7243 if (mController == null) {
7244 return false;
7245 }
7246
7247 try {
7248 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7249 stackTrace)) {
7250 killCrashingAppCallback.run();
7251 return true;
7252 }
7253 } catch (RemoteException e) {
7254 mController = null;
7255 Watchdog.getInstance().setActivityController(null);
7256 }
7257 return false;
7258 }
7259 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007260
7261 @Override
7262 public void removeRecentTasksByPackageName(String packageName, int userId) {
7263 synchronized (mGlobalLock) {
7264 mRecentTasks.removeTasksByPackageName(packageName, userId);
7265 }
7266 }
7267
7268 @Override
7269 public void cleanupRecentTasksForUser(int userId) {
7270 synchronized (mGlobalLock) {
7271 mRecentTasks.cleanupLocked(userId);
7272 }
7273 }
7274
7275 @Override
7276 public void loadRecentTasksForUser(int userId) {
7277 synchronized (mGlobalLock) {
7278 mRecentTasks.loadUserRecentsLocked(userId);
7279 }
7280 }
7281
7282 @Override
7283 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7284 synchronized (mGlobalLock) {
7285 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7286 }
7287 }
7288
7289 @Override
7290 public void flushRecentTasks() {
7291 mRecentTasks.flush();
7292 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007293
7294 @Override
7295 public WindowProcessController getHomeProcess() {
7296 synchronized (mGlobalLock) {
7297 return mHomeProcess;
7298 }
7299 }
7300
7301 @Override
7302 public WindowProcessController getPreviousProcess() {
7303 synchronized (mGlobalLock) {
7304 return mPreviousProcess;
7305 }
7306 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007307
7308 @Override
7309 public void clearLockedTasks(String reason) {
7310 synchronized (mGlobalLock) {
7311 getLockTaskController().clearLockedTasks(reason);
7312 }
7313 }
7314
7315 @Override
7316 public void updateUserConfiguration() {
7317 synchronized (mGlobalLock) {
7318 final Configuration configuration = new Configuration(getGlobalConfiguration());
7319 final int currentUserId = mAmInternal.getCurrentUserId();
7320 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7321 configuration, currentUserId, Settings.System.canWrite(mContext));
7322 updateConfigurationLocked(configuration, null /* starting */,
7323 false /* initLocale */, false /* persistent */, currentUserId,
7324 false /* deferResume */);
7325 }
7326 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007327
7328 @Override
7329 public boolean canShowErrorDialogs() {
7330 synchronized (mGlobalLock) {
7331 return mShowDialogs && !mSleeping && !mShuttingDown
7332 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7333 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7334 mAmInternal.getCurrentUserId())
7335 && !(UserManager.isDeviceInDemoMode(mContext)
7336 && mAmInternal.getCurrentUser().isDemo());
7337 }
7338 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007339
7340 @Override
7341 public void setProfileApp(String profileApp) {
7342 synchronized (mGlobalLock) {
7343 mProfileApp = profileApp;
7344 }
7345 }
7346
7347 @Override
7348 public void setProfileProc(WindowProcessController wpc) {
7349 synchronized (mGlobalLock) {
7350 mProfileProc = wpc;
7351 }
7352 }
7353
7354 @Override
7355 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7356 synchronized (mGlobalLock) {
7357 mProfilerInfo = profilerInfo;
7358 }
7359 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007360
7361 @Override
7362 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7363 synchronized (mGlobalLock) {
7364 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7365 }
7366 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007367
7368 @Override
7369 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7370 synchronized (mGlobalLock) {
7371 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7372 }
7373 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007374
7375 @Override
7376 public boolean isUidForeground(int uid) {
7377 synchronized (mGlobalLock) {
7378 return ActivityTaskManagerService.this.isUidForeground(uid);
7379 }
7380 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007381
7382 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007383 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007384 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007385 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007386 }
7387 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007388
7389 @Override
7390 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007391 // Translate package names into UIDs
7392 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007393 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007394 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7395 if (uid >= 0) {
7396 result.add(uid);
7397 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007398 }
7399 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007400 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007401 }
7402 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007403 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007404}