blob: 78637566fffeef8a654e1421aecd38edbf6e4082 [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 Ogunwale214f3482018-10-04 11:00:47 -070042import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070043import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070044import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
45import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070046import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070047import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070048import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
50import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070051import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
52import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070054import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070055import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070056import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070057import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
58import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070060import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
61import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070062import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040063import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.view.Display.DEFAULT_DISPLAY;
65import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070066import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070067import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070068
Yunfan Chen79b96062018-10-17 12:45:23 -070069import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
70import static com.android.server.am.ActivityManagerService.MY_PID;
71import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
72import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070073import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
74import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080083import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070087import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
88import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
90import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
91import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
92import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700110import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800114import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
115import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700116import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
117import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800118import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800120import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
121import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
122import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700125import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.annotation.Nullable;
127import android.annotation.UserIdInt;
128import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700129import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.app.ActivityOptions;
132import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700133import android.app.ActivityThread;
134import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700135import android.app.AppGlobals;
Michal Karpinski15486842019-04-25 17:33:42 +0100136import android.app.AppOpsManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Mark Renouf446251d2019-04-26 10:22:41 -0400143import android.app.IRequestFinishCallback;
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;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800267import com.android.server.policy.PermissionPolicyInternal;
Jeff Sharkey344ce7c2019-05-29 14:52:59 -0600268import com.android.server.uri.NeededUriGrants;
Evan Rosky4505b352018-09-06 11:20:40 -0700269import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700273import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700277import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700278import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700279import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800280import java.lang.annotation.ElementType;
281import java.lang.annotation.Retention;
282import java.lang.annotation.RetentionPolicy;
283import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700284import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700287import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700288import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400289import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700290import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700292import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700293import java.util.Map;
294import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295
296/**
297 * System service for managing activities and their containers (task, stacks, displays,... ).
298 *
299 * {@hide}
300 */
301public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700302 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700304 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
305 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
306 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
307 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
308 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700309 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700310
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700313 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700314 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100315 // How long we permit background activity starts after an activity in the process
316 // started or finished.
317 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700318
Wale Ogunwale98875612018-10-12 07:53:02 -0700319 /** Used to indicate that an app transition should be animated. */
320 static final boolean ANIMATE = true;
321
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700322 /** Hardware-reported OpenGLES version. */
323 final int GL_ES_VERSION;
324
Wale Ogunwale31913b52018-10-13 08:29:31 -0700325 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
326 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
327 public static final String DUMP_LASTANR_CMD = "lastanr" ;
328 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
329 public static final String DUMP_STARTER_CMD = "starter" ;
330 public static final String DUMP_CONTAINERS_CMD = "containers" ;
331 public static final String DUMP_RECENTS_CMD = "recents" ;
332 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
333
Wale Ogunwale64258362018-10-16 15:13:37 -0700334 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
335 public static final int RELAUNCH_REASON_NONE = 0;
336 /** This activity is being relaunched due to windowing mode change. */
337 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
338 /** This activity is being relaunched due to a free-resize operation. */
339 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
340
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700341 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700342
Wale Ogunwalef6733932018-06-27 05:14:34 -0700343 /**
344 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
345 * change at runtime. Use mContext for non-UI purposes.
346 */
347 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700349 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700350 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700351 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700352 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700353 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800354 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800355 @VisibleForTesting
356 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700357 PowerManagerInternal mPowerManagerInternal;
358 private UsageStatsManagerInternal mUsageStatsInternal;
359
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700360 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700361 IntentFirewall mIntentFirewall;
362
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700363 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800364 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800365 /**
366 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
367 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
368 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
369 *
370 * @see WindowManagerThreadPriorityBooster
371 */
372 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700373 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800374 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700375 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700376 private UserManagerService mUserManager;
377 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700378 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800379 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700380 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700381 /** All processes currently running that might have a window organized by name. */
382 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100383 /** All processes we currently have running mapped by pid and uid */
384 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700385 /** This is the process holding what we currently consider to be the "home" activity. */
386 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700387 /** The currently running heavy-weight process, if any. */
388 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700389 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700390 /**
391 * This is the process holding the activity the user last visited that is in a different process
392 * from the one they are currently in.
393 */
394 WindowProcessController mPreviousProcess;
395 /** The time at which the previous process was last visible. */
396 long mPreviousProcessVisibleTime;
397
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700398 /** List of intents that were used to start the most recent tasks. */
399 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700400 /** State of external calls telling us if the device is awake or asleep. */
401 private boolean mKeyguardShown = false;
402
403 // Wrapper around VoiceInteractionServiceManager
404 private AssistUtils mAssistUtils;
405
406 // VoiceInteraction session ID that changes for each new request except when
407 // being called for multi-window assist in a single session.
408 private int mViSessionId = 1000;
409
410 // How long to wait in getAssistContextExtras for the activity and foreground services
411 // to respond with the result.
412 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
413
414 // How long top wait when going through the modern assist (which doesn't need to block
415 // on getting this result before starting to launch its UI).
416 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
417
418 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
419 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
420
Alison Cichowlas3e340502018-08-07 17:15:01 -0400421 // Permission tokens are used to temporarily granted a trusted app the ability to call
422 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
423 // showing any appropriate error messages to the user.
424 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
425 10 * MINUTE_IN_MILLIS;
426
427 // How long before the service actually expires a token. This is slightly longer than
428 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
429 // expiration exception.
430 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
431 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
432
433 // How long the service will remember expired tokens, for the purpose of providing error
434 // messaging when a client uses an expired token.
435 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
436 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
437
Marvin Ramin830d4e32019-03-12 13:16:58 +0100438 // How long to whitelist the Services for when requested.
439 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
440
Alison Cichowlas3e340502018-08-07 17:15:01 -0400441 // Activity tokens of system activities that are delegating their call to
442 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
443 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
444
445 // Permission tokens that have expired, but we remember for error reporting.
446 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
447
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700448 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
449
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700450 // Keeps track of the active voice interaction service component, notified from
451 // VoiceInteractionManagerService
452 ComponentName mActiveVoiceInteractionServiceComponent;
453
Michal Karpinskida34cd42019-04-02 19:46:52 +0100454 // A map userId and all its companion app uids
455 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000456
Wale Ogunwalee2172292018-10-25 10:11:10 -0700457 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700458 KeyguardController mKeyguardController;
459 private final ClientLifecycleManager mLifecycleManager;
460 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700461 /** The controller for all operations related to locktask. */
462 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700463 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700464
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700465 boolean mSuppressResizeConfigChanges;
466
467 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
468 new UpdateConfigurationResult();
469
470 static final class UpdateConfigurationResult {
471 // Configuration changes that were updated.
472 int changes;
473 // If the activity was relaunched to match the new configuration.
474 boolean activityRelaunched;
475
476 void reset() {
477 changes = 0;
478 activityRelaunched = false;
479 }
480 }
481
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700482 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700483 private int mConfigurationSeq;
484 // To cache the list of supported system locales
485 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700486
487 /**
488 * Temp object used when global and/or display override configuration is updated. It is also
489 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
490 * anyone...
491 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 private Configuration mTempConfig = new Configuration();
493
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 /** Temporary to avoid allocations. */
495 final StringBuilder mStringBuilder = new StringBuilder(256);
496
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497 // Amount of time after a call to stopAppSwitches() during which we will
498 // prevent further untrusted switches from happening.
499 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
500
501 /**
502 * The time at which we will allow normal application switches again,
503 * after a call to {@link #stopAppSwitches()}.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506 /**
507 * This is set to true after the first switch after mAppSwitchesAllowedTime
508 * is set; any switches after that will clear the time.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
Ricky Wai906af482019-06-03 17:25:28 +0100512 /**
513 * Last stop app switches time, apps finished before this time cannot start background activity
514 * even if they are in grace period.
515 */
516 private long mLastStopAppSwitchesTime;
517
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700518 IActivityController mController = null;
519 boolean mControllerIsAMonkey = false;
520
Wale Ogunwale214f3482018-10-04 11:00:47 -0700521 final int mFactoryTest;
522
523 /** Used to control how we initialize the service. */
524 ComponentName mTopComponent;
525 String mTopAction = Intent.ACTION_MAIN;
526 String mTopData;
527
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800528 /** Profiling app information. */
529 String mProfileApp = null;
530 WindowProcessController mProfileProc = null;
531 ProfilerInfo mProfilerInfo = null;
532
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700533 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700534 * Dump of the activity state at the time of the last ANR. Cleared after
535 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
536 */
537 String mLastANRState;
538
539 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700540 * Used to retain an update lock when the foreground activity is in
541 * immersive mode.
542 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700543 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700544
545 /**
546 * Packages that are being allowed to perform unrestricted app switches. Mapping is
547 * User -> Type -> uid.
548 */
549 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
550
551 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700552 private int mThumbnailWidth;
553 private int mThumbnailHeight;
554 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700555
556 /**
557 * Flag that indicates if multi-window is enabled.
558 *
559 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
560 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
561 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
562 * At least one of the forms of multi-window must be enabled in order for this flag to be
563 * initialized to 'true'.
564 *
565 * @see #mSupportsSplitScreenMultiWindow
566 * @see #mSupportsFreeformWindowManagement
567 * @see #mSupportsPictureInPicture
568 * @see #mSupportsMultiDisplay
569 */
570 boolean mSupportsMultiWindow;
571 boolean mSupportsSplitScreenMultiWindow;
572 boolean mSupportsFreeformWindowManagement;
573 boolean mSupportsPictureInPicture;
574 boolean mSupportsMultiDisplay;
575 boolean mForceResizableActivities;
576
577 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
578
579 // VR Vr2d Display Id.
580 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700581
Wale Ogunwalef6733932018-06-27 05:14:34 -0700582 /**
583 * Set while we are wanting to sleep, to prevent any
584 * activities from being started/resumed.
585 *
586 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
587 *
588 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
589 * while in the sleep state until there is a pending transition out of sleep, in which case
590 * mSleeping is set to false, and remains false while awake.
591 *
592 * Whether mSleeping can quickly toggled between true/false without the device actually
593 * display changing states is undefined.
594 */
595 private boolean mSleeping = false;
596
597 /**
598 * The process state used for processes that are running the top activities.
599 * This changes between TOP and TOP_SLEEPING to following mSleeping.
600 */
601 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
602
603 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
604 // automatically. Important for devices without direct input devices.
605 private boolean mShowDialogs = true;
606
607 /** Set if we are shutting down the system, similar to sleeping. */
608 boolean mShuttingDown = false;
609
610 /**
611 * We want to hold a wake lock while running a voice interaction session, since
612 * this may happen with the screen off and we need to keep the CPU running to
613 * be able to continue to interact with the user.
614 */
615 PowerManager.WakeLock mVoiceWakeLock;
616
617 /**
618 * Set while we are running a voice interaction. This overrides sleeping while it is active.
619 */
620 IVoiceInteractionSession mRunningVoice;
621
622 /**
623 * The last resumed activity. This is identical to the current resumed activity most
624 * of the time but could be different when we're pausing one activity before we resume
625 * another activity.
626 */
627 ActivityRecord mLastResumedActivity;
628
629 /**
630 * The activity that is currently being traced as the active resumed activity.
631 *
632 * @see #updateResumedAppTrace
633 */
634 private @Nullable ActivityRecord mTracedResumedActivity;
635
636 /** If non-null, we are tracking the time the user spends in the currently focused app. */
637 AppTimeTracker mCurAppTimeTracker;
638
Wale Ogunwale008163e2018-07-23 23:11:08 -0700639 private AppWarnings mAppWarnings;
640
Wale Ogunwale53783742018-09-16 10:21:51 -0700641 /**
642 * Packages that the user has asked to have run in screen size
643 * compatibility mode instead of filling the screen.
644 */
645 CompatModePackages mCompatModePackages;
646
Wale Ogunwalef6733932018-06-27 05:14:34 -0700647 private FontScaleSettingObserver mFontScaleSettingObserver;
648
Ricky Wai96f5c352019-04-10 18:40:17 +0100649 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000650
Wale Ogunwalef6733932018-06-27 05:14:34 -0700651 private final class FontScaleSettingObserver extends ContentObserver {
652 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
653 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
654
655 public FontScaleSettingObserver() {
656 super(mH);
657 final ContentResolver resolver = mContext.getContentResolver();
658 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
659 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
660 UserHandle.USER_ALL);
661 }
662
663 @Override
664 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
665 if (mFontScaleUri.equals(uri)) {
666 updateFontScaleIfNeeded(userId);
667 } else if (mHideErrorDialogsUri.equals(uri)) {
668 synchronized (mGlobalLock) {
669 updateShouldShowDialogsLocked(getGlobalConfiguration());
670 }
671 }
672 }
673 }
674
Riddle Hsua0536432019-02-16 00:38:59 +0800675 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
676 @Target(ElementType.METHOD)
677 @Retention(RetentionPolicy.SOURCE)
678 @interface HotPath {
679 int NONE = 0;
680 int OOM_ADJUSTMENT = 1;
681 int LRU_UPDATE = 2;
682 int PROCESS_CHANGE = 3;
683 int caller() default NONE;
684 }
685
Charles Chen8d98dd22018-12-26 17:36:54 +0800686 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
687 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700688 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700689 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700690 mSystemThread = ActivityThread.currentActivityThread();
691 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700692 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800693 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700694 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700695 }
696
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700697 public void onSystemReady() {
698 synchronized (mGlobalLock) {
699 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
700 PackageManager.FEATURE_CANT_SAVE_STATE);
701 mAssistUtils = new AssistUtils(mContext);
702 mVrController.onSystemReady();
703 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700704 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700705 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700706 }
707
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700708 public void onInitPowerManagement() {
709 synchronized (mGlobalLock) {
710 mStackSupervisor.initPowerManagement();
711 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
712 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
713 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
714 mVoiceWakeLock.setReferenceCounted(false);
715 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700716 }
717
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700718 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700719 mFontScaleSettingObserver = new FontScaleSettingObserver();
720 }
721
Wale Ogunwale59507092018-10-29 09:00:30 -0700722 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700723 final boolean freeformWindowManagement =
724 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
725 || Settings.Global.getInt(
726 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
727
728 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
729 final boolean supportsPictureInPicture = supportsMultiWindow &&
730 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
731 final boolean supportsSplitScreenMultiWindow =
732 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
733 final boolean supportsMultiDisplay = mContext.getPackageManager()
734 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
736 final boolean forceResizable = Settings.Global.getInt(
737 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700738 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700739
740 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900741 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700742
743 final Configuration configuration = new Configuration();
744 Settings.System.getConfiguration(resolver, configuration);
745 if (forceRtl) {
746 // This will take care of setting the correct layout direction flags
747 configuration.setLayoutDirection(configuration.locale);
748 }
749
750 synchronized (mGlobalLock) {
751 mForceResizableActivities = forceResizable;
752 final boolean multiWindowFormEnabled = freeformWindowManagement
753 || supportsSplitScreenMultiWindow
754 || supportsPictureInPicture
755 || supportsMultiDisplay;
756 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
757 mSupportsMultiWindow = true;
758 mSupportsFreeformWindowManagement = freeformWindowManagement;
759 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
760 mSupportsPictureInPicture = supportsPictureInPicture;
761 mSupportsMultiDisplay = supportsMultiDisplay;
762 } else {
763 mSupportsMultiWindow = false;
764 mSupportsFreeformWindowManagement = false;
765 mSupportsSplitScreenMultiWindow = false;
766 mSupportsPictureInPicture = false;
767 mSupportsMultiDisplay = false;
768 }
769 mWindowManager.setForceResizableTasks(mForceResizableActivities);
770 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700771 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
772 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700773 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700774 // This happens before any activities are started, so we can change global configuration
775 // in-place.
776 updateConfigurationLocked(configuration, null, true);
777 final Configuration globalConfig = getGlobalConfiguration();
778 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
779
780 // Load resources only after the current configuration has been set.
781 final Resources res = mContext.getResources();
782 mThumbnailWidth = res.getDimensionPixelSize(
783 com.android.internal.R.dimen.thumbnail_width);
784 mThumbnailHeight = res.getDimensionPixelSize(
785 com.android.internal.R.dimen.thumbnail_height);
786
787 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
788 mFullscreenThumbnailScale = (float) res
789 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
790 (float) globalConfig.screenWidthDp;
791 } else {
792 mFullscreenThumbnailScale = res.getFraction(
793 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
794 }
795 }
796 }
797
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800798 public WindowManagerGlobalLock getGlobalLock() {
799 return mGlobalLock;
800 }
801
Yunfan Chen585f2932019-01-29 16:04:45 +0900802 /** For test purpose only. */
803 @VisibleForTesting
804 public ActivityTaskManagerInternal getAtmInternal() {
805 return mInternal;
806 }
807
Riddle Hsud93a6c42018-11-29 21:50:06 +0800808 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
809 Looper looper) {
810 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700811 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700812 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700813 final File systemDir = SystemServiceManager.ensureSystemDir();
814 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
815 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700816 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700817
818 mTempConfig.setToDefaults();
819 mTempConfig.setLocales(LocaleList.getDefault());
820 mConfigurationSeq = mTempConfig.seq = 1;
821 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800822 mRootActivityContainer = new RootActivityContainer(this);
823 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700824
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700825 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700827 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700828 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700829 mRecentTasks = createRecentTasks();
830 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700831 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700832 mKeyguardController = mStackSupervisor.getKeyguardController();
833 }
834
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700835 public void onActivityManagerInternalAdded() {
836 synchronized (mGlobalLock) {
837 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
838 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
839 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700840 }
841
Yunfan Chen75157d72018-07-27 14:47:21 +0900842 int increaseConfigurationSeqLocked() {
843 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
844 return mConfigurationSeq;
845 }
846
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700847 protected ActivityStackSupervisor createStackSupervisor() {
848 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
849 supervisor.initialize();
850 return supervisor;
851 }
852
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700853 public void setWindowManager(WindowManagerService wm) {
854 synchronized (mGlobalLock) {
855 mWindowManager = wm;
856 mLockTaskController.setWindowManager(wm);
857 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800858 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700859 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700860 }
861
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700862 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
863 synchronized (mGlobalLock) {
864 mUsageStatsInternal = usageStatsManager;
865 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700866 }
867
Wale Ogunwalef6733932018-06-27 05:14:34 -0700868 UserManagerService getUserManager() {
869 if (mUserManager == null) {
870 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
871 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
872 }
873 return mUserManager;
874 }
875
876 AppOpsService getAppOpsService() {
877 if (mAppOpsService == null) {
878 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
879 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
880 }
881 return mAppOpsService;
882 }
883
884 boolean hasUserRestriction(String restriction, int userId) {
885 return getUserManager().hasUserRestriction(restriction, userId);
886 }
887
Michal Karpinski15486842019-04-25 17:33:42 +0100888 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
889 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
890 callingUid, callingPackage);
891 if (mode == AppOpsManager.MODE_DEFAULT) {
892 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
893 == PERMISSION_GRANTED;
894 }
895 return mode == AppOpsManager.MODE_ALLOWED;
896 }
897
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700898 protected RecentTasks createRecentTasks() {
899 return new RecentTasks(this, mStackSupervisor);
900 }
901
902 RecentTasks getRecentTasks() {
903 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700904 }
905
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700906 ClientLifecycleManager getLifecycleManager() {
907 return mLifecycleManager;
908 }
909
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700910 ActivityStartController getActivityStartController() {
911 return mActivityStartController;
912 }
913
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700914 TaskChangeNotificationController getTaskChangeNotificationController() {
915 return mTaskChangeNotificationController;
916 }
917
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700918 LockTaskController getLockTaskController() {
919 return mLockTaskController;
920 }
921
Yunfan Chen75157d72018-07-27 14:47:21 +0900922 /**
923 * Return the global configuration used by the process corresponding to the input pid. This is
924 * usually the global configuration with some overrides specific to that process.
925 */
926 Configuration getGlobalConfigurationForCallingPid() {
927 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800928 return getGlobalConfigurationForPid(pid);
929 }
930
931 /**
932 * Return the global configuration used by the process corresponding to the given pid.
933 */
934 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900935 if (pid == MY_PID || pid < 0) {
936 return getGlobalConfiguration();
937 }
938 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100939 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900940 return app != null ? app.getConfiguration() : getGlobalConfiguration();
941 }
942 }
943
944 /**
945 * Return the device configuration info used by the process corresponding to the input pid.
946 * The value is consistent with the global configuration for the process.
947 */
948 @Override
949 public ConfigurationInfo getDeviceConfigurationInfo() {
950 ConfigurationInfo config = new ConfigurationInfo();
951 synchronized (mGlobalLock) {
952 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
953 config.reqTouchScreen = globalConfig.touchscreen;
954 config.reqKeyboardType = globalConfig.keyboard;
955 config.reqNavigation = globalConfig.navigation;
956 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
957 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
958 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
959 }
960 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
961 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
962 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
963 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700964 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900965 }
966 return config;
967 }
968
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700969 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700970 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700971 }
972
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700973 public static final class Lifecycle extends SystemService {
974 private final ActivityTaskManagerService mService;
975
976 public Lifecycle(Context context) {
977 super(context);
978 mService = new ActivityTaskManagerService(context);
979 }
980
981 @Override
982 public void onStart() {
983 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700984 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700985 }
986
Garfield Tan891146c2018-10-09 12:14:00 -0700987 @Override
988 public void onUnlockUser(int userId) {
989 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800990 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700991 }
992 }
993
994 @Override
995 public void onCleanupUser(int userId) {
996 synchronized (mService.getGlobalLock()) {
997 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
998 }
999 }
1000
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001001 public ActivityTaskManagerService getService() {
1002 return mService;
1003 }
1004 }
1005
1006 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001007 public final int startActivity(IApplicationThread caller, String callingPackage,
1008 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1009 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1010 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1011 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1012 UserHandle.getCallingUserId());
1013 }
1014
1015 @Override
1016 public final int startActivities(IApplicationThread caller, String callingPackage,
1017 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1018 int userId) {
1019 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001020 enforceNotIsolatedCaller(reason);
1021 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001023 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1024 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1025 reason, null /* originatingPendingIntent */,
1026 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 }
1028
1029 @Override
1030 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1031 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1032 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1033 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1034 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1035 true /*validateIncomingUser*/);
1036 }
1037
1038 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1039 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1040 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1041 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001042 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001043
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001044 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1046
1047 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001048 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001049 .setCaller(caller)
1050 .setCallingPackage(callingPackage)
1051 .setResolvedType(resolvedType)
1052 .setResultTo(resultTo)
1053 .setResultWho(resultWho)
1054 .setRequestCode(requestCode)
1055 .setStartFlags(startFlags)
1056 .setProfilerInfo(profilerInfo)
1057 .setActivityOptions(bOptions)
1058 .setMayWait(userId)
1059 .execute();
1060
1061 }
1062
1063 @Override
1064 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1065 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001066 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1067 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001068 // Refuse possible leaked file descriptors
1069 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1070 throw new IllegalArgumentException("File descriptors passed in Intent");
1071 }
1072
1073 if (!(target instanceof PendingIntentRecord)) {
1074 throw new IllegalArgumentException("Bad PendingIntent object");
1075 }
1076
1077 PendingIntentRecord pir = (PendingIntentRecord)target;
1078
1079 synchronized (mGlobalLock) {
1080 // If this is coming from the currently resumed activity, it is
1081 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001082 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001083 if (stack.mResumedActivity != null &&
1084 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001085 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001086 }
1087 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001088 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001090 }
1091
1092 @Override
1093 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1094 Bundle bOptions) {
1095 // Refuse possible leaked file descriptors
1096 if (intent != null && intent.hasFileDescriptors()) {
1097 throw new IllegalArgumentException("File descriptors passed in Intent");
1098 }
1099 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1100
1101 synchronized (mGlobalLock) {
1102 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1103 if (r == null) {
1104 SafeActivityOptions.abort(options);
1105 return false;
1106 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001107 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001108 // The caller is not running... d'oh!
1109 SafeActivityOptions.abort(options);
1110 return false;
1111 }
1112 intent = new Intent(intent);
1113 // The caller is not allowed to change the data.
1114 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1115 // And we are resetting to find the next component...
1116 intent.setComponent(null);
1117
1118 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1119
1120 ActivityInfo aInfo = null;
1121 try {
1122 List<ResolveInfo> resolves =
1123 AppGlobals.getPackageManager().queryIntentActivities(
1124 intent, r.resolvedType,
1125 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1126 UserHandle.getCallingUserId()).getList();
1127
1128 // Look for the original activity in the list...
1129 final int N = resolves != null ? resolves.size() : 0;
1130 for (int i=0; i<N; i++) {
1131 ResolveInfo rInfo = resolves.get(i);
1132 if (rInfo.activityInfo.packageName.equals(r.packageName)
1133 && rInfo.activityInfo.name.equals(r.info.name)) {
1134 // We found the current one... the next matching is
1135 // after it.
1136 i++;
1137 if (i<N) {
1138 aInfo = resolves.get(i).activityInfo;
1139 }
1140 if (debug) {
1141 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1142 + "/" + r.info.name);
1143 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1144 ? "null" : aInfo.packageName + "/" + aInfo.name));
1145 }
1146 break;
1147 }
1148 }
1149 } catch (RemoteException e) {
1150 }
1151
1152 if (aInfo == null) {
1153 // Nobody who is next!
1154 SafeActivityOptions.abort(options);
1155 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1156 return false;
1157 }
1158
1159 intent.setComponent(new ComponentName(
1160 aInfo.applicationInfo.packageName, aInfo.name));
1161 intent.setFlags(intent.getFlags()&~(
1162 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1163 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1164 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1165 FLAG_ACTIVITY_NEW_TASK));
1166
1167 // Okay now we need to start the new activity, replacing the currently running activity.
1168 // This is a little tricky because we want to start the new one as if the current one is
1169 // finished, but not finish the current one first so that there is no flicker.
1170 // And thus...
1171 final boolean wasFinishing = r.finishing;
1172 r.finishing = true;
1173
1174 // Propagate reply information over to the new activity.
1175 final ActivityRecord resultTo = r.resultTo;
1176 final String resultWho = r.resultWho;
1177 final int requestCode = r.requestCode;
1178 r.resultTo = null;
1179 if (resultTo != null) {
1180 resultTo.removeResultsLocked(r, resultWho, requestCode);
1181 }
1182
1183 final long origId = Binder.clearCallingIdentity();
1184 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001185 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001186 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001187 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001188 .setResolvedType(r.resolvedType)
1189 .setActivityInfo(aInfo)
1190 .setResultTo(resultTo != null ? resultTo.appToken : null)
1191 .setResultWho(resultWho)
1192 .setRequestCode(requestCode)
1193 .setCallingPid(-1)
1194 .setCallingUid(r.launchedFromUid)
1195 .setCallingPackage(r.launchedFromPackage)
1196 .setRealCallingPid(-1)
1197 .setRealCallingUid(r.launchedFromUid)
1198 .setActivityOptions(options)
1199 .execute();
1200 Binder.restoreCallingIdentity(origId);
1201
1202 r.finishing = wasFinishing;
1203 if (res != ActivityManager.START_SUCCESS) {
1204 return false;
1205 }
1206 return true;
1207 }
1208 }
1209
1210 @Override
1211 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1212 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1213 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1214 final WaitResult res = new WaitResult();
1215 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001216 enforceNotIsolatedCaller("startActivityAndWait");
1217 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1218 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001219 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001220 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 .setCaller(caller)
1222 .setCallingPackage(callingPackage)
1223 .setResolvedType(resolvedType)
1224 .setResultTo(resultTo)
1225 .setResultWho(resultWho)
1226 .setRequestCode(requestCode)
1227 .setStartFlags(startFlags)
1228 .setActivityOptions(bOptions)
1229 .setMayWait(userId)
1230 .setProfilerInfo(profilerInfo)
1231 .setWaitResult(res)
1232 .execute();
1233 }
1234 return res;
1235 }
1236
1237 @Override
1238 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1239 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1240 int startFlags, Configuration config, Bundle bOptions, int userId) {
1241 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001242 enforceNotIsolatedCaller("startActivityWithConfig");
1243 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1244 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001245 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001246 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001247 .setCaller(caller)
1248 .setCallingPackage(callingPackage)
1249 .setResolvedType(resolvedType)
1250 .setResultTo(resultTo)
1251 .setResultWho(resultWho)
1252 .setRequestCode(requestCode)
1253 .setStartFlags(startFlags)
1254 .setGlobalConfiguration(config)
1255 .setActivityOptions(bOptions)
1256 .setMayWait(userId)
1257 .execute();
1258 }
1259 }
1260
Alison Cichowlas3e340502018-08-07 17:15:01 -04001261
1262 @Override
1263 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1264 int callingUid = Binder.getCallingUid();
1265 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1266 throw new SecurityException("Only the system process can request a permission token, "
1267 + "received request from uid: " + callingUid);
1268 }
1269 IBinder permissionToken = new Binder();
1270 synchronized (mGlobalLock) {
1271 mStartActivitySources.put(permissionToken, delegatorToken);
1272 }
1273
1274 Message expireMsg = PooledLambda.obtainMessage(
1275 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1276 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1277
1278 Message forgetMsg = PooledLambda.obtainMessage(
1279 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1280 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1281
1282 return permissionToken;
1283 }
1284
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 @Override
1286 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1287 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001288 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1289 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001290 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001291 // permission grants) as any app that may launch one of your own activities. So we only
1292 // allow this in two cases:
1293 // 1) The caller is an activity that is part of the core framework, and then only when it
1294 // is running as the system.
1295 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1296 // can only be requested by a system activity, which may then delegate this call to
1297 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001298 final ActivityRecord sourceRecord;
1299 final int targetUid;
1300 final String targetPackage;
1301 final boolean isResolver;
1302 synchronized (mGlobalLock) {
1303 if (resultTo == null) {
1304 throw new SecurityException("Must be called from an activity");
1305 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001306 final IBinder sourceToken;
1307 if (permissionToken != null) {
1308 // To even attempt to use a permissionToken, an app must also have this signature
1309 // permission.
1310 mAmInternal.enforceCallingPermission(
1311 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1312 "startActivityAsCaller");
1313 // If called with a permissionToken, we want the sourceRecord from the delegator
1314 // activity that requested this token.
1315 sourceToken = mStartActivitySources.remove(permissionToken);
1316 if (sourceToken == null) {
1317 // Invalid permissionToken, check if it recently expired.
1318 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1319 throw new SecurityException("Called with expired permission token: "
1320 + permissionToken);
1321 } else {
1322 throw new SecurityException("Called with invalid permission token: "
1323 + permissionToken);
1324 }
1325 }
1326 } else {
1327 // This method was called directly by the source.
1328 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001330
Wale Ogunwaled32da472018-11-16 07:19:28 -08001331 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001332 if (sourceRecord == null) {
1333 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001334 }
1335 if (sourceRecord.app == null) {
1336 throw new SecurityException("Called without a process attached to activity");
1337 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001338
1339 // Whether called directly or from a delegate, the source activity must be from the
1340 // android package.
1341 if (!sourceRecord.info.packageName.equals("android")) {
1342 throw new SecurityException("Must be called from an activity that is "
1343 + "declared in the android package");
1344 }
1345
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001346 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 // This is still okay, as long as this activity is running under the
1348 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001349 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001351 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001352 + " must be system uid or original calling uid "
1353 + sourceRecord.launchedFromUid);
1354 }
1355 }
1356 if (ignoreTargetSecurity) {
1357 if (intent.getComponent() == null) {
1358 throw new SecurityException(
1359 "Component must be specified with ignoreTargetSecurity");
1360 }
1361 if (intent.getSelector() != null) {
1362 throw new SecurityException(
1363 "Selector not allowed with ignoreTargetSecurity");
1364 }
1365 }
1366 targetUid = sourceRecord.launchedFromUid;
1367 targetPackage = sourceRecord.launchedFromPackage;
1368 isResolver = sourceRecord.isResolverOrChildActivity();
1369 }
1370
1371 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001372 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 }
1374
1375 // TODO: Switch to user app stacks here.
1376 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001377 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 .setCallingUid(targetUid)
1379 .setCallingPackage(targetPackage)
1380 .setResolvedType(resolvedType)
1381 .setResultTo(resultTo)
1382 .setResultWho(resultWho)
1383 .setRequestCode(requestCode)
1384 .setStartFlags(startFlags)
1385 .setActivityOptions(bOptions)
1386 .setMayWait(userId)
1387 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1388 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001389 // The target may well be in the background, which would normally prevent it
1390 // from starting an activity. Here we definitely want the start to succeed.
1391 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001392 .execute();
1393 } catch (SecurityException e) {
1394 // XXX need to figure out how to propagate to original app.
1395 // A SecurityException here is generally actually a fault of the original
1396 // calling activity (such as a fairly granting permissions), so propagate it
1397 // back to them.
1398 /*
1399 StringBuilder msg = new StringBuilder();
1400 msg.append("While launching");
1401 msg.append(intent.toString());
1402 msg.append(": ");
1403 msg.append(e.getMessage());
1404 */
1405 throw e;
1406 }
1407 }
1408
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001409 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1410 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1411 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1412 }
1413
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001414 @Override
1415 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1416 Intent intent, String resolvedType, IVoiceInteractionSession session,
1417 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1418 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001419 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001420 if (session == null || interactor == null) {
1421 throw new NullPointerException("null session or interactor");
1422 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001423 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001425 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001426 .setCallingUid(callingUid)
1427 .setCallingPackage(callingPackage)
1428 .setResolvedType(resolvedType)
1429 .setVoiceSession(session)
1430 .setVoiceInteractor(interactor)
1431 .setStartFlags(startFlags)
1432 .setProfilerInfo(profilerInfo)
1433 .setActivityOptions(bOptions)
1434 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001435 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001436 .execute();
1437 }
1438
1439 @Override
1440 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1441 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001442 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1443 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001444
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001445 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 .setCallingUid(callingUid)
1447 .setCallingPackage(callingPackage)
1448 .setResolvedType(resolvedType)
1449 .setActivityOptions(bOptions)
1450 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001451 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001452 .execute();
1453 }
1454
1455 @Override
1456 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1457 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001458 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001459 final int callingPid = Binder.getCallingPid();
1460 final long origId = Binder.clearCallingIdentity();
1461 try {
1462 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001463 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1464 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465
1466 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001467 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1468 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001469 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1470 recentsUid, assistDataReceiver);
1471 }
1472 } finally {
1473 Binder.restoreCallingIdentity(origId);
1474 }
1475 }
1476
1477 @Override
1478 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001479 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 "startActivityFromRecents()");
1481
1482 final int callingPid = Binder.getCallingPid();
1483 final int callingUid = Binder.getCallingUid();
1484 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1485 final long origId = Binder.clearCallingIdentity();
1486 try {
1487 synchronized (mGlobalLock) {
1488 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1489 safeOptions);
1490 }
1491 } finally {
1492 Binder.restoreCallingIdentity(origId);
1493 }
1494 }
1495
1496 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001497 * Public API to check if the client is allowed to start an activity on specified display.
1498 *
1499 * If the target display is private or virtual, some restrictions will apply.
1500 *
1501 * @param displayId Target display id.
1502 * @param intent Intent used to launch the activity.
1503 * @param resolvedType The MIME type of the intent.
1504 * @param userId The id of the user for whom the call is made.
1505 * @return {@code true} if a call to start an activity on the target display should succeed and
1506 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1507 */
1508 @Override
1509 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1510 String resolvedType, int userId) {
1511 final int callingUid = Binder.getCallingUid();
1512 final int callingPid = Binder.getCallingPid();
1513 final long origId = Binder.clearCallingIdentity();
1514
1515 try {
1516 // Collect information about the target of the Intent.
1517 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1518 0 /* startFlags */, null /* profilerInfo */, userId,
1519 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1520 UserHandle.USER_NULL));
1521 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1522
1523 synchronized (mGlobalLock) {
1524 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1525 aInfo);
1526 }
1527 } finally {
1528 Binder.restoreCallingIdentity(origId);
1529 }
1530 }
1531
1532 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001533 * This is the internal entry point for handling Activity.finish().
1534 *
1535 * @param token The Binder token referencing the Activity we want to finish.
1536 * @param resultCode Result code, if any, from this Activity.
1537 * @param resultData Result data (Intent), if any, from this Activity.
1538 * @param finishTask Whether to finish the task associated with this Activity.
1539 *
1540 * @return Returns true if the activity successfully finished, or false if it is still running.
1541 */
1542 @Override
1543 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1544 int finishTask) {
1545 // Refuse possible leaked file descriptors
1546 if (resultData != null && resultData.hasFileDescriptors()) {
1547 throw new IllegalArgumentException("File descriptors passed in Intent");
1548 }
1549
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001550 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001552 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001553 if (r == null) {
1554 return true;
1555 }
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001556 }
1557
1558 // Carefully collect grants without holding lock
1559 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
1560 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
1561
1562 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001563 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001564 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 ActivityRecord rootR = tr.getRootActivity();
1566 if (rootR == null) {
1567 Slog.w(TAG, "Finishing task with all activities already finished");
1568 }
1569 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1570 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001571 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 return false;
1573 }
1574
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001575 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1576 // We should consolidate.
1577 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001578 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001579 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001580 if (next != null) {
1581 // ask watcher if this is allowed
1582 boolean resumeOK = true;
1583 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001584 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001585 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001586 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001587 Watchdog.getInstance().setActivityController(null);
1588 }
1589
1590 if (!resumeOK) {
1591 Slog.i(TAG, "Not finishing activity because controller resumed");
1592 return false;
1593 }
1594 }
1595 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001596
1597 // note down that the process has finished an activity and is in background activity
1598 // starts grace period
1599 if (r.app != null) {
1600 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1601 }
1602
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001603 final long origId = Binder.clearCallingIdentity();
1604 try {
1605 boolean res;
1606 final boolean finishWithRootActivity =
1607 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1608 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1609 || (finishWithRootActivity && r == rootR)) {
1610 // If requested, remove the task that is associated to this activity only if it
1611 // was the root activity in the task. The result code and data is ignored
1612 // because we don't support returning them across task boundaries. Also, to
1613 // keep backwards compatibility we remove the task from recents when finishing
1614 // task with root activity.
1615 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1616 finishWithRootActivity, "finish-activity");
1617 if (!res) {
1618 Slog.i(TAG, "Removing task failed to finish activity");
1619 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001620 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001621 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001622 } else {
1623 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06001624 resultData, resultGrants, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001625 if (!res) {
1626 Slog.i(TAG, "Failed to finish by app-request");
1627 }
1628 }
1629 return res;
1630 } finally {
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633 }
1634 }
1635
1636 @Override
1637 public boolean finishActivityAffinity(IBinder token) {
1638 synchronized (mGlobalLock) {
1639 final long origId = Binder.clearCallingIdentity();
1640 try {
1641 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1642 if (r == null) {
1643 return false;
1644 }
1645
1646 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1647 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001648 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001649 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 return false;
1651 }
1652 return task.getStack().finishActivityAffinityLocked(r);
1653 } finally {
1654 Binder.restoreCallingIdentity(origId);
1655 }
1656 }
1657 }
1658
1659 @Override
1660 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1661 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001662 try {
1663 WindowProcessController proc = null;
1664 synchronized (mGlobalLock) {
1665 ActivityStack stack = ActivityRecord.getStackLocked(token);
1666 if (stack == null) {
1667 return;
1668 }
1669 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1670 false /* fromTimeout */, false /* processPausingActivities */, config);
1671 if (r != null) {
1672 proc = r.app;
1673 }
1674 if (stopProfiling && proc != null) {
1675 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
1677 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001678 } finally {
1679 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001680 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001681 }
1682
1683 @Override
1684 public final void activityResumed(IBinder token) {
1685 final long origId = Binder.clearCallingIdentity();
1686 synchronized (mGlobalLock) {
1687 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001688 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001689 }
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001694 public final void activityTopResumedStateLost() {
1695 final long origId = Binder.clearCallingIdentity();
1696 synchronized (mGlobalLock) {
1697 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1698 }
1699 Binder.restoreCallingIdentity(origId);
1700 }
1701
1702 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001703 public final void activityPaused(IBinder token) {
1704 final long origId = Binder.clearCallingIdentity();
1705 synchronized (mGlobalLock) {
1706 ActivityStack stack = ActivityRecord.getStackLocked(token);
1707 if (stack != null) {
1708 stack.activityPausedLocked(token, false);
1709 }
1710 }
1711 Binder.restoreCallingIdentity(origId);
1712 }
1713
1714 @Override
1715 public final void activityStopped(IBinder token, Bundle icicle,
1716 PersistableBundle persistentState, CharSequence description) {
1717 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1718
1719 // Refuse possible leaked file descriptors
1720 if (icicle != null && icicle.hasFileDescriptors()) {
1721 throw new IllegalArgumentException("File descriptors passed in Bundle");
1722 }
1723
1724 final long origId = Binder.clearCallingIdentity();
1725
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001726 String restartingName = null;
1727 int restartingUid = 0;
1728 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001729 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001732 if (r.attachedToProcess()
1733 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1734 // The activity was requested to restart from
1735 // {@link #restartActivityProcessIfVisible}.
1736 restartingName = r.app.mName;
1737 restartingUid = r.app.mUid;
1738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001739 r.activityStoppedLocked(icicle, persistentState, description);
1740 }
1741 }
1742
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001743 if (restartingName != null) {
1744 // In order to let the foreground activity can be restarted with its saved state from
1745 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1746 // until the activity reports stopped with the state. And the activity record will be
1747 // kept because the record state is restarting, then the activity will be restarted
1748 // immediately if it is still the top one.
1749 mStackSupervisor.removeRestartTimeouts(r);
1750 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1751 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001752 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753
1754 Binder.restoreCallingIdentity(origId);
1755 }
1756
1757 @Override
1758 public final void activityDestroyed(IBinder token) {
1759 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1760 synchronized (mGlobalLock) {
1761 ActivityStack stack = ActivityRecord.getStackLocked(token);
1762 if (stack != null) {
1763 stack.activityDestroyedLocked(token, "activityDestroyed");
1764 }
1765 }
1766 }
1767
1768 @Override
1769 public final void activityRelaunched(IBinder token) {
1770 final long origId = Binder.clearCallingIdentity();
1771 synchronized (mGlobalLock) {
1772 mStackSupervisor.activityRelaunchedLocked(token);
1773 }
1774 Binder.restoreCallingIdentity(origId);
1775 }
1776
1777 public final void activitySlept(IBinder token) {
1778 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1779
1780 final long origId = Binder.clearCallingIdentity();
1781
1782 synchronized (mGlobalLock) {
1783 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1784 if (r != null) {
1785 mStackSupervisor.activitySleptLocked(r);
1786 }
1787 }
1788
1789 Binder.restoreCallingIdentity(origId);
1790 }
1791
1792 @Override
1793 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1794 synchronized (mGlobalLock) {
1795 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1796 if (r == null) {
1797 return;
1798 }
1799 final long origId = Binder.clearCallingIdentity();
1800 try {
1801 r.setRequestedOrientation(requestedOrientation);
1802 } finally {
1803 Binder.restoreCallingIdentity(origId);
1804 }
1805 }
1806 }
1807
1808 @Override
1809 public int getRequestedOrientation(IBinder token) {
1810 synchronized (mGlobalLock) {
1811 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1812 if (r == null) {
1813 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1814 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001815 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001816 }
1817 }
1818
1819 @Override
1820 public void setImmersive(IBinder token, boolean immersive) {
1821 synchronized (mGlobalLock) {
1822 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1823 if (r == null) {
1824 throw new IllegalArgumentException();
1825 }
1826 r.immersive = immersive;
1827
1828 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001829 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001830 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001831 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 }
1833 }
1834 }
1835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001836 void applyUpdateLockStateLocked(ActivityRecord r) {
1837 // Modifications to the UpdateLock state are done on our handler, outside
1838 // the activity manager's locks. The new state is determined based on the
1839 // state *now* of the relevant activity record. The object is passed to
1840 // the handler solely for logging detail, not to be consulted/modified.
1841 final boolean nextState = r != null && r.immersive;
1842 mH.post(() -> {
1843 if (mUpdateLock.isHeld() != nextState) {
1844 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1845 "Applying new update lock state '" + nextState + "' for " + r);
1846 if (nextState) {
1847 mUpdateLock.acquire();
1848 } else {
1849 mUpdateLock.release();
1850 }
1851 }
1852 });
1853 }
1854
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001855 @Override
1856 public boolean isImmersive(IBinder token) {
1857 synchronized (mGlobalLock) {
1858 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1859 if (r == null) {
1860 throw new IllegalArgumentException();
1861 }
1862 return r.immersive;
1863 }
1864 }
1865
1866 @Override
1867 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001868 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001870 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001871 return (r != null) ? r.immersive : false;
1872 }
1873 }
1874
1875 @Override
1876 public void overridePendingTransition(IBinder token, String packageName,
1877 int enterAnim, int exitAnim) {
1878 synchronized (mGlobalLock) {
1879 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1880 if (self == null) {
1881 return;
1882 }
1883
1884 final long origId = Binder.clearCallingIdentity();
1885
1886 if (self.isState(
1887 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001888 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001889 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 }
1891
1892 Binder.restoreCallingIdentity(origId);
1893 }
1894 }
1895
1896 @Override
1897 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001898 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001899 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001900 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 if (r == null) {
1902 return ActivityManager.COMPAT_MODE_UNKNOWN;
1903 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001904 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 }
1906 }
1907
1908 @Override
1909 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001910 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001911 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001912 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001914 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 if (r == null) {
1916 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1917 return;
1918 }
1919 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001920 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 }
1922 }
1923
1924 @Override
1925 public int getLaunchedFromUid(IBinder activityToken) {
1926 ActivityRecord srec;
1927 synchronized (mGlobalLock) {
1928 srec = ActivityRecord.forTokenLocked(activityToken);
1929 }
1930 if (srec == null) {
1931 return -1;
1932 }
1933 return srec.launchedFromUid;
1934 }
1935
1936 @Override
1937 public String getLaunchedFromPackage(IBinder activityToken) {
1938 ActivityRecord srec;
1939 synchronized (mGlobalLock) {
1940 srec = ActivityRecord.forTokenLocked(activityToken);
1941 }
1942 if (srec == null) {
1943 return null;
1944 }
1945 return srec.launchedFromPackage;
1946 }
1947
1948 @Override
1949 public boolean convertFromTranslucent(IBinder token) {
1950 final long origId = Binder.clearCallingIdentity();
1951 try {
1952 synchronized (mGlobalLock) {
1953 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1954 if (r == null) {
1955 return false;
1956 }
1957 final boolean translucentChanged = r.changeWindowTranslucency(true);
1958 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001959 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001960 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 return translucentChanged;
1963 }
1964 } finally {
1965 Binder.restoreCallingIdentity(origId);
1966 }
1967 }
1968
1969 @Override
1970 public boolean convertToTranslucent(IBinder token, Bundle options) {
1971 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1972 final long origId = Binder.clearCallingIdentity();
1973 try {
1974 synchronized (mGlobalLock) {
1975 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1976 if (r == null) {
1977 return false;
1978 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001979 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 int index = task.mActivities.lastIndexOf(r);
1981 if (index > 0) {
1982 ActivityRecord under = task.mActivities.get(index - 1);
1983 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1984 }
1985 final boolean translucentChanged = r.changeWindowTranslucency(false);
1986 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001987 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001989 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001990 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001991 return translucentChanged;
1992 }
1993 } finally {
1994 Binder.restoreCallingIdentity(origId);
1995 }
1996 }
1997
1998 @Override
1999 public void notifyActivityDrawn(IBinder token) {
2000 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
2001 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002002 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002004 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 }
2006 }
2007 }
2008
2009 @Override
2010 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
2011 synchronized (mGlobalLock) {
2012 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2013 if (r == null) {
2014 return;
2015 }
2016 r.reportFullyDrawnLocked(restoredFromBundle);
2017 }
2018 }
2019
2020 @Override
2021 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2022 synchronized (mGlobalLock) {
2023 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2024 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2025 return stack.mDisplayId;
2026 }
2027 return DEFAULT_DISPLAY;
2028 }
2029 }
2030
2031 @Override
2032 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002033 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 long ident = Binder.clearCallingIdentity();
2035 try {
2036 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002037 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002039 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 return null;
2042 }
2043 } finally {
2044 Binder.restoreCallingIdentity(ident);
2045 }
2046 }
2047
2048 @Override
2049 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002050 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002051 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2052 final long callingId = Binder.clearCallingIdentity();
2053 try {
2054 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002055 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002056 if (stack == null) {
2057 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2058 return;
2059 }
2060 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002061 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002062 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002063 }
2064 }
2065 } finally {
2066 Binder.restoreCallingIdentity(callingId);
2067 }
2068 }
2069
2070 @Override
2071 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2074 final long callingId = Binder.clearCallingIdentity();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002078 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002079 if (task == null) {
2080 return;
2081 }
2082 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002083 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002084 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 }
2086 }
2087 } finally {
2088 Binder.restoreCallingIdentity(callingId);
2089 }
2090 }
2091
2092 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002093 public void restartActivityProcessIfVisible(IBinder activityToken) {
2094 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2095 final long callingId = Binder.clearCallingIdentity();
2096 try {
2097 synchronized (mGlobalLock) {
2098 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2099 if (r == null) {
2100 return;
2101 }
2102 r.restartProcessIfVisible();
2103 }
2104 } finally {
2105 Binder.restoreCallingIdentity(callingId);
2106 }
2107 }
2108
2109 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002111 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002112 synchronized (mGlobalLock) {
2113 final long ident = Binder.clearCallingIdentity();
2114 try {
2115 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2116 "remove-task");
2117 } finally {
2118 Binder.restoreCallingIdentity(ident);
2119 }
2120 }
2121 }
2122
2123 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002124 public void removeAllVisibleRecentTasks() {
2125 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2126 synchronized (mGlobalLock) {
2127 final long ident = Binder.clearCallingIdentity();
2128 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002129 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002130 } finally {
2131 Binder.restoreCallingIdentity(ident);
2132 }
2133 }
2134 }
2135
2136 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2138 synchronized (mGlobalLock) {
2139 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2140 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002141 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 }
2143 }
2144 return false;
2145 }
2146
2147 @Override
2148 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2149 Intent resultData) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002150 final ActivityRecord r;
2151 synchronized (mGlobalLock) {
2152 r = ActivityRecord.isInStackLocked(token);
2153 if (r == null) {
2154 return false;
2155 }
2156 }
2157
2158 // Carefully collect grants without holding lock
2159 final NeededUriGrants destGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
2160 Binder.getCallingUid(), destIntent, r.packageName, r.mUserId);
2161 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
2162 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163
2164 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002165 return r.getActivityStack().navigateUpToLocked(
2166 r, destIntent, destGrants, resultCode, resultData, resultGrants);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002167 }
2168 }
2169
2170 /**
2171 * Attempts to move a task backwards in z-order (the order of activities within the task is
2172 * unchanged).
2173 *
2174 * There are several possible results of this call:
2175 * - if the task is locked, then we will show the lock toast
2176 * - if there is a task behind the provided task, then that task is made visible and resumed as
2177 * this task is moved to the back
2178 * - otherwise, if there are no other tasks in the stack:
2179 * - if this task is in the pinned stack, then we remove the stack completely, which will
2180 * have the effect of moving the task to the top or bottom of the fullscreen stack
2181 * (depending on whether it is visible)
2182 * - otherwise, we simply return home and hide this task
2183 *
2184 * @param token A reference to the activity we wish to move
2185 * @param nonRoot If false then this only works if the activity is the root
2186 * of a task; if true it will work for any activity in a task.
2187 * @return Returns true if the move completed, false if not.
2188 */
2189 @Override
2190 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002191 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002192 synchronized (mGlobalLock) {
2193 final long origId = Binder.clearCallingIdentity();
2194 try {
2195 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002196 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 if (task != null) {
2198 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2199 }
2200 } finally {
2201 Binder.restoreCallingIdentity(origId);
2202 }
2203 }
2204 return false;
2205 }
2206
2207 @Override
2208 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002209 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 long ident = Binder.clearCallingIdentity();
2211 Rect rect = new Rect();
2212 try {
2213 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002214 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002215 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2216 if (task == null) {
2217 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2218 return rect;
2219 }
2220 if (task.getStack() != null) {
2221 // Return the bounds from window manager since it will be adjusted for various
2222 // things like the presense of a docked stack for tasks that aren't resizeable.
2223 task.getWindowContainerBounds(rect);
2224 } else {
2225 // Task isn't in window manager yet since it isn't associated with a stack.
2226 // Return the persist value from activity manager
2227 if (!task.matchParentBounds()) {
2228 rect.set(task.getBounds());
2229 } else if (task.mLastNonFullscreenBounds != null) {
2230 rect.set(task.mLastNonFullscreenBounds);
2231 }
2232 }
2233 }
2234 } finally {
2235 Binder.restoreCallingIdentity(ident);
2236 }
2237 return rect;
2238 }
2239
2240 @Override
2241 public ActivityManager.TaskDescription getTaskDescription(int id) {
2242 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002243 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002245 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002246 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2247 if (tr != null) {
2248 return tr.lastTaskDescription;
2249 }
2250 }
2251 return null;
2252 }
2253
2254 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002255 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2256 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2257 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2258 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2259 return;
2260 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002261 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002262 synchronized (mGlobalLock) {
2263 final long ident = Binder.clearCallingIdentity();
2264 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002265 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002266 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002267 if (task == null) {
2268 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2269 return;
2270 }
2271
2272 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2273 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2274
2275 if (!task.isActivityTypeStandardOrUndefined()) {
2276 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2277 + " non-standard task " + taskId + " to windowing mode="
2278 + windowingMode);
2279 }
2280
2281 final ActivityStack stack = task.getStack();
2282 if (toTop) {
2283 stack.moveToFront("setTaskWindowingMode", task);
2284 }
2285 stack.setWindowingMode(windowingMode);
2286 } finally {
2287 Binder.restoreCallingIdentity(ident);
2288 }
2289 }
2290 }
2291
2292 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002293 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002294 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 ActivityRecord r = getCallingRecordLocked(token);
2296 return r != null ? r.info.packageName : null;
2297 }
2298 }
2299
2300 @Override
2301 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002302 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002303 ActivityRecord r = getCallingRecordLocked(token);
2304 return r != null ? r.intent.getComponent() : null;
2305 }
2306 }
2307
2308 private ActivityRecord getCallingRecordLocked(IBinder token) {
2309 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2310 if (r == null) {
2311 return null;
2312 }
2313 return r.resultTo;
2314 }
2315
2316 @Override
2317 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002318 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002319
2320 synchronized (mGlobalLock) {
2321 final long origId = Binder.clearCallingIdentity();
2322 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002323 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002324 } finally {
2325 Binder.restoreCallingIdentity(origId);
2326 }
2327 }
2328 }
2329
Mark Renouf446251d2019-04-26 10:22:41 -04002330 @Override
2331 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2332 synchronized (mGlobalLock) {
2333 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2334 if (r == null) {
2335 return;
2336 }
2337 ActivityStack stack = r.getActivityStack();
2338 if (stack != null && stack.isSingleTaskInstance()) {
2339 // Single-task stacks are used for activities which are presented in floating
2340 // windows above full screen activities. Instead of directly finishing the
2341 // task, a task change listener is used to notify SystemUI so the action can be
2342 // handled specially.
2343 final TaskRecord task = r.getTaskRecord();
2344 mTaskChangeNotificationController
2345 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2346 } else {
2347 try {
2348 callback.requestFinish();
2349 } catch (RemoteException e) {
2350 Slog.e(TAG, "Failed to invoke request finish callback", e);
2351 }
2352 }
2353 }
2354 }
2355
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 /**
2357 * TODO: Add mController hook
2358 */
2359 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002360 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2361 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002362 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363
2364 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2365 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2367 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 }
2369 }
2370
Ricky Waiaca8a772019-04-04 16:01:06 +01002371 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2372 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002373 boolean fromRecents) {
2374
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 final int callingPid = Binder.getCallingPid();
2376 final int callingUid = Binder.getCallingUid();
2377 if (!isSameApp(callingUid, callingPackage)) {
2378 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2379 + Binder.getCallingPid() + " as package " + callingPackage;
2380 Slog.w(TAG, msg);
2381 throw new SecurityException(msg);
2382 }
2383 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 SafeActivityOptions.abort(options);
2385 return;
2386 }
2387 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002388 WindowProcessController callerApp = null;
2389 if (appThread != null) {
2390 callerApp = getProcessController(appThread);
2391 }
2392 final ActivityStarter starter = getActivityStartController().obtainStarter(
2393 null /* intent */, "moveTaskToFront");
2394 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2395 -1, callerApp, null, false, null)) {
2396 boolean abort = !isBackgroundActivityStartsEnabled();
2397 starter.showBackgroundActivityBlockedToast(abort, callingPackage);
2398 if (abort) {
2399 return;
2400 }
2401 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002403 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 if (task == null) {
2405 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002406 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 return;
2408 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002409 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002411 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002412 return;
2413 }
2414 ActivityOptions realOptions = options != null
2415 ? options.getOptions(mStackSupervisor)
2416 : null;
2417 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2418 false /* forceNonResizable */);
2419
2420 final ActivityRecord topActivity = task.getTopActivity();
2421 if (topActivity != null) {
2422
2423 // We are reshowing a task, use a starting window to hide the initial draw delay
2424 // so the transition can start earlier.
2425 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2426 true /* taskSwitch */, fromRecents);
2427 }
2428 } finally {
2429 Binder.restoreCallingIdentity(origId);
2430 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002431 }
2432
Ricky Waiaca8a772019-04-04 16:01:06 +01002433 /**
2434 * Return true if callingUid is system, or packageName belongs to that callingUid.
2435 */
2436 boolean isSameApp(int callingUid, @Nullable String packageName) {
2437 try {
2438 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2439 if (packageName == null) {
2440 return false;
2441 }
2442 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2443 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2444 UserHandle.getUserId(callingUid));
2445 return UserHandle.isSameApp(callingUid, uid);
2446 }
2447 } catch (RemoteException e) {
2448 // Should not happen
2449 }
2450 return true;
2451 }
2452
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002453 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2454 int callingPid, int callingUid, String name) {
2455 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2456 return true;
2457 }
2458
2459 if (getRecentTasks().isCallerRecents(sourceUid)) {
2460 return true;
2461 }
2462
2463 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2464 if (perm == PackageManager.PERMISSION_GRANTED) {
2465 return true;
2466 }
2467 if (checkAllowAppSwitchUid(sourceUid)) {
2468 return true;
2469 }
2470
2471 // If the actual IPC caller is different from the logical source, then
2472 // also see if they are allowed to control app switches.
2473 if (callingUid != -1 && callingUid != sourceUid) {
2474 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2475 if (perm == PackageManager.PERMISSION_GRANTED) {
2476 return true;
2477 }
2478 if (checkAllowAppSwitchUid(callingUid)) {
2479 return true;
2480 }
2481 }
2482
2483 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2484 return false;
2485 }
2486
2487 private boolean checkAllowAppSwitchUid(int uid) {
2488 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2489 if (types != null) {
2490 for (int i = types.size() - 1; i >= 0; i--) {
2491 if (types.valueAt(i).intValue() == uid) {
2492 return true;
2493 }
2494 }
2495 }
2496 return false;
2497 }
2498
2499 @Override
2500 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2501 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2502 "setActivityController()");
2503 synchronized (mGlobalLock) {
2504 mController = controller;
2505 mControllerIsAMonkey = imAMonkey;
2506 Watchdog.getInstance().setActivityController(controller);
2507 }
2508 }
2509
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002510 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002511 synchronized (mGlobalLock) {
2512 return mController != null && mControllerIsAMonkey;
2513 }
2514 }
2515
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002516 @Override
2517 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2518 synchronized (mGlobalLock) {
2519 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2520 }
2521 }
2522
2523 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002524 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2525 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2526 }
2527
2528 @Override
2529 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2530 @WindowConfiguration.ActivityType int ignoreActivityType,
2531 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2532 final int callingUid = Binder.getCallingUid();
2533 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2534
2535 synchronized (mGlobalLock) {
2536 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2537
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002538 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002539 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002540 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002541 ignoreWindowingMode, callingUid, allowed);
2542 }
2543
2544 return list;
2545 }
2546
2547 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002548 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2549 synchronized (mGlobalLock) {
2550 final long origId = Binder.clearCallingIdentity();
2551 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2552 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002553 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002554 }
2555 Binder.restoreCallingIdentity(origId);
2556 }
2557 }
2558
2559 @Override
2560 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002561 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 ActivityStack stack = ActivityRecord.getStackLocked(token);
2563 if (stack != null) {
2564 return stack.willActivityBeVisibleLocked(token);
2565 }
2566 return false;
2567 }
2568 }
2569
2570 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002571 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002572 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 synchronized (mGlobalLock) {
2574 final long ident = Binder.clearCallingIdentity();
2575 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002576 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002577 if (task == null) {
2578 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2579 return;
2580 }
2581
2582 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2583 + " to stackId=" + stackId + " toTop=" + toTop);
2584
Wale Ogunwaled32da472018-11-16 07:19:28 -08002585 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586 if (stack == null) {
2587 throw new IllegalStateException(
2588 "moveTaskToStack: No stack for stackId=" + stackId);
2589 }
2590 if (!stack.isActivityTypeStandardOrUndefined()) {
2591 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2592 + taskId + " to stack " + stackId);
2593 }
2594 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002595 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002596 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2597 }
2598 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2599 "moveTaskToStack");
2600 } finally {
2601 Binder.restoreCallingIdentity(ident);
2602 }
2603 }
2604 }
2605
2606 @Override
2607 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2608 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002609 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002610
2611 final long ident = Binder.clearCallingIdentity();
2612 try {
2613 synchronized (mGlobalLock) {
2614 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002615 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002616 if (stack == null) {
2617 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2618 return;
2619 }
2620 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2621 throw new IllegalArgumentException("Stack: " + stackId
2622 + " doesn't support animated resize.");
2623 }
2624 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2625 animationDuration, false /* fromFullscreen */);
2626 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002627 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 if (stack == null) {
2629 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2630 return;
2631 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002632 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002633 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2634 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2635 }
2636 }
2637 } finally {
2638 Binder.restoreCallingIdentity(ident);
2639 }
2640 }
2641
wilsonshih5c4cf522019-01-25 09:03:47 +08002642 @Override
2643 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2644 int animationDuration) {
2645 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2646
2647 final long ident = Binder.clearCallingIdentity();
2648 try {
2649 synchronized (mGlobalLock) {
2650 if (xOffset == 0 && yOffset == 0) {
2651 return;
2652 }
2653 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2654 if (stack == null) {
2655 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2656 return;
2657 }
2658 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2659 throw new IllegalArgumentException("Stack: " + stackId
2660 + " doesn't support animated resize.");
2661 }
2662 final Rect destBounds = new Rect();
2663 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002664 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002665 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2666 return;
2667 }
2668 destBounds.offset(xOffset, yOffset);
2669 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2670 animationDuration, false /* fromFullscreen */);
2671 }
2672 } finally {
2673 Binder.restoreCallingIdentity(ident);
2674 }
2675 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002676 /**
2677 * Moves the specified task to the primary-split-screen stack.
2678 *
2679 * @param taskId Id of task to move.
2680 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2681 * exist already. See
2682 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2683 * and
2684 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2685 * @param toTop If the task and stack should be moved to the top.
2686 * @param animate Whether we should play an animation for the moving the task.
2687 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2688 * stack. Pass {@code null} to use default bounds.
2689 * @param showRecents If the recents activity should be shown on the other side of the task
2690 * going into split-screen mode.
2691 */
2692 @Override
2693 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2694 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002695 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002696 "setTaskWindowingModeSplitScreenPrimary()");
2697 synchronized (mGlobalLock) {
2698 final long ident = Binder.clearCallingIdentity();
2699 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002700 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002701 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002702 if (task == null) {
2703 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2704 return false;
2705 }
2706 if (DEBUG_STACK) Slog.d(TAG_STACK,
2707 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2708 + " to createMode=" + createMode + " toTop=" + toTop);
2709 if (!task.isActivityTypeStandardOrUndefined()) {
2710 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2711 + " non-standard task " + taskId + " to split-screen windowing mode");
2712 }
2713
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002714 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002715 final int windowingMode = task.getWindowingMode();
2716 final ActivityStack stack = task.getStack();
2717 if (toTop) {
2718 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2719 }
2720 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002721 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2722 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002723 return windowingMode != task.getWindowingMode();
2724 } finally {
2725 Binder.restoreCallingIdentity(ident);
2726 }
2727 }
2728 }
2729
2730 /**
2731 * Removes stacks in the input windowing modes from the system if they are of activity type
2732 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2733 */
2734 @Override
2735 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002736 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002737 "removeStacksInWindowingModes()");
2738
2739 synchronized (mGlobalLock) {
2740 final long ident = Binder.clearCallingIdentity();
2741 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002742 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002743 } finally {
2744 Binder.restoreCallingIdentity(ident);
2745 }
2746 }
2747 }
2748
2749 @Override
2750 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002751 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002752 "removeStacksWithActivityTypes()");
2753
2754 synchronized (mGlobalLock) {
2755 final long ident = Binder.clearCallingIdentity();
2756 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002757 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002758 } finally {
2759 Binder.restoreCallingIdentity(ident);
2760 }
2761 }
2762 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763
2764 @Override
2765 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2766 int userId) {
2767 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002768 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2769 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002770 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002771 final boolean detailed = checkGetTasksPermission(
2772 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2773 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 == PackageManager.PERMISSION_GRANTED;
2775
2776 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002777 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 callingUid);
2779 }
2780 }
2781
2782 @Override
2783 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002784 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002785 long ident = Binder.clearCallingIdentity();
2786 try {
2787 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002788 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 }
2790 } finally {
2791 Binder.restoreCallingIdentity(ident);
2792 }
2793 }
2794
2795 @Override
2796 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002797 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002798 long ident = Binder.clearCallingIdentity();
2799 try {
2800 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002801 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002802 }
2803 } finally {
2804 Binder.restoreCallingIdentity(ident);
2805 }
2806 }
2807
2808 @Override
2809 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002810 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002811 final long callingUid = Binder.getCallingUid();
2812 final long origId = Binder.clearCallingIdentity();
2813 try {
2814 synchronized (mGlobalLock) {
2815 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002816 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2818 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2819 }
2820 } finally {
2821 Binder.restoreCallingIdentity(origId);
2822 }
2823 }
2824
2825 @Override
2826 public void startLockTaskModeByToken(IBinder token) {
2827 synchronized (mGlobalLock) {
2828 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2829 if (r == null) {
2830 return;
2831 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002832 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002833 }
2834 }
2835
2836 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002837 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002838 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 // This makes inner call to look as if it was initiated by system.
2840 long ident = Binder.clearCallingIdentity();
2841 try {
2842 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002843 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002844 MATCH_TASK_IN_STACKS_ONLY);
2845 if (task == null) {
2846 return;
2847 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002848
2849 // When starting lock task mode the stack must be in front and focused
2850 task.getStack().moveToFront("startSystemLockTaskMode");
2851 startLockTaskModeLocked(task, true /* isSystemCaller */);
2852 }
2853 } finally {
2854 Binder.restoreCallingIdentity(ident);
2855 }
2856 }
2857
2858 @Override
2859 public void stopLockTaskModeByToken(IBinder token) {
2860 synchronized (mGlobalLock) {
2861 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2862 if (r == null) {
2863 return;
2864 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002865 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002866 }
2867 }
2868
2869 /**
2870 * This API should be called by SystemUI only when user perform certain action to dismiss
2871 * lock task mode. We should only dismiss pinned lock task mode in this case.
2872 */
2873 @Override
2874 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002875 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2877 }
2878
2879 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2880 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2881 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2882 return;
2883 }
2884
Wale Ogunwaled32da472018-11-16 07:19:28 -08002885 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002886 if (stack == null || task != stack.topTask()) {
2887 throw new IllegalArgumentException("Invalid task, not in foreground");
2888 }
2889
2890 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2891 // system or a specific app.
2892 // * System-initiated requests will only start the pinned mode (screen pinning)
2893 // * App-initiated requests
2894 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2895 // - will start the pinned mode, otherwise
2896 final int callingUid = Binder.getCallingUid();
2897 long ident = Binder.clearCallingIdentity();
2898 try {
2899 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002900 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002901
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002902 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903 } finally {
2904 Binder.restoreCallingIdentity(ident);
2905 }
2906 }
2907
2908 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2909 final int callingUid = Binder.getCallingUid();
2910 long ident = Binder.clearCallingIdentity();
2911 try {
2912 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002913 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002914 }
2915 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2916 // task and jumping straight into a call in the case of emergency call back.
2917 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2918 if (tm != null) {
2919 tm.showInCallScreen(false);
2920 }
2921 } finally {
2922 Binder.restoreCallingIdentity(ident);
2923 }
2924 }
2925
2926 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002927 public void updateLockTaskPackages(int userId, String[] packages) {
2928 final int callingUid = Binder.getCallingUid();
2929 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2930 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2931 "updateLockTaskPackages()");
2932 }
2933 synchronized (this) {
2934 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2935 + Arrays.toString(packages));
2936 getLockTaskController().updateLockTaskPackages(userId, packages);
2937 }
2938 }
2939
2940 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002941 public boolean isInLockTaskMode() {
2942 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2943 }
2944
2945 @Override
2946 public int getLockTaskModeState() {
2947 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002948 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002949 }
2950 }
2951
2952 @Override
2953 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2954 synchronized (mGlobalLock) {
2955 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2956 if (r != null) {
2957 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002958 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002959 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002960 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 }
2962 }
2963 }
2964
2965 @Override
2966 public Bundle getActivityOptions(IBinder token) {
2967 final long origId = Binder.clearCallingIdentity();
2968 try {
2969 synchronized (mGlobalLock) {
2970 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2971 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002972 final ActivityOptions activityOptions = r.takeOptionsLocked(
2973 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002974 return activityOptions == null ? null : activityOptions.toBundle();
2975 }
2976 return null;
2977 }
2978 } finally {
2979 Binder.restoreCallingIdentity(origId);
2980 }
2981 }
2982
2983 @Override
2984 public List<IBinder> getAppTasks(String callingPackage) {
2985 int callingUid = Binder.getCallingUid();
2986 long ident = Binder.clearCallingIdentity();
2987 try {
2988 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002989 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002990 }
2991 } finally {
2992 Binder.restoreCallingIdentity(ident);
2993 }
2994 }
2995
2996 @Override
2997 public void finishVoiceTask(IVoiceInteractionSession session) {
2998 synchronized (mGlobalLock) {
2999 final long origId = Binder.clearCallingIdentity();
3000 try {
3001 // TODO: VI Consider treating local voice interactions and voice tasks
3002 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08003003 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003004 } finally {
3005 Binder.restoreCallingIdentity(origId);
3006 }
3007 }
3008
3009 }
3010
3011 @Override
3012 public boolean isTopOfTask(IBinder token) {
3013 synchronized (mGlobalLock) {
3014 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003015 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 }
3017 }
3018
3019 @Override
3020 public void notifyLaunchTaskBehindComplete(IBinder token) {
3021 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
3022 }
3023
3024 @Override
3025 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003026 mH.post(() -> {
3027 synchronized (mGlobalLock) {
3028 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003029 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003030 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003031 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003032 } catch (RemoteException e) {
3033 }
3034 }
3035 }
3036
3037 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038 }
3039
3040 /** Called from an app when assist data is ready. */
3041 @Override
3042 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3043 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003044 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 synchronized (pae) {
3046 pae.result = extras;
3047 pae.structure = structure;
3048 pae.content = content;
3049 if (referrer != null) {
3050 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3051 }
3052 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003053 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003054 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3055 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 structure.setHomeActivity(pae.isHome);
3057 }
3058 pae.haveResult = true;
3059 pae.notifyAll();
3060 if (pae.intent == null && pae.receiver == null) {
3061 // Caller is just waiting for the result.
3062 return;
3063 }
3064 }
3065 // We are now ready to launch the assist activity.
3066 IAssistDataReceiver sendReceiver = null;
3067 Bundle sendBundle = null;
3068 synchronized (mGlobalLock) {
3069 buildAssistBundleLocked(pae, extras);
3070 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003071 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 if (!exists) {
3073 // Timed out.
3074 return;
3075 }
3076
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003077 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003078 // Caller wants result sent back to them.
3079 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003080 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3081 pae.activity.getTaskRecord().taskId);
3082 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3083 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003084 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3085 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3086 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3087 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3088 }
3089 }
3090 if (sendReceiver != null) {
3091 try {
3092 sendReceiver.onHandleAssistData(sendBundle);
3093 } catch (RemoteException e) {
3094 }
3095 return;
3096 }
3097
3098 final long ident = Binder.clearCallingIdentity();
3099 try {
3100 if (TextUtils.equals(pae.intent.getAction(),
3101 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
3102 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01003103
3104 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003105 } else {
3106 pae.intent.replaceExtras(pae.extras);
3107 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3108 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3109 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003110 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111
3112 try {
3113 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3114 } catch (ActivityNotFoundException e) {
3115 Slog.w(TAG, "No activity to handle assist action.", e);
3116 }
3117 }
3118 } finally {
3119 Binder.restoreCallingIdentity(ident);
3120 }
3121 }
3122
Marvin Ramin830d4e32019-03-12 13:16:58 +01003123 /**
3124 * Workaround for historical API which starts the Assist service with a non-foreground
3125 * {@code startService()} call.
3126 */
3127 private void startVoiceInteractionServiceAsUser(
3128 Intent intent, int userHandle, String reason) {
3129 // Resolve the intent to find out which package we need to whitelist.
3130 ResolveInfo resolveInfo =
3131 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3132 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3133 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3134 return;
3135 }
3136 intent.setPackage(resolveInfo.serviceInfo.packageName);
3137
3138 // Whitelist background services temporarily.
3139 LocalServices.getService(DeviceIdleController.LocalService.class)
3140 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3141 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3142
3143 // Finally, try to start the service.
3144 try {
3145 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3146 } catch (RuntimeException e) {
3147 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3148 }
3149 }
3150
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 @Override
3152 public int addAppTask(IBinder activityToken, Intent intent,
3153 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3154 final int callingUid = Binder.getCallingUid();
3155 final long callingIdent = Binder.clearCallingIdentity();
3156
3157 try {
3158 synchronized (mGlobalLock) {
3159 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3160 if (r == null) {
3161 throw new IllegalArgumentException("Activity does not exist; token="
3162 + activityToken);
3163 }
3164 ComponentName comp = intent.getComponent();
3165 if (comp == null) {
3166 throw new IllegalArgumentException("Intent " + intent
3167 + " must specify explicit component");
3168 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003169 if (thumbnail.getWidth() != mThumbnailWidth
3170 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 throw new IllegalArgumentException("Bad thumbnail size: got "
3172 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003173 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003174 }
3175 if (intent.getSelector() != null) {
3176 intent.setSelector(null);
3177 }
3178 if (intent.getSourceBounds() != null) {
3179 intent.setSourceBounds(null);
3180 }
3181 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3182 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3183 // The caller has added this as an auto-remove task... that makes no
3184 // sense, so turn off auto-remove.
3185 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3186 }
3187 }
3188 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3189 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3190 if (ainfo.applicationInfo.uid != callingUid) {
3191 throw new SecurityException(
3192 "Can't add task for another application: target uid="
3193 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3194 }
3195
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003196 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003197 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003198 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003199 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003200 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 // The app has too many tasks already and we can't add any more
3202 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3203 return INVALID_TASK_ID;
3204 }
3205 task.lastTaskDescription.copyFrom(description);
3206
3207 // TODO: Send the thumbnail to WM to store it.
3208
3209 return task.taskId;
3210 }
3211 } finally {
3212 Binder.restoreCallingIdentity(callingIdent);
3213 }
3214 }
3215
3216 @Override
3217 public Point getAppTaskThumbnailSize() {
3218 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003219 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 }
3221 }
3222
3223 @Override
3224 public void setTaskResizeable(int taskId, int resizeableMode) {
3225 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003226 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003227 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3228 if (task == null) {
3229 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3230 return;
3231 }
3232 task.setResizeMode(resizeableMode);
3233 }
3234 }
3235
3236 @Override
3237 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003238 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003239 long ident = Binder.clearCallingIdentity();
3240 try {
3241 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003242 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003243 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003244 if (task == null) {
3245 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3246 return;
3247 }
3248 // Place the task in the right stack if it isn't there already based on
3249 // the requested bounds.
3250 // The stack transition logic is:
3251 // - a null bounds on a freeform task moves that task to fullscreen
3252 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3253 // that task to freeform
3254 // - otherwise the task is not moved
3255 ActivityStack stack = task.getStack();
3256 if (!task.getWindowConfiguration().canResizeTask()) {
3257 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3258 }
3259 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3260 stack = stack.getDisplay().getOrCreateStack(
3261 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3262 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3263 stack = stack.getDisplay().getOrCreateStack(
3264 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3265 }
3266
3267 // Reparent the task to the right stack if necessary
3268 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3269 if (stack != task.getStack()) {
3270 // Defer resume until the task is resized below
3271 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3272 DEFER_RESUME, "resizeTask");
3273 preserveWindow = false;
3274 }
3275
3276 // After reparenting (which only resizes the task to the stack bounds), resize the
3277 // task to the actual bounds provided
3278 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3279 }
3280 } finally {
3281 Binder.restoreCallingIdentity(ident);
3282 }
3283 }
3284
3285 @Override
3286 public boolean releaseActivityInstance(IBinder token) {
3287 synchronized (mGlobalLock) {
3288 final long origId = Binder.clearCallingIdentity();
3289 try {
3290 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3291 if (r == null) {
3292 return false;
3293 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003294 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295 } finally {
3296 Binder.restoreCallingIdentity(origId);
3297 }
3298 }
3299 }
3300
3301 @Override
3302 public void releaseSomeActivities(IApplicationThread appInt) {
3303 synchronized (mGlobalLock) {
3304 final long origId = Binder.clearCallingIdentity();
3305 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003306 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003307 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003308 } finally {
3309 Binder.restoreCallingIdentity(origId);
3310 }
3311 }
3312 }
3313
3314 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003315 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003316 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 != PackageManager.PERMISSION_GRANTED) {
3318 throw new SecurityException("Requires permission "
3319 + android.Manifest.permission.DEVICE_POWER);
3320 }
3321
3322 synchronized (mGlobalLock) {
3323 long ident = Binder.clearCallingIdentity();
3324 if (mKeyguardShown != keyguardShowing) {
3325 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003326 final Message msg = PooledLambda.obtainMessage(
3327 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3328 keyguardShowing);
3329 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003330 }
3331 try {
wilsonshih177261f2019-02-22 12:02:18 +08003332 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003333 } finally {
3334 Binder.restoreCallingIdentity(ident);
3335 }
3336 }
3337
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003338 mH.post(() -> {
3339 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3340 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3341 }
3342 });
3343 }
3344
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003345 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003346 mH.post(() -> {
3347 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3348 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3349 }
3350 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003351 }
3352
3353 @Override
3354 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003355 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3356 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003357
3358 final File passedIconFile = new File(filePath);
3359 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3360 passedIconFile.getName());
3361 if (!legitIconFile.getPath().equals(filePath)
3362 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3363 throw new IllegalArgumentException("Bad file path: " + filePath
3364 + " passed for userId " + userId);
3365 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003366 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003367 }
3368
3369 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003370 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003371 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3372 final ActivityOptions activityOptions = safeOptions != null
3373 ? safeOptions.getOptions(mStackSupervisor)
3374 : null;
3375 if (activityOptions == null
3376 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3377 || activityOptions.getCustomInPlaceResId() == 0) {
3378 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3379 "with valid animation");
3380 }
lumark588a3e82018-07-20 18:53:54 +08003381 // Get top display of front most application.
3382 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3383 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003384 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3385 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3386 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003387 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003388 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003389 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003390 }
3391
3392 @Override
3393 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003394 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003395 synchronized (mGlobalLock) {
3396 final long ident = Binder.clearCallingIdentity();
3397 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003398 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 if (stack == null) {
3400 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3401 return;
3402 }
3403 if (!stack.isActivityTypeStandardOrUndefined()) {
3404 throw new IllegalArgumentException(
3405 "Removing non-standard stack is not allowed.");
3406 }
3407 mStackSupervisor.removeStack(stack);
3408 } finally {
3409 Binder.restoreCallingIdentity(ident);
3410 }
3411 }
3412 }
3413
3414 @Override
3415 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003416 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003417
3418 synchronized (mGlobalLock) {
3419 final long ident = Binder.clearCallingIdentity();
3420 try {
3421 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3422 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003423 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 } finally {
3425 Binder.restoreCallingIdentity(ident);
3426 }
3427 }
3428 }
3429
3430 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003431 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 synchronized (mGlobalLock) {
3433 long ident = Binder.clearCallingIdentity();
3434 try {
3435 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3436 if (r == null) {
3437 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003438 "toggleFreeformWindowingMode: No activity record matching token="
3439 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003440 }
3441
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003442 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003443 if (stack == null) {
3444 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3445 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 }
3447
Yunfan Chend967af82019-01-17 18:30:18 +09003448 if (!stack.inFreeformWindowingMode()
3449 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3450 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3451 + "toggle between fullscreen and freeform.");
3452 }
3453
3454 if (stack.inFreeformWindowingMode()) {
3455 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003456 } else if (stack.getParent().inFreeformWindowingMode()) {
3457 // If the window is on a freeform display, set it to undefined. It will be
3458 // resolved to freeform and it can adjust windowing mode when the display mode
3459 // changes in runtime.
3460 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003461 } else {
3462 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3463 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 } finally {
3465 Binder.restoreCallingIdentity(ident);
3466 }
3467 }
3468 }
3469
3470 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3471 @Override
3472 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003473 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003474 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003475 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003476 }
3477
3478 /** Unregister a task stack listener so that it stops receiving callbacks. */
3479 @Override
3480 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003481 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003482 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003483 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003484 }
3485
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003486 @Override
3487 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3488 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3489 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3490 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3491 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3492 }
3493
3494 @Override
3495 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3496 IBinder activityToken, int flags) {
3497 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3498 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3499 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3500 }
3501
3502 @Override
3503 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3504 Bundle args) {
3505 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3506 true /* focused */, true /* newSessionId */, userHandle, args,
3507 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3508 }
3509
3510 @Override
3511 public Bundle getAssistContextExtras(int requestType) {
3512 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3513 null, null, true /* focused */, true /* newSessionId */,
3514 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3515 if (pae == null) {
3516 return null;
3517 }
3518 synchronized (pae) {
3519 while (!pae.haveResult) {
3520 try {
3521 pae.wait();
3522 } catch (InterruptedException e) {
3523 }
3524 }
3525 }
3526 synchronized (mGlobalLock) {
3527 buildAssistBundleLocked(pae, pae.result);
3528 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003529 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003530 }
3531 return pae.extras;
3532 }
3533
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003534 /**
3535 * Binder IPC calls go through the public entry point.
3536 * This can be called with or without the global lock held.
3537 */
3538 private static int checkCallingPermission(String permission) {
3539 return checkPermission(
3540 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3541 }
3542
3543 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003544 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003545 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3546 mAmInternal.enforceCallingPermission(permission, func);
3547 }
3548 }
3549
3550 @VisibleForTesting
3551 int checkGetTasksPermission(String permission, int pid, int uid) {
3552 return checkPermission(permission, pid, uid);
3553 }
3554
3555 static int checkPermission(String permission, int pid, int uid) {
3556 if (permission == null) {
3557 return PackageManager.PERMISSION_DENIED;
3558 }
3559 return checkComponentPermission(permission, pid, uid, -1, true);
3560 }
3561
Wale Ogunwale214f3482018-10-04 11:00:47 -07003562 public static int checkComponentPermission(String permission, int pid, int uid,
3563 int owningUid, boolean exported) {
3564 return ActivityManagerService.checkComponentPermission(
3565 permission, pid, uid, owningUid, exported);
3566 }
3567
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003568 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3569 if (getRecentTasks().isCallerRecents(callingUid)) {
3570 // Always allow the recents component to get tasks
3571 return true;
3572 }
3573
3574 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3575 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3576 if (!allowed) {
3577 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3578 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3579 // Temporary compatibility: some existing apps on the system image may
3580 // still be requesting the old permission and not switched to the new
3581 // one; if so, we'll still allow them full access. This means we need
3582 // to see if they are holding the old permission and are a system app.
3583 try {
3584 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3585 allowed = true;
3586 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3587 + " is using old GET_TASKS but privileged; allowing");
3588 }
3589 } catch (RemoteException e) {
3590 }
3591 }
3592 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3593 + " does not hold REAL_GET_TASKS; limiting output");
3594 }
3595 return allowed;
3596 }
3597
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003598 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3599 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3600 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3601 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003602 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003603 "enqueueAssistContext()");
3604
3605 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003606 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 if (activity == null) {
3608 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3609 return null;
3610 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003611 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003612 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3613 return null;
3614 }
3615 if (focused) {
3616 if (activityToken != null) {
3617 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3618 if (activity != caller) {
3619 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3620 + " is not current top " + activity);
3621 return null;
3622 }
3623 }
3624 } else {
3625 activity = ActivityRecord.forTokenLocked(activityToken);
3626 if (activity == null) {
3627 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3628 + " couldn't be found");
3629 return null;
3630 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003631 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3633 return null;
3634 }
3635 }
3636
3637 PendingAssistExtras pae;
3638 Bundle extras = new Bundle();
3639 if (args != null) {
3640 extras.putAll(args);
3641 }
3642 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003643 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003644
3645 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3646 userHandle);
3647 pae.isHome = activity.isActivityTypeHome();
3648
3649 // Increment the sessionId if necessary
3650 if (newSessionId) {
3651 mViSessionId++;
3652 }
3653 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003654 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3655 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003656 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003657 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003658 } catch (RemoteException e) {
3659 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3660 return null;
3661 }
3662 return pae;
3663 }
3664 }
3665
3666 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3667 if (result != null) {
3668 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3669 }
3670 if (pae.hint != null) {
3671 pae.extras.putBoolean(pae.hint, true);
3672 }
3673 }
3674
3675 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3676 IAssistDataReceiver receiver;
3677 synchronized (mGlobalLock) {
3678 mPendingAssistExtras.remove(pae);
3679 receiver = pae.receiver;
3680 }
3681 if (receiver != null) {
3682 // Caller wants result sent back to them.
3683 Bundle sendBundle = new Bundle();
3684 // At least return the receiver extras
3685 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3686 try {
3687 pae.receiver.onHandleAssistData(sendBundle);
3688 } catch (RemoteException e) {
3689 }
3690 }
3691 }
3692
3693 public class PendingAssistExtras extends Binder implements Runnable {
3694 public final ActivityRecord activity;
3695 public boolean isHome;
3696 public final Bundle extras;
3697 public final Intent intent;
3698 public final String hint;
3699 public final IAssistDataReceiver receiver;
3700 public final int userHandle;
3701 public boolean haveResult = false;
3702 public Bundle result = null;
3703 public AssistStructure structure = null;
3704 public AssistContent content = null;
3705 public Bundle receiverExtras;
3706
3707 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3708 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3709 int _userHandle) {
3710 activity = _activity;
3711 extras = _extras;
3712 intent = _intent;
3713 hint = _hint;
3714 receiver = _receiver;
3715 receiverExtras = _receiverExtras;
3716 userHandle = _userHandle;
3717 }
3718
3719 @Override
3720 public void run() {
3721 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3722 synchronized (this) {
3723 haveResult = true;
3724 notifyAll();
3725 }
3726 pendingAssistExtrasTimedOut(this);
3727 }
3728 }
3729
3730 @Override
3731 public boolean isAssistDataAllowedOnCurrentActivity() {
3732 int userId;
3733 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003734 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003735 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3736 return false;
3737 }
3738
3739 final ActivityRecord activity = focusedStack.getTopActivity();
3740 if (activity == null) {
3741 return false;
3742 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003743 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003744 }
3745 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3746 }
3747
3748 @Override
3749 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3750 long ident = Binder.clearCallingIdentity();
3751 try {
3752 synchronized (mGlobalLock) {
3753 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003754 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003755 if (top != caller) {
3756 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3757 + " is not current top " + top);
3758 return false;
3759 }
3760 if (!top.nowVisible) {
3761 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3762 + " is not visible");
3763 return false;
3764 }
3765 }
3766 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3767 token);
3768 } finally {
3769 Binder.restoreCallingIdentity(ident);
3770 }
3771 }
3772
3773 @Override
3774 public boolean isRootVoiceInteraction(IBinder token) {
3775 synchronized (mGlobalLock) {
3776 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3777 if (r == null) {
3778 return false;
3779 }
3780 return r.rootVoiceInteraction;
3781 }
3782 }
3783
Wale Ogunwalef6733932018-06-27 05:14:34 -07003784 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3785 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3786 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3787 if (activityToCallback == null) return;
3788 activityToCallback.setVoiceSessionLocked(voiceSession);
3789
3790 // Inform the activity
3791 try {
3792 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3793 voiceInteractor);
3794 long token = Binder.clearCallingIdentity();
3795 try {
3796 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3797 } finally {
3798 Binder.restoreCallingIdentity(token);
3799 }
3800 // TODO: VI Should we cache the activity so that it's easier to find later
3801 // rather than scan through all the stacks and activities?
3802 } catch (RemoteException re) {
3803 activityToCallback.clearVoiceSessionLocked();
3804 // TODO: VI Should this terminate the voice session?
3805 }
3806 }
3807
3808 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3809 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3810 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3811 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3812 boolean wasRunningVoice = mRunningVoice != null;
3813 mRunningVoice = session;
3814 if (!wasRunningVoice) {
3815 mVoiceWakeLock.acquire();
3816 updateSleepIfNeededLocked();
3817 }
3818 }
3819 }
3820
3821 void finishRunningVoiceLocked() {
3822 if (mRunningVoice != null) {
3823 mRunningVoice = null;
3824 mVoiceWakeLock.release();
3825 updateSleepIfNeededLocked();
3826 }
3827 }
3828
3829 @Override
3830 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3831 synchronized (mGlobalLock) {
3832 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3833 if (keepAwake) {
3834 mVoiceWakeLock.acquire();
3835 } else {
3836 mVoiceWakeLock.release();
3837 }
3838 }
3839 }
3840 }
3841
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003842 @Override
3843 public ComponentName getActivityClassForToken(IBinder token) {
3844 synchronized (mGlobalLock) {
3845 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3846 if (r == null) {
3847 return null;
3848 }
3849 return r.intent.getComponent();
3850 }
3851 }
3852
3853 @Override
3854 public String getPackageForToken(IBinder token) {
3855 synchronized (mGlobalLock) {
3856 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3857 if (r == null) {
3858 return null;
3859 }
3860 return r.packageName;
3861 }
3862 }
3863
3864 @Override
3865 public void showLockTaskEscapeMessage(IBinder token) {
3866 synchronized (mGlobalLock) {
3867 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3868 if (r == null) {
3869 return;
3870 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003871 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003872 }
3873 }
3874
3875 @Override
3876 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003877 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 final long token = Binder.clearCallingIdentity();
3879 try {
3880 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003881 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003882 }
3883 } finally {
3884 Binder.restoreCallingIdentity(token);
3885 }
3886 }
3887
3888 /**
3889 * Try to place task to provided position. The final position might be different depending on
3890 * current user and stacks state. The task will be moved to target stack if it's currently in
3891 * different stack.
3892 */
3893 @Override
3894 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003895 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003896 synchronized (mGlobalLock) {
3897 long ident = Binder.clearCallingIdentity();
3898 try {
3899 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3900 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003901 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003902 if (task == null) {
3903 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3904 + taskId);
3905 }
3906
Wale Ogunwaled32da472018-11-16 07:19:28 -08003907 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908
3909 if (stack == null) {
3910 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3911 + stackId);
3912 }
3913 if (!stack.isActivityTypeStandardOrUndefined()) {
3914 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3915 + " the position of task " + taskId + " in/to non-standard stack");
3916 }
3917
3918 // TODO: Have the callers of this API call a separate reparent method if that is
3919 // what they intended to do vs. having this method also do reparenting.
3920 if (task.getStack() == stack) {
3921 // Change position in current stack.
3922 stack.positionChildAt(task, position);
3923 } else {
3924 // Reparent to new stack.
3925 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3926 !DEFER_RESUME, "positionTaskInStack");
3927 }
3928 } finally {
3929 Binder.restoreCallingIdentity(ident);
3930 }
3931 }
3932 }
3933
3934 @Override
3935 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3936 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3937 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3938 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3939 synchronized (mGlobalLock) {
3940 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3941 if (record == null) {
3942 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3943 + "found for: " + token);
3944 }
3945 record.setSizeConfigurations(horizontalSizeConfiguration,
3946 verticalSizeConfigurations, smallestSizeConfigurations);
3947 }
3948 }
3949
3950 /**
3951 * Dismisses split-screen multi-window mode.
3952 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3953 */
3954 @Override
3955 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003956 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003957 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3958 final long ident = Binder.clearCallingIdentity();
3959 try {
3960 synchronized (mGlobalLock) {
3961 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003962 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003963 if (stack == null) {
3964 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3965 return;
3966 }
3967
3968 if (toTop) {
3969 // Caller wants the current split-screen primary stack to be the top stack after
3970 // it goes fullscreen, so move it to the front.
3971 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003972 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 // In this case the current split-screen primary stack shouldn't be the top
3974 // stack after it goes fullscreen, but it current has focus, so we move the
3975 // focus to the top-most split-screen secondary stack next to it.
3976 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3977 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3978 if (otherStack != null) {
3979 otherStack.moveToFront("dismissSplitScreenMode_other");
3980 }
3981 }
3982
Evan Rosky10475742018-09-05 19:02:48 -07003983 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984 }
3985 } finally {
3986 Binder.restoreCallingIdentity(ident);
3987 }
3988 }
3989
3990 /**
3991 * Dismisses Pip
3992 * @param animate True if the dismissal should be animated.
3993 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3994 * default animation duration should be used.
3995 */
3996 @Override
3997 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003998 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003999 final long ident = Binder.clearCallingIdentity();
4000 try {
4001 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08004002 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08004003 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004004 if (stack == null) {
4005 Slog.w(TAG, "dismissPip: pinned stack not found.");
4006 return;
4007 }
4008 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
4009 throw new IllegalArgumentException("Stack: " + stack
4010 + " doesn't support animated resize.");
4011 }
4012 if (animate) {
4013 stack.animateResizePinnedStack(null /* sourceHintBounds */,
4014 null /* destBounds */, animationDuration, false /* fromFullscreen */);
4015 } else {
4016 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
4017 }
4018 }
4019 } finally {
4020 Binder.restoreCallingIdentity(ident);
4021 }
4022 }
4023
4024 @Override
4025 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004026 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 synchronized (mGlobalLock) {
4028 mSuppressResizeConfigChanges = suppress;
4029 }
4030 }
4031
4032 /**
4033 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
4034 * animated the stack to the fullscreen, but can also be called if we are relaunching an
4035 * activity and clearing the task at the same time.
4036 */
4037 @Override
4038 // TODO: API should just be about changing windowing modes...
4039 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004040 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004041 "moveTasksToFullscreenStack()");
4042 synchronized (mGlobalLock) {
4043 final long origId = Binder.clearCallingIdentity();
4044 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004045 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 if (stack != null){
4047 if (!stack.isActivityTypeStandardOrUndefined()) {
4048 throw new IllegalArgumentException(
4049 "You can't move tasks from non-standard stacks.");
4050 }
4051 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4052 }
4053 } finally {
4054 Binder.restoreCallingIdentity(origId);
4055 }
4056 }
4057 }
4058
4059 /**
4060 * Moves the top activity in the input stackId to the pinned stack.
4061 *
4062 * @param stackId Id of stack to move the top activity to pinned stack.
4063 * @param bounds Bounds to use for pinned stack.
4064 *
4065 * @return True if the top activity of the input stack was successfully moved to the pinned
4066 * stack.
4067 */
4068 @Override
4069 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004070 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004071 "moveTopActivityToPinnedStack()");
4072 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004073 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4075 + "Device doesn't support picture-in-picture mode");
4076 }
4077
4078 long ident = Binder.clearCallingIdentity();
4079 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004080 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 } finally {
4082 Binder.restoreCallingIdentity(ident);
4083 }
4084 }
4085 }
4086
4087 @Override
4088 public boolean isInMultiWindowMode(IBinder token) {
4089 final long origId = Binder.clearCallingIdentity();
4090 try {
4091 synchronized (mGlobalLock) {
4092 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4093 if (r == null) {
4094 return false;
4095 }
4096 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4097 return r.inMultiWindowMode();
4098 }
4099 } finally {
4100 Binder.restoreCallingIdentity(origId);
4101 }
4102 }
4103
4104 @Override
4105 public boolean isInPictureInPictureMode(IBinder token) {
4106 final long origId = Binder.clearCallingIdentity();
4107 try {
4108 synchronized (mGlobalLock) {
4109 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4110 }
4111 } finally {
4112 Binder.restoreCallingIdentity(origId);
4113 }
4114 }
4115
4116 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004117 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4118 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 return false;
4120 }
4121
4122 // If we are animating to fullscreen then we have already dispatched the PIP mode
4123 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004124 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4125 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004126 }
4127
4128 @Override
4129 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4130 final long origId = Binder.clearCallingIdentity();
4131 try {
4132 synchronized (mGlobalLock) {
4133 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4134 "enterPictureInPictureMode", token, params);
4135
4136 // If the activity is already in picture in picture mode, then just return early
4137 if (isInPictureInPictureMode(r)) {
4138 return true;
4139 }
4140
4141 // Activity supports picture-in-picture, now check that we can enter PiP at this
4142 // point, if it is
4143 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4144 false /* beforeStopping */)) {
4145 return false;
4146 }
4147
4148 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004149 synchronized (mGlobalLock) {
4150 // Only update the saved args from the args that are set
4151 r.pictureInPictureArgs.copyOnlySet(params);
4152 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4153 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4154 // Adjust the source bounds by the insets for the transition down
4155 final Rect sourceBounds = new Rect(
4156 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004157 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004158 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004159 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004160 stack.setPictureInPictureAspectRatio(aspectRatio);
4161 stack.setPictureInPictureActions(actions);
4162 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4163 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4164 logPictureInPictureArgs(params);
4165 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 };
4167
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004168 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004169 // If the keyguard is showing or occluded, then try and dismiss it before
4170 // entering picture-in-picture (this will prompt the user to authenticate if the
4171 // device is currently locked).
4172 dismissKeyguard(token, new KeyguardDismissCallback() {
4173 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004174 public void onDismissSucceeded() {
4175 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004176 }
4177 }, null /* message */);
4178 } else {
4179 // Enter picture in picture immediately otherwise
4180 enterPipRunnable.run();
4181 }
4182 return true;
4183 }
4184 } finally {
4185 Binder.restoreCallingIdentity(origId);
4186 }
4187 }
4188
4189 @Override
4190 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4191 final long origId = Binder.clearCallingIdentity();
4192 try {
4193 synchronized (mGlobalLock) {
4194 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4195 "setPictureInPictureParams", token, params);
4196
4197 // Only update the saved args from the args that are set
4198 r.pictureInPictureArgs.copyOnlySet(params);
4199 if (r.inPinnedWindowingMode()) {
4200 // If the activity is already in picture-in-picture, update the pinned stack now
4201 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4202 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004203 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004204 if (!stack.isAnimatingBoundsToFullscreen()) {
4205 stack.setPictureInPictureAspectRatio(
4206 r.pictureInPictureArgs.getAspectRatio());
4207 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4208 }
4209 }
4210 logPictureInPictureArgs(params);
4211 }
4212 } finally {
4213 Binder.restoreCallingIdentity(origId);
4214 }
4215 }
4216
4217 @Override
4218 public int getMaxNumPictureInPictureActions(IBinder token) {
4219 // Currently, this is a static constant, but later, we may change this to be dependent on
4220 // the context of the activity
4221 return 3;
4222 }
4223
4224 private void logPictureInPictureArgs(PictureInPictureParams params) {
4225 if (params.hasSetActions()) {
4226 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4227 params.getActions().size());
4228 }
4229 if (params.hasSetAspectRatio()) {
4230 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4231 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4232 MetricsLogger.action(lm);
4233 }
4234 }
4235
4236 /**
4237 * Checks the state of the system and the activity associated with the given {@param token} to
4238 * verify that picture-in-picture is supported for that activity.
4239 *
4240 * @return the activity record for the given {@param token} if all the checks pass.
4241 */
4242 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4243 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 throw new IllegalStateException(caller
4246 + ": Device doesn't support picture-in-picture mode.");
4247 }
4248
4249 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4250 if (r == null) {
4251 throw new IllegalStateException(caller
4252 + ": Can't find activity for token=" + token);
4253 }
4254
4255 if (!r.supportsPictureInPicture()) {
4256 throw new IllegalStateException(caller
4257 + ": Current activity does not support picture-in-picture.");
4258 }
4259
4260 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004261 && !mWindowManager.isValidPictureInPictureAspectRatio(
4262 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 final float minAspectRatio = mContext.getResources().getFloat(
4264 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4265 final float maxAspectRatio = mContext.getResources().getFloat(
4266 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4267 throw new IllegalArgumentException(String.format(caller
4268 + ": Aspect ratio is too extreme (must be between %f and %f).",
4269 minAspectRatio, maxAspectRatio));
4270 }
4271
4272 // Truncate the number of actions if necessary
4273 params.truncateActions(getMaxNumPictureInPictureActions(token));
4274
4275 return r;
4276 }
4277
4278 @Override
4279 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004280 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 synchronized (mGlobalLock) {
4282 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4283 if (r == null) {
4284 throw new IllegalArgumentException("Activity does not exist; token="
4285 + activityToken);
4286 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004287 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004288 }
4289 }
4290
4291 @Override
4292 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4293 Rect tempDockedTaskInsetBounds,
4294 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004295 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 long ident = Binder.clearCallingIdentity();
4297 try {
4298 synchronized (mGlobalLock) {
4299 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4300 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4301 PRESERVE_WINDOWS);
4302 }
4303 } finally {
4304 Binder.restoreCallingIdentity(ident);
4305 }
4306 }
4307
4308 @Override
4309 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 final long ident = Binder.clearCallingIdentity();
4312 try {
4313 synchronized (mGlobalLock) {
4314 mStackSupervisor.setSplitScreenResizing(resizing);
4315 }
4316 } finally {
4317 Binder.restoreCallingIdentity(ident);
4318 }
4319 }
4320
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004321 /**
4322 * Check that we have the features required for VR-related API calls, and throw an exception if
4323 * not.
4324 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004325 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004326 if (!mContext.getPackageManager().hasSystemFeature(
4327 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4328 throw new UnsupportedOperationException("VR mode not supported on this device!");
4329 }
4330 }
4331
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004332 @Override
4333 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004334 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004335
4336 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4337
4338 ActivityRecord r;
4339 synchronized (mGlobalLock) {
4340 r = ActivityRecord.isInStackLocked(token);
4341 }
4342
4343 if (r == null) {
4344 throw new IllegalArgumentException();
4345 }
4346
4347 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004348 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004349 VrManagerInternal.NO_ERROR) {
4350 return err;
4351 }
4352
4353 // Clear the binder calling uid since this path may call moveToTask().
4354 final long callingId = Binder.clearCallingIdentity();
4355 try {
4356 synchronized (mGlobalLock) {
4357 r.requestedVrComponent = (enabled) ? packageName : null;
4358
4359 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004360 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004361 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004362 }
4363 return 0;
4364 }
4365 } finally {
4366 Binder.restoreCallingIdentity(callingId);
4367 }
4368 }
4369
4370 @Override
4371 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4372 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4373 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004374 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004375 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4376 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4377 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004378 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 || activity.voiceSession != null) {
4380 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4381 return;
4382 }
4383 if (activity.pendingVoiceInteractionStart) {
4384 Slog.w(TAG, "Pending start of voice interaction already.");
4385 return;
4386 }
4387 activity.pendingVoiceInteractionStart = true;
4388 }
4389 LocalServices.getService(VoiceInteractionManagerInternal.class)
4390 .startLocalVoiceInteraction(callingActivity, options);
4391 }
4392
4393 @Override
4394 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4395 LocalServices.getService(VoiceInteractionManagerInternal.class)
4396 .stopLocalVoiceInteraction(callingActivity);
4397 }
4398
4399 @Override
4400 public boolean supportsLocalVoiceInteraction() {
4401 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4402 .supportsLocalVoiceInteraction();
4403 }
4404
4405 /** Notifies all listeners when the pinned stack animation starts. */
4406 @Override
4407 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004408 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004409 }
4410
4411 /** Notifies all listeners when the pinned stack animation ends. */
4412 @Override
4413 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004414 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004415 }
4416
4417 @Override
4418 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004419 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004420 final long ident = Binder.clearCallingIdentity();
4421 try {
4422 synchronized (mGlobalLock) {
4423 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4424 }
4425 } finally {
4426 Binder.restoreCallingIdentity(ident);
4427 }
4428 }
4429
4430 @Override
4431 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004432 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004433
4434 synchronized (mGlobalLock) {
4435 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004436 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004437 // Call might come when display is not yet added or has already been removed.
4438 if (DEBUG_CONFIGURATION) {
4439 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4440 + displayId);
4441 }
4442 return false;
4443 }
4444
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004445 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004447 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004448 }
4449
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004450 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004451 final Message msg = PooledLambda.obtainMessage(
4452 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4453 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004454 }
4455
4456 final long origId = Binder.clearCallingIdentity();
4457 try {
4458 if (values != null) {
4459 Settings.System.clearConfiguration(values);
4460 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004461 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004462 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4463 return mTmpUpdateConfigurationResult.changes != 0;
4464 } finally {
4465 Binder.restoreCallingIdentity(origId);
4466 }
4467 }
4468 }
4469
4470 @Override
4471 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004472 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004473
4474 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004475 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004476 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004477 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004478 }
4479
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004480 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004481 final Message msg = PooledLambda.obtainMessage(
4482 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4483 DEFAULT_DISPLAY);
4484 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 }
4486
4487 final long origId = Binder.clearCallingIdentity();
4488 try {
4489 if (values != null) {
4490 Settings.System.clearConfiguration(values);
4491 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004492 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004493 UserHandle.USER_NULL, false /* deferResume */,
4494 mTmpUpdateConfigurationResult);
4495 return mTmpUpdateConfigurationResult.changes != 0;
4496 } finally {
4497 Binder.restoreCallingIdentity(origId);
4498 }
4499 }
4500 }
4501
4502 @Override
4503 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4504 CharSequence message) {
4505 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004506 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004507 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4508 }
4509 final long callingId = Binder.clearCallingIdentity();
4510 try {
4511 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004512 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004513 }
4514 } finally {
4515 Binder.restoreCallingIdentity(callingId);
4516 }
4517 }
4518
4519 @Override
4520 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004521 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004522 "cancelTaskWindowTransition()");
4523 final long ident = Binder.clearCallingIdentity();
4524 try {
4525 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004526 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004527 MATCH_TASK_IN_STACKS_ONLY);
4528 if (task == null) {
4529 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4530 return;
4531 }
4532 task.cancelWindowTransition();
4533 }
4534 } finally {
4535 Binder.restoreCallingIdentity(ident);
4536 }
4537 }
4538
4539 @Override
4540 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004541 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004542 final long ident = Binder.clearCallingIdentity();
4543 try {
4544 final TaskRecord task;
4545 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004546 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004547 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4548 if (task == null) {
4549 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4550 return null;
4551 }
4552 }
4553 // Don't call this while holding the lock as this operation might hit the disk.
4554 return task.getSnapshot(reducedResolution);
4555 } finally {
4556 Binder.restoreCallingIdentity(ident);
4557 }
4558 }
4559
4560 @Override
4561 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4562 synchronized (mGlobalLock) {
4563 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4564 if (r == null) {
4565 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4566 + token);
4567 return;
4568 }
4569 final long origId = Binder.clearCallingIdentity();
4570 try {
4571 r.setDisablePreviewScreenshots(disable);
4572 } finally {
4573 Binder.restoreCallingIdentity(origId);
4574 }
4575 }
4576 }
4577
4578 /** Return the user id of the last resumed activity. */
4579 @Override
4580 public @UserIdInt
4581 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004583 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4584 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004585 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004586 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004587 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004588 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004589 }
4590 }
4591
4592 @Override
4593 public void updateLockTaskFeatures(int userId, int flags) {
4594 final int callingUid = Binder.getCallingUid();
4595 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004596 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004597 "updateLockTaskFeatures()");
4598 }
4599 synchronized (mGlobalLock) {
4600 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4601 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004602 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004603 }
4604 }
4605
4606 @Override
4607 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4608 synchronized (mGlobalLock) {
4609 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4610 if (r == null) {
4611 return;
4612 }
4613 final long origId = Binder.clearCallingIdentity();
4614 try {
4615 r.setShowWhenLocked(showWhenLocked);
4616 } finally {
4617 Binder.restoreCallingIdentity(origId);
4618 }
4619 }
4620 }
4621
4622 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004623 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4624 synchronized (mGlobalLock) {
4625 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4626 if (r == null) {
4627 return;
4628 }
4629 final long origId = Binder.clearCallingIdentity();
4630 try {
4631 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4632 } finally {
4633 Binder.restoreCallingIdentity(origId);
4634 }
4635 }
4636 }
4637
4638 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004639 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4640 synchronized (mGlobalLock) {
4641 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4642 if (r == null) {
4643 return;
4644 }
4645 final long origId = Binder.clearCallingIdentity();
4646 try {
4647 r.setTurnScreenOn(turnScreenOn);
4648 } finally {
4649 Binder.restoreCallingIdentity(origId);
4650 }
4651 }
4652 }
4653
4654 @Override
4655 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004656 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004657 "registerRemoteAnimations");
4658 definition.setCallingPid(Binder.getCallingPid());
4659 synchronized (mGlobalLock) {
4660 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4661 if (r == null) {
4662 return;
4663 }
4664 final long origId = Binder.clearCallingIdentity();
4665 try {
4666 r.registerRemoteAnimations(definition);
4667 } finally {
4668 Binder.restoreCallingIdentity(origId);
4669 }
4670 }
4671 }
4672
4673 @Override
4674 public void registerRemoteAnimationForNextActivityStart(String packageName,
4675 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004676 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004677 "registerRemoteAnimationForNextActivityStart");
4678 adapter.setCallingPid(Binder.getCallingPid());
4679 synchronized (mGlobalLock) {
4680 final long origId = Binder.clearCallingIdentity();
4681 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004682 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004683 packageName, adapter);
4684 } finally {
4685 Binder.restoreCallingIdentity(origId);
4686 }
4687 }
4688 }
4689
Evan Rosky966759f2019-01-15 10:33:58 -08004690 @Override
4691 public void registerRemoteAnimationsForDisplay(int displayId,
4692 RemoteAnimationDefinition definition) {
4693 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4694 "registerRemoteAnimations");
4695 definition.setCallingPid(Binder.getCallingPid());
4696 synchronized (mGlobalLock) {
4697 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4698 if (display == null) {
4699 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4700 return;
4701 }
4702 final long origId = Binder.clearCallingIdentity();
4703 try {
4704 display.mDisplayContent.registerRemoteAnimations(definition);
4705 } finally {
4706 Binder.restoreCallingIdentity(origId);
4707 }
4708 }
4709 }
4710
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004711 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4712 @Override
4713 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4714 synchronized (mGlobalLock) {
4715 final long origId = Binder.clearCallingIdentity();
4716 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004717 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004718 } finally {
4719 Binder.restoreCallingIdentity(origId);
4720 }
4721 }
4722 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004723
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004724 @Override
4725 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004726 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004727 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004728 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004729 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004730 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004731 }
4732 }
4733
4734 @Override
4735 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004736 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004737 != PERMISSION_GRANTED) {
4738 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4739 + Binder.getCallingPid()
4740 + ", uid=" + Binder.getCallingUid()
4741 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4742 Slog.w(TAG, msg);
4743 throw new SecurityException(msg);
4744 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004745 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004746 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004747 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004748 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004749 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004750 }
4751 }
4752
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004753 @Override
4754 public void stopAppSwitches() {
4755 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4756 synchronized (mGlobalLock) {
4757 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004758 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004759 mDidAppSwitch = false;
4760 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4761 }
4762 }
4763
4764 @Override
4765 public void resumeAppSwitches() {
4766 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4767 synchronized (mGlobalLock) {
4768 // Note that we don't execute any pending app switches... we will
4769 // let those wait until either the timeout, or the next start
4770 // activity request.
4771 mAppSwitchesAllowedTime = 0;
4772 }
4773 }
4774
Ricky Wai906af482019-06-03 17:25:28 +01004775 long getLastStopAppSwitchesTime() {
4776 return mLastStopAppSwitchesTime;
4777 }
4778
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004779 void onStartActivitySetDidAppSwitch() {
4780 if (mDidAppSwitch) {
4781 // This is the second allowed switch since we stopped switches, so now just generally
4782 // allow switches. Use case:
4783 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4784 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4785 // anyone to switch again).
4786 mAppSwitchesAllowedTime = 0;
4787 } else {
4788 mDidAppSwitch = true;
4789 }
4790 }
4791
4792 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004793 boolean shouldDisableNonVrUiLocked() {
4794 return mVrController.shouldDisableNonVrUiLocked();
4795 }
4796
Wale Ogunwale53783742018-09-16 10:21:51 -07004797 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004798 // VR apps are expected to run in a main display. If an app is turning on VR for
4799 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4800 // fullscreen stack before enabling VR Mode.
4801 // TODO: The goal of this code is to keep the VR app on the main display. When the
4802 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4803 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4804 // option would be a better choice here.
4805 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4806 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4807 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004808 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004809 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004810 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004811 }
4812 mH.post(() -> {
4813 if (!mVrController.onVrModeChanged(r)) {
4814 return;
4815 }
4816 synchronized (mGlobalLock) {
4817 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4818 mWindowManager.disableNonVrUi(disableNonVrUi);
4819 if (disableNonVrUi) {
4820 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4821 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004822 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004823 }
4824 }
4825 });
4826 }
4827
Wale Ogunwale53783742018-09-16 10:21:51 -07004828 @Override
4829 public int getPackageScreenCompatMode(String packageName) {
4830 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4831 synchronized (mGlobalLock) {
4832 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4833 }
4834 }
4835
4836 @Override
4837 public void setPackageScreenCompatMode(String packageName, int mode) {
4838 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4839 "setPackageScreenCompatMode");
4840 synchronized (mGlobalLock) {
4841 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4842 }
4843 }
4844
4845 @Override
4846 public boolean getPackageAskScreenCompat(String packageName) {
4847 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4848 synchronized (mGlobalLock) {
4849 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4850 }
4851 }
4852
4853 @Override
4854 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4855 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4856 "setPackageAskScreenCompat");
4857 synchronized (mGlobalLock) {
4858 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4859 }
4860 }
4861
Wale Ogunwale64258362018-10-16 15:13:37 -07004862 public static String relaunchReasonToString(int relaunchReason) {
4863 switch (relaunchReason) {
4864 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4865 return "window_resize";
4866 case RELAUNCH_REASON_FREE_RESIZE:
4867 return "free_resize";
4868 default:
4869 return null;
4870 }
4871 }
4872
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004873 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004874 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004875 }
4876
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004877 /** Pokes the task persister. */
4878 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4879 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4880 }
4881
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004882 boolean isKeyguardLocked() {
4883 return mKeyguardController.isKeyguardLocked();
4884 }
4885
Garfield Tan01548632018-11-27 10:15:48 -08004886 /**
4887 * Clears launch params for the given package.
4888 * @param packageNames the names of the packages of which the launch params are to be cleared
4889 */
4890 @Override
4891 public void clearLaunchParamsForPackages(List<String> packageNames) {
4892 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4893 "clearLaunchParamsForPackages");
4894 synchronized (mGlobalLock) {
4895 for (int i = 0; i < packageNames.size(); ++i) {
4896 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4897 }
4898 }
4899 }
4900
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004901 /**
4902 * Makes the display with the given id a single task instance display. I.e the display can only
4903 * contain one task.
4904 */
4905 @Override
4906 public void setDisplayToSingleTaskInstance(int displayId) {
4907 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4908 "setDisplayToSingleTaskInstance");
4909 final long origId = Binder.clearCallingIdentity();
4910 try {
4911 final ActivityDisplay display =
4912 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4913 if (display != null) {
4914 display.setDisplayToSingleTaskInstance();
4915 }
4916 } finally {
4917 Binder.restoreCallingIdentity(origId);
4918 }
4919 }
4920
Wale Ogunwale31913b52018-10-13 08:29:31 -07004921 void dumpLastANRLocked(PrintWriter pw) {
4922 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4923 if (mLastANRState == null) {
4924 pw.println(" <no ANR has occurred since boot>");
4925 } else {
4926 pw.println(mLastANRState);
4927 }
4928 }
4929
4930 void dumpLastANRTracesLocked(PrintWriter pw) {
4931 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4932
4933 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4934 if (ArrayUtils.isEmpty(files)) {
4935 pw.println(" <no ANR has occurred since boot>");
4936 return;
4937 }
4938 // Find the latest file.
4939 File latest = null;
4940 for (File f : files) {
4941 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4942 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004943 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004944 }
4945 pw.print("File: ");
4946 pw.print(latest.getName());
4947 pw.println();
4948 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4949 String line;
4950 while ((line = in.readLine()) != null) {
4951 pw.println(line);
4952 }
4953 } catch (IOException e) {
4954 pw.print("Unable to read: ");
4955 pw.print(e);
4956 pw.println();
4957 }
4958 }
4959
4960 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4961 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4962 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4963 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4964 }
4965
4966 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4967 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4968 pw.println(header);
4969
Wale Ogunwaled32da472018-11-16 07:19:28 -08004970 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004971 dumpPackage);
4972 boolean needSep = printedAnything;
4973
4974 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004975 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004976 " ResumedActivity: ");
4977 if (printed) {
4978 printedAnything = true;
4979 needSep = false;
4980 }
4981
4982 if (dumpPackage == null) {
4983 if (needSep) {
4984 pw.println();
4985 }
4986 printedAnything = true;
4987 mStackSupervisor.dump(pw, " ");
4988 }
4989
4990 if (!printedAnything) {
4991 pw.println(" (nothing)");
4992 }
4993 }
4994
4995 void dumpActivityContainersLocked(PrintWriter pw) {
4996 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004997 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004998 pw.println(" ");
4999 }
5000
5001 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
5002 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
5003 getActivityStartController().dump(pw, "", dumpPackage);
5004 }
5005
5006 /**
5007 * There are three things that cmd can be:
5008 * - a flattened component name that matches an existing activity
5009 * - the cmd arg isn't the flattened component name of an existing activity:
5010 * dump all activity whose component contains the cmd as a substring
5011 * - A hex number of the ActivityRecord object instance.
5012 *
5013 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
5014 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
5015 */
5016 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
5017 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
5018 ArrayList<ActivityRecord> activities;
5019
5020 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005021 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07005022 dumpFocusedStackOnly);
5023 }
5024
5025 if (activities.size() <= 0) {
5026 return false;
5027 }
5028
5029 String[] newArgs = new String[args.length - opti];
5030 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
5031
5032 TaskRecord lastTask = null;
5033 boolean needSep = false;
5034 for (int i = activities.size() - 1; i >= 0; i--) {
5035 ActivityRecord r = activities.get(i);
5036 if (needSep) {
5037 pw.println();
5038 }
5039 needSep = true;
5040 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005041 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07005042 if (lastTask != task) {
5043 lastTask = task;
5044 pw.print("TASK "); pw.print(lastTask.affinity);
5045 pw.print(" id="); pw.print(lastTask.taskId);
5046 pw.print(" userId="); pw.println(lastTask.userId);
5047 if (dumpAll) {
5048 lastTask.dump(pw, " ");
5049 }
5050 }
5051 }
5052 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5053 }
5054 return true;
5055 }
5056
5057 /**
5058 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5059 * there is a thread associated with the activity.
5060 */
5061 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5062 final ActivityRecord r, String[] args, boolean dumpAll) {
5063 String innerPrefix = prefix + " ";
5064 synchronized (mGlobalLock) {
5065 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5066 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5067 pw.print(" pid=");
5068 if (r.hasProcess()) pw.println(r.app.getPid());
5069 else pw.println("(not running)");
5070 if (dumpAll) {
5071 r.dump(pw, innerPrefix);
5072 }
5073 }
5074 if (r.attachedToProcess()) {
5075 // flush anything that is already in the PrintWriter since the thread is going
5076 // to write to the file descriptor directly
5077 pw.flush();
5078 try {
5079 TransferPipe tp = new TransferPipe();
5080 try {
5081 r.app.getThread().dumpActivity(tp.getWriteFd(),
5082 r.appToken, innerPrefix, args);
5083 tp.go(fd);
5084 } finally {
5085 tp.kill();
5086 }
5087 } catch (IOException e) {
5088 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5089 } catch (RemoteException e) {
5090 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5091 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005092 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005093 }
5094
sanryhuang498e77e2018-12-06 14:57:01 +08005095 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5096 boolean testPssMode) {
5097 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5098 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5099 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005100 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005101 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5102 st.toString());
5103 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005104 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5105 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5106 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005107 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5108 testPssMode);
5109 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005110 }
5111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005112 int getCurrentUserId() {
5113 return mAmInternal.getCurrentUserId();
5114 }
5115
5116 private void enforceNotIsolatedCaller(String caller) {
5117 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5118 throw new SecurityException("Isolated process not allowed to call " + caller);
5119 }
5120 }
5121
Wale Ogunwalef6733932018-06-27 05:14:34 -07005122 public Configuration getConfiguration() {
5123 Configuration ci;
5124 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005125 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005126 ci.userSetLocale = false;
5127 }
5128 return ci;
5129 }
5130
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005131 /**
5132 * Current global configuration information. Contains general settings for the entire system,
5133 * also corresponds to the merged configuration of the default display.
5134 */
5135 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005136 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137 }
5138
5139 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5140 boolean initLocale) {
5141 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5142 }
5143
5144 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5145 boolean initLocale, boolean deferResume) {
5146 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5147 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5148 UserHandle.USER_NULL, deferResume);
5149 }
5150
Wale Ogunwale59507092018-10-29 09:00:30 -07005151 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005152 final long origId = Binder.clearCallingIdentity();
5153 try {
5154 synchronized (mGlobalLock) {
5155 updateConfigurationLocked(values, null, false, true, userId,
5156 false /* deferResume */);
5157 }
5158 } finally {
5159 Binder.restoreCallingIdentity(origId);
5160 }
5161 }
5162
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005163 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5164 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5165 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5166 deferResume, null /* result */);
5167 }
5168
5169 /**
5170 * Do either or both things: (1) change the current configuration, and (2)
5171 * make sure the given activity is running with the (now) current
5172 * configuration. Returns true if the activity has been left running, or
5173 * false if <var>starting</var> is being destroyed to match the new
5174 * configuration.
5175 *
5176 * @param userId is only used when persistent parameter is set to true to persist configuration
5177 * for that particular user
5178 */
5179 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5180 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5181 ActivityTaskManagerService.UpdateConfigurationResult result) {
5182 int changes = 0;
5183 boolean kept = true;
5184
5185 if (mWindowManager != null) {
5186 mWindowManager.deferSurfaceLayout();
5187 }
5188 try {
5189 if (values != null) {
5190 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5191 deferResume);
5192 }
5193
5194 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5195 } finally {
5196 if (mWindowManager != null) {
5197 mWindowManager.continueSurfaceLayout();
5198 }
5199 }
5200
5201 if (result != null) {
5202 result.changes = changes;
5203 result.activityRelaunched = !kept;
5204 }
5205 return kept;
5206 }
5207
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005208 /** Update default (global) configuration and notify listeners about changes. */
5209 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5210 boolean persistent, int userId, boolean deferResume) {
5211 mTempConfig.setTo(getGlobalConfiguration());
5212 final int changes = mTempConfig.updateFrom(values);
5213 if (changes == 0) {
5214 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5215 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5216 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5217 // (even if there are no actual changes) to unfreeze the window.
5218 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5219 return 0;
5220 }
5221
5222 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5223 "Updating global configuration to: " + values);
5224
5225 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5226 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5227 values.colorMode,
5228 values.densityDpi,
5229 values.fontScale,
5230 values.hardKeyboardHidden,
5231 values.keyboard,
5232 values.keyboardHidden,
5233 values.mcc,
5234 values.mnc,
5235 values.navigation,
5236 values.navigationHidden,
5237 values.orientation,
5238 values.screenHeightDp,
5239 values.screenLayout,
5240 values.screenWidthDp,
5241 values.smallestScreenWidthDp,
5242 values.touchscreen,
5243 values.uiMode);
5244
5245
5246 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5247 final LocaleList locales = values.getLocales();
5248 int bestLocaleIndex = 0;
5249 if (locales.size() > 1) {
5250 if (mSupportedSystemLocales == null) {
5251 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5252 }
5253 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5254 }
5255 SystemProperties.set("persist.sys.locale",
5256 locales.get(bestLocaleIndex).toLanguageTag());
5257 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005258
5259 final Message m = PooledLambda.obtainMessage(
5260 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5261 locales.get(bestLocaleIndex));
5262 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005263 }
5264
Yunfan Chen75157d72018-07-27 14:47:21 +09005265 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005266
5267 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005268 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005269
5270 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5271 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005272 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005273
5274 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005275 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005276
5277 AttributeCache ac = AttributeCache.instance();
5278 if (ac != null) {
5279 ac.updateConfiguration(mTempConfig);
5280 }
5281
5282 // Make sure all resources in our process are updated right now, so that anyone who is going
5283 // to retrieve resource values after we return will be sure to get the new ones. This is
5284 // especially important during boot, where the first config change needs to guarantee all
5285 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005286 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005287
5288 // We need another copy of global config because we're scheduling some calls instead of
5289 // running them in place. We need to be sure that object we send will be handled unchanged.
5290 final Configuration configCopy = new Configuration(mTempConfig);
5291 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005292 final Message msg = PooledLambda.obtainMessage(
5293 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5294 this, userId, configCopy);
5295 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005296 }
5297
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005298 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5299 for (int i = pidMap.size() - 1; i >= 0; i--) {
5300 final int pid = pidMap.keyAt(i);
5301 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005302 if (DEBUG_CONFIGURATION) {
5303 Slog.v(TAG_CONFIGURATION, "Update process config of "
5304 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005305 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005306 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005307 }
5308
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005309 final Message msg = PooledLambda.obtainMessage(
5310 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5311 mAmInternal, changes, initLocale);
5312 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005313
5314 // Override configuration of the default display duplicates global config, so we need to
5315 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005316 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005317 DEFAULT_DISPLAY);
5318
5319 return changes;
5320 }
5321
5322 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5323 boolean deferResume, int displayId) {
5324 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5325 displayId, null /* result */);
5326 }
5327
5328 /**
5329 * Updates override configuration specific for the selected display. If no config is provided,
5330 * new one will be computed in WM based on current display info.
5331 */
5332 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5333 ActivityRecord starting, boolean deferResume, int displayId,
5334 ActivityTaskManagerService.UpdateConfigurationResult result) {
5335 int changes = 0;
5336 boolean kept = true;
5337
5338 if (mWindowManager != null) {
5339 mWindowManager.deferSurfaceLayout();
5340 }
5341 try {
5342 if (values != null) {
5343 if (displayId == DEFAULT_DISPLAY) {
5344 // Override configuration of the default display duplicates global config, so
5345 // we're calling global config update instead for default display. It will also
5346 // apply the correct override config.
5347 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5348 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5349 } else {
5350 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5351 }
5352 }
5353
5354 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5355 } finally {
5356 if (mWindowManager != null) {
5357 mWindowManager.continueSurfaceLayout();
5358 }
5359 }
5360
5361 if (result != null) {
5362 result.changes = changes;
5363 result.activityRelaunched = !kept;
5364 }
5365 return kept;
5366 }
5367
5368 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5369 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005370 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005371 final int changes = mTempConfig.updateFrom(values);
5372 if (changes != 0) {
5373 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5374 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005375 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005376
5377 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5378 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005379 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005380
Wale Ogunwale5c918702018-10-18 11:06:33 -07005381 // Post message to start process to avoid possible deadlock of calling into AMS with
5382 // the ATMS lock held.
5383 final Message msg = PooledLambda.obtainMessage(
5384 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005385 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005386 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005387 }
5388 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005389 return changes;
5390 }
5391
Wale Ogunwalef6733932018-06-27 05:14:34 -07005392 private void updateEventDispatchingLocked(boolean booted) {
5393 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5394 }
5395
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005396 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5397 final ContentResolver resolver = mContext.getContentResolver();
5398 Settings.System.putConfigurationForUser(resolver, config, userId);
5399 }
5400
5401 private void sendLocaleToMountDaemonMsg(Locale l) {
5402 try {
5403 IBinder service = ServiceManager.getService("mount");
5404 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5405 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5406 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5407 } catch (RemoteException e) {
5408 Log.e(TAG, "Error storing locale for decryption UI", e);
5409 }
5410 }
5411
Alison Cichowlas3e340502018-08-07 17:15:01 -04005412 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5413 mStartActivitySources.remove(permissionToken);
5414 mExpiredStartAsCallerTokens.add(permissionToken);
5415 }
5416
5417 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5418 mExpiredStartAsCallerTokens.remove(permissionToken);
5419 }
5420
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005421 boolean isActivityStartsLoggingEnabled() {
5422 return mAmInternal.isActivityStartsLoggingEnabled();
5423 }
5424
Michal Karpinski8596ded2018-11-14 14:43:48 +00005425 boolean isBackgroundActivityStartsEnabled() {
5426 return mAmInternal.isBackgroundActivityStartsEnabled();
5427 }
5428
Ricky Waiaca8a772019-04-04 16:01:06 +01005429 boolean isPackageNameWhitelistedForBgActivityStarts(@Nullable String packageName) {
5430 if (packageName == null) {
5431 return false;
5432 }
Michal Karpinski666631b2019-02-26 16:59:11 +00005433 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5434 }
5435
Wale Ogunwalef6733932018-06-27 05:14:34 -07005436 void enableScreenAfterBoot(boolean booted) {
5437 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5438 SystemClock.uptimeMillis());
5439 mWindowManager.enableScreenAfterBoot();
5440
5441 synchronized (mGlobalLock) {
5442 updateEventDispatchingLocked(booted);
5443 }
5444 }
5445
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005446 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5447 if (r == null || !r.hasProcess()) {
5448 return KEY_DISPATCHING_TIMEOUT_MS;
5449 }
5450 return getInputDispatchingTimeoutLocked(r.app);
5451 }
5452
5453 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005454 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005455 }
5456
Wale Ogunwalef6733932018-06-27 05:14:34 -07005457 /**
5458 * Decide based on the configuration whether we should show the ANR,
5459 * crash, etc dialogs. The idea is that if there is no affordance to
5460 * press the on-screen buttons, or the user experience would be more
5461 * greatly impacted than the crash itself, we shouldn't show the dialog.
5462 *
5463 * A thought: SystemUI might also want to get told about this, the Power
5464 * dialog / global actions also might want different behaviors.
5465 */
5466 private void updateShouldShowDialogsLocked(Configuration config) {
5467 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5468 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5469 && config.navigation == Configuration.NAVIGATION_NONAV);
5470 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5471 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5472 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5473 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5474 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5475 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5476 HIDE_ERROR_DIALOGS, 0) != 0;
5477 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5478 }
5479
5480 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5481 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5482 FONT_SCALE, 1.0f, userId);
5483
5484 synchronized (this) {
5485 if (getGlobalConfiguration().fontScale == scaleFactor) {
5486 return;
5487 }
5488
5489 final Configuration configuration
5490 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5491 configuration.fontScale = scaleFactor;
5492 updatePersistentConfiguration(configuration, userId);
5493 }
5494 }
5495
5496 // Actually is sleeping or shutting down or whatever else in the future
5497 // is an inactive state.
5498 boolean isSleepingOrShuttingDownLocked() {
5499 return isSleepingLocked() || mShuttingDown;
5500 }
5501
5502 boolean isSleepingLocked() {
5503 return mSleeping;
5504 }
5505
Riddle Hsu16567132018-08-16 21:37:47 +08005506 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005507 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005508 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005509 if (task.isActivityTypeStandard()) {
5510 if (mCurAppTimeTracker != r.appTimeTracker) {
5511 // We are switching app tracking. Complete the current one.
5512 if (mCurAppTimeTracker != null) {
5513 mCurAppTimeTracker.stop();
5514 mH.obtainMessage(
5515 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005516 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005517 mCurAppTimeTracker = null;
5518 }
5519 if (r.appTimeTracker != null) {
5520 mCurAppTimeTracker = r.appTimeTracker;
5521 startTimeTrackingFocusedActivityLocked();
5522 }
5523 } else {
5524 startTimeTrackingFocusedActivityLocked();
5525 }
5526 } else {
5527 r.appTimeTracker = null;
5528 }
5529 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5530 // TODO: Probably not, because we don't want to resume voice on switching
5531 // back to this activity
5532 if (task.voiceInteractor != null) {
5533 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5534 } else {
5535 finishRunningVoiceLocked();
5536
5537 if (mLastResumedActivity != null) {
5538 final IVoiceInteractionSession session;
5539
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005540 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005541 if (lastResumedActivityTask != null
5542 && lastResumedActivityTask.voiceSession != null) {
5543 session = lastResumedActivityTask.voiceSession;
5544 } else {
5545 session = mLastResumedActivity.voiceSession;
5546 }
5547
5548 if (session != null) {
5549 // We had been in a voice interaction session, but now focused has
5550 // move to something different. Just finish the session, we can't
5551 // return to it and retain the proper state and synchronization with
5552 // the voice interaction service.
5553 finishVoiceTask(session);
5554 }
5555 }
5556 }
5557
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005558 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5559 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005560 }
5561 updateResumedAppTrace(r);
5562 mLastResumedActivity = r;
5563
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005564 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005565
5566 applyUpdateLockStateLocked(r);
5567 applyUpdateVrModeLocked(r);
5568
5569 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005570 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005571 r == null ? "NULL" : r.shortComponentName,
5572 reason);
5573 }
5574
5575 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5576 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005577 final ActivityTaskManagerInternal.SleepToken token =
5578 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005579 updateSleepIfNeededLocked();
5580 return token;
5581 }
5582 }
5583
5584 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005585 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005586 final boolean wasSleeping = mSleeping;
5587 boolean updateOomAdj = false;
5588
5589 if (!shouldSleep) {
5590 // If wasSleeping is true, we need to wake up activity manager state from when
5591 // we started sleeping. In either case, we need to apply the sleep tokens, which
5592 // will wake up stacks or put them to sleep as appropriate.
5593 if (wasSleeping) {
5594 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005595 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5596 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005597 startTimeTrackingFocusedActivityLocked();
5598 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005599 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005600 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5601 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005602 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005603 if (wasSleeping) {
5604 updateOomAdj = true;
5605 }
5606 } else if (!mSleeping && shouldSleep) {
5607 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005608 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5609 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005610 if (mCurAppTimeTracker != null) {
5611 mCurAppTimeTracker.stop();
5612 }
5613 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005614 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005615 mStackSupervisor.goingToSleepLocked();
5616 updateResumedAppTrace(null /* resumed */);
5617 updateOomAdj = true;
5618 }
5619 if (updateOomAdj) {
5620 mH.post(mAmInternal::updateOomAdj);
5621 }
5622 }
5623
5624 void updateOomAdj() {
5625 mH.post(mAmInternal::updateOomAdj);
5626 }
5627
Wale Ogunwale53783742018-09-16 10:21:51 -07005628 void updateCpuStats() {
5629 mH.post(mAmInternal::updateCpuStats);
5630 }
5631
Hui Yu03d12402018-12-06 18:00:37 -08005632 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5633 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005634 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5635 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005636 mH.sendMessage(m);
5637 }
5638
Hui Yu03d12402018-12-06 18:00:37 -08005639 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005640 ComponentName taskRoot = null;
5641 final TaskRecord task = activity.getTaskRecord();
5642 if (task != null) {
5643 final ActivityRecord rootActivity = task.getRootActivity();
5644 if (rootActivity != null) {
5645 taskRoot = rootActivity.mActivityComponent;
5646 }
5647 }
5648
Hui Yu03d12402018-12-06 18:00:37 -08005649 final Message m = PooledLambda.obtainMessage(
5650 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005651 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005652 mH.sendMessage(m);
5653 }
5654
Wale Ogunwale53783742018-09-16 10:21:51 -07005655 void setBooting(boolean booting) {
5656 mAmInternal.setBooting(booting);
5657 }
5658
5659 boolean isBooting() {
5660 return mAmInternal.isBooting();
5661 }
5662
5663 void setBooted(boolean booted) {
5664 mAmInternal.setBooted(booted);
5665 }
5666
5667 boolean isBooted() {
5668 return mAmInternal.isBooted();
5669 }
5670
5671 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5672 mH.post(() -> {
5673 if (finishBooting) {
5674 mAmInternal.finishBooting();
5675 }
5676 if (enableScreen) {
5677 mInternal.enableScreenAfterBoot(isBooted());
5678 }
5679 });
5680 }
5681
5682 void setHeavyWeightProcess(ActivityRecord root) {
5683 mHeavyWeightProcess = root.app;
5684 final Message m = PooledLambda.obtainMessage(
5685 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005686 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005687 mH.sendMessage(m);
5688 }
5689
5690 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5691 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5692 return;
5693 }
5694
5695 mHeavyWeightProcess = null;
5696 final Message m = PooledLambda.obtainMessage(
5697 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5698 proc.mUserId);
5699 mH.sendMessage(m);
5700 }
5701
5702 private void cancelHeavyWeightProcessNotification(int userId) {
5703 final INotificationManager inm = NotificationManager.getService();
5704 if (inm == null) {
5705 return;
5706 }
5707 try {
5708 inm.cancelNotificationWithTag("android", null,
5709 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5710 } catch (RuntimeException e) {
5711 Slog.w(TAG, "Error canceling notification for service", e);
5712 } catch (RemoteException e) {
5713 }
5714
5715 }
5716
5717 private void postHeavyWeightProcessNotification(
5718 WindowProcessController proc, Intent intent, int userId) {
5719 if (proc == null) {
5720 return;
5721 }
5722
5723 final INotificationManager inm = NotificationManager.getService();
5724 if (inm == null) {
5725 return;
5726 }
5727
5728 try {
5729 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5730 String text = mContext.getString(R.string.heavy_weight_notification,
5731 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5732 Notification notification =
5733 new Notification.Builder(context,
5734 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5735 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5736 .setWhen(0)
5737 .setOngoing(true)
5738 .setTicker(text)
5739 .setColor(mContext.getColor(
5740 com.android.internal.R.color.system_notification_accent_color))
5741 .setContentTitle(text)
5742 .setContentText(
5743 mContext.getText(R.string.heavy_weight_notification_detail))
5744 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5745 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5746 new UserHandle(userId)))
5747 .build();
5748 try {
5749 inm.enqueueNotificationWithTag("android", "android", null,
5750 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5751 } catch (RuntimeException e) {
5752 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5753 } catch (RemoteException e) {
5754 }
5755 } catch (PackageManager.NameNotFoundException e) {
5756 Slog.w(TAG, "Unable to create context for heavy notification", e);
5757 }
5758
5759 }
5760
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005761 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5762 IBinder token, String resultWho, int requestCode, Intent[] intents,
5763 String[] resolvedTypes, int flags, Bundle bOptions) {
5764
5765 ActivityRecord activity = null;
5766 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5767 activity = ActivityRecord.isInStackLocked(token);
5768 if (activity == null) {
5769 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5770 return null;
5771 }
5772 if (activity.finishing) {
5773 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5774 return null;
5775 }
5776 }
5777
5778 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5779 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5780 bOptions);
5781 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5782 if (noCreate) {
5783 return rec;
5784 }
5785 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5786 if (activity.pendingResults == null) {
5787 activity.pendingResults = new HashSet<>();
5788 }
5789 activity.pendingResults.add(rec.ref);
5790 }
5791 return rec;
5792 }
5793
Andrii Kulian52d255c2018-07-13 11:32:19 -07005794 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005795 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005796 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005797 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5798 mCurAppTimeTracker.start(resumedActivity.packageName);
5799 }
5800 }
5801
5802 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5803 if (mTracedResumedActivity != null) {
5804 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5805 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5806 }
5807 if (resumed != null) {
5808 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5809 constructResumedTraceName(resumed.packageName), 0);
5810 }
5811 mTracedResumedActivity = resumed;
5812 }
5813
5814 private String constructResumedTraceName(String packageName) {
5815 return "focused app: " + packageName;
5816 }
5817
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005818 /** Applies latest configuration and/or visibility updates if needed. */
5819 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5820 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005821 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005822 // mainStack is null during startup.
5823 if (mainStack != null) {
5824 if (changes != 0 && starting == null) {
5825 // If the configuration changed, and the caller is not already
5826 // in the process of starting an activity, then find the top
5827 // activity to check if its configuration needs to change.
5828 starting = mainStack.topRunningActivityLocked();
5829 }
5830
5831 if (starting != null) {
5832 kept = starting.ensureActivityConfiguration(changes,
5833 false /* preserveWindow */);
5834 // And we need to make sure at this point that all other activities
5835 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005836 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005837 !PRESERVE_WINDOWS);
5838 }
5839 }
5840
5841 return kept;
5842 }
5843
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005844 void scheduleAppGcsLocked() {
5845 mH.post(() -> mAmInternal.scheduleAppGcs());
5846 }
5847
Wale Ogunwale53783742018-09-16 10:21:51 -07005848 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5849 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5850 }
5851
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005852 /**
5853 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5854 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5855 * on demand.
5856 */
5857 IPackageManager getPackageManager() {
5858 return AppGlobals.getPackageManager();
5859 }
5860
5861 PackageManagerInternal getPackageManagerInternalLocked() {
5862 if (mPmInternal == null) {
5863 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5864 }
5865 return mPmInternal;
5866 }
5867
Hai Zhangf4da9be2019-05-01 13:46:06 +08005868 PermissionPolicyInternal getPermissionPolicyInternal() {
5869 if (mPermissionPolicyInternal == null) {
5870 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5871 }
5872 return mPermissionPolicyInternal;
5873 }
5874
Wale Ogunwale008163e2018-07-23 23:11:08 -07005875 AppWarnings getAppWarningsLocked() {
5876 return mAppWarnings;
5877 }
5878
Wale Ogunwale214f3482018-10-04 11:00:47 -07005879 Intent getHomeIntent() {
5880 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5881 intent.setComponent(mTopComponent);
5882 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5883 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5884 intent.addCategory(Intent.CATEGORY_HOME);
5885 }
5886 return intent;
5887 }
5888
Chilun2ef71f72018-11-16 17:57:15 +08005889 /**
5890 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5891 * activities.
5892 *
5893 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5894 * component defined in config_secondaryHomeComponent.
5895 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5896 */
5897 Intent getSecondaryHomeIntent(String preferredPackage) {
5898 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005899 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5900 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5901 if (preferredPackage == null || useSystemProvidedLauncher) {
5902 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005903 final String secondaryHomeComponent = mContext.getResources().getString(
5904 com.android.internal.R.string.config_secondaryHomeComponent);
5905 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5906 } else {
5907 intent.setPackage(preferredPackage);
5908 }
5909 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5910 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5911 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5912 }
5913 return intent;
5914 }
5915
Wale Ogunwale214f3482018-10-04 11:00:47 -07005916 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5917 if (info == null) return null;
5918 ApplicationInfo newInfo = new ApplicationInfo(info);
5919 newInfo.initForUser(userId);
5920 return newInfo;
5921 }
5922
Wale Ogunwale9c103022018-10-18 07:44:54 -07005923 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005924 if (uid == SYSTEM_UID) {
5925 // The system gets to run in any process. If there are multiple processes with the same
5926 // uid, just pick the first (this should never happen).
5927 final SparseArray<WindowProcessController> procs =
5928 mProcessNames.getMap().get(processName);
5929 if (procs == null) return null;
5930 final int procCount = procs.size();
5931 for (int i = 0; i < procCount; i++) {
5932 final int procUid = procs.keyAt(i);
5933 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5934 // Don't use an app process or different user process for system component.
5935 continue;
5936 }
5937 return procs.valueAt(i);
5938 }
5939 }
5940
5941 return mProcessNames.get(processName, uid);
5942 }
5943
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005944 WindowProcessController getProcessController(IApplicationThread thread) {
5945 if (thread == null) {
5946 return null;
5947 }
5948
5949 final IBinder threadBinder = thread.asBinder();
5950 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5951 for (int i = pmap.size()-1; i >= 0; i--) {
5952 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5953 for (int j = procs.size() - 1; j >= 0; j--) {
5954 final WindowProcessController proc = procs.valueAt(j);
5955 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5956 return proc;
5957 }
5958 }
5959 }
5960
5961 return null;
5962 }
5963
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005964 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005965 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005966 if (proc == null) return null;
5967 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5968 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005969 }
5970 return null;
5971 }
5972
Riddle Hsua0536432019-02-16 00:38:59 +08005973 int getUidState(int uid) {
5974 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005975 }
5976
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005977 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005978 // A uid is considered to be foreground if it has a visible non-toast window.
5979 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005980 }
5981
Ricky Wai96f5c352019-04-10 18:40:17 +01005982 boolean isDeviceOwner(int uid) {
5983 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005984 }
5985
Ricky Wai96f5c352019-04-10 18:40:17 +01005986 void setDeviceOwnerUid(int uid) {
5987 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005988 }
5989
Wale Ogunwale9de19442018-10-18 19:05:03 -07005990 /**
5991 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5992 * the whitelist
5993 */
5994 String getPendingTempWhitelistTagForUidLocked(int uid) {
5995 return mPendingTempWhitelist.get(uid);
5996 }
5997
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005998 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5999 if (true || Build.IS_USER) {
6000 return;
6001 }
6002
6003 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
6004 StrictMode.allowThreadDiskWrites();
6005 try {
6006 File tracesDir = new File("/data/anr");
6007 File tracesFile = null;
6008 try {
6009 tracesFile = File.createTempFile("app_slow", null, tracesDir);
6010
6011 StringBuilder sb = new StringBuilder();
6012 Time tobj = new Time();
6013 tobj.set(System.currentTimeMillis());
6014 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
6015 sb.append(": ");
6016 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
6017 sb.append(" since ");
6018 sb.append(msg);
6019 FileOutputStream fos = new FileOutputStream(tracesFile);
6020 fos.write(sb.toString().getBytes());
6021 if (app == null) {
6022 fos.write("\n*** No application process!".getBytes());
6023 }
6024 fos.close();
6025 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
6026 } catch (IOException e) {
6027 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
6028 return;
6029 }
6030
6031 if (app != null && app.getPid() > 0) {
6032 ArrayList<Integer> firstPids = new ArrayList<Integer>();
6033 firstPids.add(app.getPid());
6034 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6035 }
6036
6037 File lastTracesFile = null;
6038 File curTracesFile = null;
6039 for (int i=9; i>=0; i--) {
6040 String name = String.format(Locale.US, "slow%02d.txt", i);
6041 curTracesFile = new File(tracesDir, name);
6042 if (curTracesFile.exists()) {
6043 if (lastTracesFile != null) {
6044 curTracesFile.renameTo(lastTracesFile);
6045 } else {
6046 curTracesFile.delete();
6047 }
6048 }
6049 lastTracesFile = curTracesFile;
6050 }
6051 tracesFile.renameTo(curTracesFile);
6052 } finally {
6053 StrictMode.setThreadPolicy(oldPolicy);
6054 }
6055 }
6056
Michal Karpinskida34cd42019-04-02 19:46:52 +01006057 boolean isAssociatedCompanionApp(int userId, int uid) {
6058 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6059 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006060 return false;
6061 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006062 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006063 }
6064
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006065 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006066 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006067
6068
Wale Ogunwale98875612018-10-12 07:53:02 -07006069 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6070 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006071
Riddle Hsud93a6c42018-11-29 21:50:06 +08006072 H(Looper looper) {
6073 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006074 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006075
6076 @Override
6077 public void handleMessage(Message msg) {
6078 switch (msg.what) {
6079 case REPORT_TIME_TRACKER_MSG: {
6080 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6081 tracker.deliverResult(mContext);
6082 } break;
6083 }
6084 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006085 }
6086
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006087 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006088 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006089
6090 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006091 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006092 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006093
6094 @Override
6095 public void handleMessage(Message msg) {
6096 switch (msg.what) {
6097 case DISMISS_DIALOG_UI_MSG: {
6098 final Dialog d = (Dialog) msg.obj;
6099 d.dismiss();
6100 break;
6101 }
6102 }
6103 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006104 }
6105
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006106 final class LocalService extends ActivityTaskManagerInternal {
6107 @Override
6108 public SleepToken acquireSleepToken(String tag, int displayId) {
6109 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006110 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006111 }
6112
6113 @Override
6114 public ComponentName getHomeActivityForUser(int userId) {
6115 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006116 final ActivityRecord homeActivity =
6117 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006118 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006119 }
6120 }
6121
6122 @Override
6123 public void onLocalVoiceInteractionStarted(IBinder activity,
6124 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6125 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006126 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006127 }
6128 }
6129
6130 @Override
6131 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
6132 synchronized (mGlobalLock) {
6133 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6134 reasons, timestamp);
6135 }
6136 }
6137
6138 @Override
6139 public void notifyAppTransitionFinished() {
6140 synchronized (mGlobalLock) {
6141 mStackSupervisor.notifyAppTransitionDone();
6142 }
6143 }
6144
6145 @Override
6146 public void notifyAppTransitionCancelled() {
6147 synchronized (mGlobalLock) {
6148 mStackSupervisor.notifyAppTransitionDone();
6149 }
6150 }
6151
6152 @Override
6153 public List<IBinder> getTopVisibleActivities() {
6154 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006155 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006156 }
6157 }
6158
6159 @Override
6160 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6161 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006162 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006163 }
6164 }
6165
6166 @Override
6167 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6168 Bundle bOptions) {
6169 Preconditions.checkNotNull(intents, "intents");
6170 final String[] resolvedTypes = new String[intents.length];
6171
6172 // UID of the package on user userId.
6173 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6174 // packageUid may not be initialized.
6175 int packageUid = 0;
6176 final long ident = Binder.clearCallingIdentity();
6177
6178 try {
6179 for (int i = 0; i < intents.length; i++) {
6180 resolvedTypes[i] =
6181 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6182 }
6183
6184 packageUid = AppGlobals.getPackageManager().getPackageUid(
6185 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6186 } catch (RemoteException e) {
6187 // Shouldn't happen.
6188 } finally {
6189 Binder.restoreCallingIdentity(ident);
6190 }
6191
Riddle Hsu591bf612019-02-14 17:55:31 +08006192 return getActivityStartController().startActivitiesInPackage(
6193 packageUid, packageName,
6194 intents, resolvedTypes, null /* resultTo */,
6195 SafeActivityOptions.fromBundle(bOptions), userId,
6196 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6197 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006198 }
6199
6200 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006201 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6202 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6203 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6204 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006205 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006206 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006207 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6208 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6209 userId, validateIncomingUser, originatingPendingIntent,
6210 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006211 }
6212 }
6213
6214 @Override
6215 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6216 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6217 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6218 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006219 PendingIntentRecord originatingPendingIntent,
6220 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006221 synchronized (mGlobalLock) {
6222 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6223 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6224 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006225 validateIncomingUser, originatingPendingIntent,
6226 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006227 }
6228 }
6229
6230 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006231 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6232 Intent intent, Bundle options, int userId) {
6233 return ActivityTaskManagerService.this.startActivityAsUser(
6234 caller, callerPacakge, intent,
6235 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6236 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6237 false /*validateIncomingUser*/);
6238 }
6239
6240 @Override
lumark588a3e82018-07-20 18:53:54 +08006241 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006242 synchronized (mGlobalLock) {
6243
6244 // We might change the visibilities here, so prepare an empty app transition which
6245 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006246 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006247 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006248 if (activityDisplay == null) {
6249 return;
6250 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006251 final DisplayContent dc = activityDisplay.mDisplayContent;
6252 final boolean wasTransitionSet =
6253 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006254 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006255 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006256 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006257 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006258
6259 // If there was a transition set already we don't want to interfere with it as we
6260 // might be starting it too early.
6261 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006262 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006263 }
6264 }
6265 if (callback != null) {
6266 callback.run();
6267 }
6268 }
6269
6270 @Override
6271 public void notifyKeyguardTrustedChanged() {
6272 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006273 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006274 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006275 }
6276 }
6277 }
6278
6279 /**
6280 * Called after virtual display Id is updated by
6281 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6282 * {@param vrVr2dDisplayId}.
6283 */
6284 @Override
6285 public void setVr2dDisplayId(int vr2dDisplayId) {
6286 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6287 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006288 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006289 }
6290 }
6291
6292 @Override
6293 public void setFocusedActivity(IBinder token) {
6294 synchronized (mGlobalLock) {
6295 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6296 if (r == null) {
6297 throw new IllegalArgumentException(
6298 "setFocusedActivity: No activity record matching token=" + token);
6299 }
Louis Chang19443452018-10-09 12:10:21 +08006300 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006301 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006302 }
6303 }
6304 }
6305
6306 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006307 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006308 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006309 }
6310
6311 @Override
6312 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006313 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006314 }
6315
6316 @Override
6317 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006318 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006319 }
6320
6321 @Override
6322 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6323 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6324 }
6325
6326 @Override
6327 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006328 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006329 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006330
6331 @Override
6332 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6333 synchronized (mGlobalLock) {
6334 mActiveVoiceInteractionServiceComponent = component;
6335 }
6336 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006337
6338 @Override
6339 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6340 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6341 return;
6342 }
6343 synchronized (mGlobalLock) {
6344 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6345 if (types == null) {
6346 if (uid < 0) {
6347 return;
6348 }
6349 types = new ArrayMap<>();
6350 mAllowAppSwitchUids.put(userId, types);
6351 }
6352 if (uid < 0) {
6353 types.remove(type);
6354 } else {
6355 types.put(type, uid);
6356 }
6357 }
6358 }
6359
6360 @Override
6361 public void onUserStopped(int userId) {
6362 synchronized (mGlobalLock) {
6363 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6364 mAllowAppSwitchUids.remove(userId);
6365 }
6366 }
6367
6368 @Override
6369 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6370 synchronized (mGlobalLock) {
6371 return ActivityTaskManagerService.this.isGetTasksAllowed(
6372 caller, callingPid, callingUid);
6373 }
6374 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006375
Riddle Hsua0536432019-02-16 00:38:59 +08006376 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006377 @Override
6378 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006379 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006380 mProcessNames.put(proc.mName, proc.mUid, proc);
6381 }
6382 }
6383
Riddle Hsua0536432019-02-16 00:38:59 +08006384 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006385 @Override
6386 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006387 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006388 mProcessNames.remove(name, uid);
6389 }
6390 }
6391
Riddle Hsua0536432019-02-16 00:38:59 +08006392 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006393 @Override
6394 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006395 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006396 if (proc == mHomeProcess) {
6397 mHomeProcess = null;
6398 }
6399 if (proc == mPreviousProcess) {
6400 mPreviousProcess = null;
6401 }
6402 }
6403 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006404
Riddle Hsua0536432019-02-16 00:38:59 +08006405 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006406 @Override
6407 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006408 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006409 return mTopProcessState;
6410 }
6411 }
6412
Riddle Hsua0536432019-02-16 00:38:59 +08006413 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006414 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006415 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006416 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006417 return proc == mHeavyWeightProcess;
6418 }
6419 }
6420
Riddle Hsua0536432019-02-16 00:38:59 +08006421 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006422 @Override
6423 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006424 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006425 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6426 }
6427 }
6428
6429 @Override
6430 public void finishHeavyWeightApp() {
6431 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006432 if (mHeavyWeightProcess != null) {
6433 mHeavyWeightProcess.finishActivities();
6434 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006435 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6436 mHeavyWeightProcess);
6437 }
6438 }
6439
Riddle Hsua0536432019-02-16 00:38:59 +08006440 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006441 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006442 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006443 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006444 return isSleepingLocked();
6445 }
6446 }
6447
6448 @Override
6449 public boolean isShuttingDown() {
6450 synchronized (mGlobalLock) {
6451 return mShuttingDown;
6452 }
6453 }
6454
6455 @Override
6456 public boolean shuttingDown(boolean booted, int timeout) {
6457 synchronized (mGlobalLock) {
6458 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006459 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006460 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006461 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006462 return mStackSupervisor.shutdownLocked(timeout);
6463 }
6464 }
6465
6466 @Override
6467 public void enableScreenAfterBoot(boolean booted) {
6468 synchronized (mGlobalLock) {
6469 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6470 SystemClock.uptimeMillis());
6471 mWindowManager.enableScreenAfterBoot();
6472 updateEventDispatchingLocked(booted);
6473 }
6474 }
6475
6476 @Override
6477 public boolean showStrictModeViolationDialog() {
6478 synchronized (mGlobalLock) {
6479 return mShowDialogs && !mSleeping && !mShuttingDown;
6480 }
6481 }
6482
6483 @Override
6484 public void showSystemReadyErrorDialogsIfNeeded() {
6485 synchronized (mGlobalLock) {
6486 try {
6487 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6488 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6489 + " data partition or your device will be unstable.");
6490 mUiHandler.post(() -> {
6491 if (mShowDialogs) {
6492 AlertDialog d = new BaseErrorDialog(mUiContext);
6493 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6494 d.setCancelable(false);
6495 d.setTitle(mUiContext.getText(R.string.android_system_label));
6496 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6497 d.setButton(DialogInterface.BUTTON_POSITIVE,
6498 mUiContext.getText(R.string.ok),
6499 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6500 d.show();
6501 }
6502 });
6503 }
6504 } catch (RemoteException e) {
6505 }
6506
6507 if (!Build.isBuildConsistent()) {
6508 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6509 mUiHandler.post(() -> {
6510 if (mShowDialogs) {
6511 AlertDialog d = new BaseErrorDialog(mUiContext);
6512 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6513 d.setCancelable(false);
6514 d.setTitle(mUiContext.getText(R.string.android_system_label));
6515 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6516 d.setButton(DialogInterface.BUTTON_POSITIVE,
6517 mUiContext.getText(R.string.ok),
6518 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6519 d.show();
6520 }
6521 });
6522 }
6523 }
6524 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006525
6526 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006527 public void onProcessMapped(int pid, WindowProcessController proc) {
6528 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006529 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006530 }
6531 }
6532
6533 @Override
6534 public void onProcessUnMapped(int pid) {
6535 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006536 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006537 }
6538 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006539
6540 @Override
6541 public void onPackageDataCleared(String name) {
6542 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006543 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006544 mAppWarnings.onPackageDataCleared(name);
6545 }
6546 }
6547
6548 @Override
6549 public void onPackageUninstalled(String name) {
6550 synchronized (mGlobalLock) {
6551 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006552 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006553 }
6554 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006555
6556 @Override
6557 public void onPackageAdded(String name, boolean replacing) {
6558 synchronized (mGlobalLock) {
6559 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6560 }
6561 }
6562
6563 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006564 public void onPackageReplaced(ApplicationInfo aInfo) {
6565 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006566 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006567 }
6568 }
6569
6570 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006571 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6572 synchronized (mGlobalLock) {
6573 return compatibilityInfoForPackageLocked(ai);
6574 }
6575 }
6576
Yunfan Chen75157d72018-07-27 14:47:21 +09006577 /**
6578 * Set the corresponding display information for the process global configuration. To be
6579 * called when we need to show IME on a different display.
6580 *
6581 * @param pid The process id associated with the IME window.
6582 * @param displayId The ID of the display showing the IME.
6583 */
6584 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006585 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006586 // Don't update process-level configuration for Multi-Client IME process since other
6587 // IMEs on other displays will also receive this configuration change due to IME
6588 // services use the same application config/context.
6589 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006590
Yunfan Chen75157d72018-07-27 14:47:21 +09006591 if (pid == MY_PID || pid < 0) {
6592 if (DEBUG_CONFIGURATION) {
6593 Slog.w(TAG,
6594 "Trying to update display configuration for system/invalid process.");
6595 }
6596 return;
6597 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006598 synchronized (mGlobalLock) {
6599 final ActivityDisplay activityDisplay =
6600 mRootActivityContainer.getActivityDisplay(displayId);
6601 if (activityDisplay == null) {
6602 // Call might come when display is not yet added or has been removed.
6603 if (DEBUG_CONFIGURATION) {
6604 Slog.w(TAG, "Trying to update display configuration for non-existing "
6605 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006606 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006607 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006608 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006609 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006610 if (process == null) {
6611 if (DEBUG_CONFIGURATION) {
6612 Slog.w(TAG, "Trying to update display configuration for invalid "
6613 + "process, pid=" + pid);
6614 }
6615 return;
6616 }
6617 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6618 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006619 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006620
6621 @Override
6622 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006623 int requestCode, int resultCode, Intent resultData) {
6624 final ActivityRecord r;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006625 synchronized (mGlobalLock) {
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006626 r = ActivityRecord.isInStackLocked(activityToken);
6627 if (r == null || r.getActivityStack() == null) {
6628 return;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006629 }
6630 }
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06006631
6632 // Carefully collect grants without holding lock
6633 final NeededUriGrants resultGrants = mUgmInternal.checkGrantUriPermissionFromIntent(
6634 Binder.getCallingUid(), resultData, r.packageName, r.mUserId);
6635
6636 synchronized (mGlobalLock) {
6637 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6638 requestCode, resultCode, resultData, resultGrants);
6639 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006640 }
6641
6642 @Override
6643 public void clearPendingResultForActivity(IBinder activityToken,
6644 WeakReference<PendingIntentRecord> pir) {
6645 synchronized (mGlobalLock) {
6646 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6647 if (r != null && r.pendingResults != null) {
6648 r.pendingResults.remove(pir);
6649 }
6650 }
6651 }
6652
6653 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006654 public ActivityTokens getTopActivityForTask(int taskId) {
6655 synchronized (mGlobalLock) {
6656 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6657 if (taskRecord == null) {
6658 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6659 + " Requested task not found");
6660 return null;
6661 }
6662 final ActivityRecord activity = taskRecord.getTopActivity();
6663 if (activity == null) {
6664 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6665 + " Requested activity not found");
6666 return null;
6667 }
6668 if (!activity.attachedToProcess()) {
6669 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6670 + activity);
6671 return null;
6672 }
6673 return new ActivityTokens(activity.appToken, activity.assistToken,
6674 activity.app.getThread());
6675 }
6676 }
6677
6678 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006679 public IIntentSender getIntentSender(int type, String packageName,
6680 int callingUid, int userId, IBinder token, String resultWho,
6681 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6682 Bundle bOptions) {
6683 synchronized (mGlobalLock) {
6684 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6685 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6686 }
6687 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006688
6689 @Override
6690 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6691 synchronized (mGlobalLock) {
6692 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6693 if (r == null) {
6694 return null;
6695 }
6696 if (r.mServiceConnectionsHolder == null) {
6697 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6698 ActivityTaskManagerService.this, r);
6699 }
6700
6701 return r.mServiceConnectionsHolder;
6702 }
6703 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006704
6705 @Override
6706 public Intent getHomeIntent() {
6707 synchronized (mGlobalLock) {
6708 return ActivityTaskManagerService.this.getHomeIntent();
6709 }
6710 }
6711
6712 @Override
6713 public boolean startHomeActivity(int userId, String reason) {
6714 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006715 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006716 }
6717 }
6718
6719 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006720 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006721 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006722 synchronized (mGlobalLock) {
6723 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006724 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006725 }
Chilun8b1f1be2019-03-13 17:14:36 +08006726 }
6727
6728 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006729 public boolean startHomeOnAllDisplays(int userId, String reason) {
6730 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006731 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006732 }
6733 }
6734
Riddle Hsua0536432019-02-16 00:38:59 +08006735 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006736 @Override
6737 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006738 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006739 if (mFactoryTest == FACTORY_TEST_OFF) {
6740 return false;
6741 }
6742 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6743 && wpc.mName.equals(mTopComponent.getPackageName())) {
6744 return true;
6745 }
6746 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6747 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6748 }
6749 }
6750
6751 @Override
6752 public void updateTopComponentForFactoryTest() {
6753 synchronized (mGlobalLock) {
6754 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6755 return;
6756 }
6757 final ResolveInfo ri = mContext.getPackageManager()
6758 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6759 final CharSequence errorMsg;
6760 if (ri != null) {
6761 final ActivityInfo ai = ri.activityInfo;
6762 final ApplicationInfo app = ai.applicationInfo;
6763 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6764 mTopAction = Intent.ACTION_FACTORY_TEST;
6765 mTopData = null;
6766 mTopComponent = new ComponentName(app.packageName, ai.name);
6767 errorMsg = null;
6768 } else {
6769 errorMsg = mContext.getResources().getText(
6770 com.android.internal.R.string.factorytest_not_system);
6771 }
6772 } else {
6773 errorMsg = mContext.getResources().getText(
6774 com.android.internal.R.string.factorytest_no_action);
6775 }
6776 if (errorMsg == null) {
6777 return;
6778 }
6779
6780 mTopAction = null;
6781 mTopData = null;
6782 mTopComponent = null;
6783 mUiHandler.post(() -> {
6784 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6785 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006786 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006787 });
6788 }
6789 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006790
Riddle Hsua0536432019-02-16 00:38:59 +08006791 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006792 @Override
6793 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6794 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006795 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006796 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006797 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006798
6799 wpc.clearRecentTasks();
6800 wpc.clearActivities();
6801
6802 if (wpc.isInstrumenting()) {
6803 finishInstrumentationCallback.run();
6804 }
6805
Jorim Jaggid0752812018-10-16 16:07:20 +02006806 if (!restarting && hasVisibleActivities) {
6807 mWindowManager.deferSurfaceLayout();
6808 try {
6809 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6810 // If there was nothing to resume, and we are not already restarting
6811 // this process, but there is a visible activity that is hosted by the
6812 // process...then make sure all visible activities are running, taking
6813 // care of restarting this process.
6814 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6815 !PRESERVE_WINDOWS);
6816 }
6817 } finally {
6818 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006819 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006820 }
6821 }
6822 }
6823
6824 @Override
6825 public void closeSystemDialogs(String reason) {
6826 enforceNotIsolatedCaller("closeSystemDialogs");
6827
6828 final int pid = Binder.getCallingPid();
6829 final int uid = Binder.getCallingUid();
6830 final long origId = Binder.clearCallingIdentity();
6831 try {
6832 synchronized (mGlobalLock) {
6833 // Only allow this from foreground processes, so that background
6834 // applications can't abuse it to prevent system UI from being shown.
6835 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006836 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 if (!proc.isPerceptible()) {
6838 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6839 + " from background process " + proc);
6840 return;
6841 }
6842 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006843 mWindowManager.closeSystemDialogs(reason);
6844
Wale Ogunwaled32da472018-11-16 07:19:28 -08006845 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006847 // Call into AM outside the synchronized block.
6848 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006849 } finally {
6850 Binder.restoreCallingIdentity(origId);
6851 }
6852 }
6853
6854 @Override
6855 public void cleanupDisabledPackageComponents(
6856 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6857 synchronized (mGlobalLock) {
6858 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006859 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006860 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006861 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006862 mStackSupervisor.scheduleIdleLocked();
6863 }
6864
6865 // Clean-up disabled tasks
6866 getRecentTasks().cleanupDisabledPackageTasksLocked(
6867 packageName, disabledClasses, userId);
6868 }
6869 }
6870
6871 @Override
6872 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6873 int userId) {
6874 synchronized (mGlobalLock) {
6875
6876 boolean didSomething =
6877 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006878 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006879 null, doit, evenPersistent, userId);
6880 return didSomething;
6881 }
6882 }
6883
6884 @Override
6885 public void resumeTopActivities(boolean scheduleIdle) {
6886 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006887 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006888 if (scheduleIdle) {
6889 mStackSupervisor.scheduleIdleLocked();
6890 }
6891 }
6892 }
6893
Riddle Hsua0536432019-02-16 00:38:59 +08006894 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006895 @Override
6896 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006897 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006898 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6899 }
6900 }
6901
Riddle Hsua0536432019-02-16 00:38:59 +08006902 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006903 @Override
6904 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006905 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006906 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006907 }
6908 }
6909
6910 @Override
6911 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6912 try {
6913 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6914 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6915 }
6916 } catch (RemoteException ex) {
6917 throw new SecurityException("Fail to check is caller a privileged app", ex);
6918 }
6919
6920 synchronized (mGlobalLock) {
6921 final long ident = Binder.clearCallingIdentity();
6922 try {
6923 if (mAmInternal.shouldConfirmCredentials(userId)) {
6924 if (mKeyguardController.isKeyguardLocked()) {
6925 // Showing launcher to avoid user entering credential twice.
6926 startHomeActivity(currentUserId, "notifyLockedProfile");
6927 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006928 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006929 }
6930 } finally {
6931 Binder.restoreCallingIdentity(ident);
6932 }
6933 }
6934 }
6935
6936 @Override
6937 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6938 mAmInternal.enforceCallingPermission(
6939 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6940
6941 synchronized (mGlobalLock) {
6942 final long ident = Binder.clearCallingIdentity();
6943 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006944 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6945 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006946 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6948 UserHandle.CURRENT);
6949 } finally {
6950 Binder.restoreCallingIdentity(ident);
6951 }
6952 }
6953 }
6954
6955 @Override
6956 public void writeActivitiesToProto(ProtoOutputStream proto) {
6957 synchronized (mGlobalLock) {
6958 // The output proto of "activity --proto activities"
6959 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006960 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006961 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6962 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006963 }
6964 }
6965
6966 @Override
6967 public void saveANRState(String reason) {
6968 synchronized (mGlobalLock) {
6969 final StringWriter sw = new StringWriter();
6970 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6971 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6972 if (reason != null) {
6973 pw.println(" Reason: " + reason);
6974 }
6975 pw.println();
6976 getActivityStartController().dump(pw, " ", null);
6977 pw.println();
6978 pw.println("-------------------------------------------------------------------------------");
6979 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6980 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6981 "" /* header */);
6982 pw.println();
6983 pw.close();
6984
6985 mLastANRState = sw.toString();
6986 }
6987 }
6988
6989 @Override
6990 public void clearSavedANRState() {
6991 synchronized (mGlobalLock) {
6992 mLastANRState = null;
6993 }
6994 }
6995
6996 @Override
6997 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6998 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6999 synchronized (mGlobalLock) {
7000 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
7001 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
7002 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
7003 dumpLastANRLocked(pw);
7004 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
7005 dumpLastANRTracesLocked(pw);
7006 } else if (DUMP_STARTER_CMD.equals(cmd)) {
7007 dumpActivityStarterLocked(pw, dumpPackage);
7008 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
7009 dumpActivityContainersLocked(pw);
7010 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
7011 if (getRecentTasks() != null) {
7012 getRecentTasks().dump(pw, dumpAll, dumpPackage);
7013 }
7014 }
7015 }
7016 }
7017
7018 @Override
7019 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
7020 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
7021 int wakefulness) {
7022 synchronized (mGlobalLock) {
7023 if (mHomeProcess != null && (dumpPackage == null
7024 || mHomeProcess.mPkgList.contains(dumpPackage))) {
7025 if (needSep) {
7026 pw.println();
7027 needSep = false;
7028 }
7029 pw.println(" mHomeProcess: " + mHomeProcess);
7030 }
7031 if (mPreviousProcess != null && (dumpPackage == null
7032 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7033 if (needSep) {
7034 pw.println();
7035 needSep = false;
7036 }
7037 pw.println(" mPreviousProcess: " + mPreviousProcess);
7038 }
7039 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7040 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7041 StringBuilder sb = new StringBuilder(128);
7042 sb.append(" mPreviousProcessVisibleTime: ");
7043 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7044 pw.println(sb);
7045 }
7046 if (mHeavyWeightProcess != null && (dumpPackage == null
7047 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7048 if (needSep) {
7049 pw.println();
7050 needSep = false;
7051 }
7052 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7053 }
7054 if (dumpPackage == null) {
7055 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007056 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007057 }
7058 if (dumpAll) {
7059 if (dumpPackage == null) {
7060 pw.println(" mConfigWillChange: "
7061 + getTopDisplayFocusedStack().mConfigWillChange);
7062 }
7063 if (mCompatModePackages.getPackages().size() > 0) {
7064 boolean printed = false;
7065 for (Map.Entry<String, Integer> entry
7066 : mCompatModePackages.getPackages().entrySet()) {
7067 String pkg = entry.getKey();
7068 int mode = entry.getValue();
7069 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7070 continue;
7071 }
7072 if (!printed) {
7073 pw.println(" mScreenCompatPackages:");
7074 printed = true;
7075 }
7076 pw.println(" " + pkg + ": " + mode);
7077 }
7078 }
7079 }
7080
7081 if (dumpPackage == null) {
7082 pw.println(" mWakefulness="
7083 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007084 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007085 if (mRunningVoice != null) {
7086 pw.println(" mRunningVoice=" + mRunningVoice);
7087 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7088 }
7089 pw.println(" mSleeping=" + mSleeping);
7090 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7091 pw.println(" mVrController=" + mVrController);
7092 }
7093 if (mCurAppTimeTracker != null) {
7094 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7095 }
7096 if (mAllowAppSwitchUids.size() > 0) {
7097 boolean printed = false;
7098 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7099 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7100 for (int j = 0; j < types.size(); j++) {
7101 if (dumpPackage == null ||
7102 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7103 if (needSep) {
7104 pw.println();
7105 needSep = false;
7106 }
7107 if (!printed) {
7108 pw.println(" mAllowAppSwitchUids:");
7109 printed = true;
7110 }
7111 pw.print(" User ");
7112 pw.print(mAllowAppSwitchUids.keyAt(i));
7113 pw.print(": Type ");
7114 pw.print(types.keyAt(j));
7115 pw.print(" = ");
7116 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7117 pw.println();
7118 }
7119 }
7120 }
7121 }
7122 if (dumpPackage == null) {
7123 if (mController != null) {
7124 pw.println(" mController=" + mController
7125 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7126 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007127 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7128 pw.println(" mLaunchingActivityWakeLock="
7129 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007130 }
7131
7132 return needSep;
7133 }
7134 }
7135
7136 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007137 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7138 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007139 synchronized (mGlobalLock) {
7140 if (dumpPackage == null) {
7141 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7142 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007143 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7144 if (mRunningVoice != null) {
7145 final long vrToken = proto.start(
7146 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7147 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7148 mRunningVoice.toString());
7149 mVoiceWakeLock.writeToProto(
7150 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7151 proto.end(vrToken);
7152 }
7153 mVrController.writeToProto(proto,
7154 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007155 if (mController != null) {
7156 final long token = proto.start(CONTROLLER);
7157 proto.write(CONTROLLER, mController.toString());
7158 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7159 proto.end(token);
7160 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007161 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7162 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7163 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007164 }
7165
7166 if (mHomeProcess != null && (dumpPackage == null
7167 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007168 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007169 }
7170
7171 if (mPreviousProcess != null && (dumpPackage == null
7172 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007173 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007174 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7175 }
7176
7177 if (mHeavyWeightProcess != null && (dumpPackage == null
7178 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007179 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007180 }
7181
7182 for (Map.Entry<String, Integer> entry
7183 : mCompatModePackages.getPackages().entrySet()) {
7184 String pkg = entry.getKey();
7185 int mode = entry.getValue();
7186 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7187 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7188 proto.write(PACKAGE, pkg);
7189 proto.write(MODE, mode);
7190 proto.end(compatToken);
7191 }
7192 }
7193
7194 if (mCurAppTimeTracker != null) {
7195 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7196 }
7197
7198 }
7199 }
7200
7201 @Override
7202 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7203 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7204 boolean dumpFocusedStackOnly) {
7205 synchronized (mGlobalLock) {
7206 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7207 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7208 }
7209 }
7210
7211 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007212 public void dumpForOom(PrintWriter pw) {
7213 synchronized (mGlobalLock) {
7214 pw.println(" mHomeProcess: " + mHomeProcess);
7215 pw.println(" mPreviousProcess: " + mPreviousProcess);
7216 if (mHeavyWeightProcess != null) {
7217 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7218 }
7219 }
7220 }
7221
7222 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007223 public boolean canGcNow() {
7224 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007225 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007226 }
7227 }
7228
Riddle Hsua0536432019-02-16 00:38:59 +08007229 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007230 @Override
7231 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007232 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007233 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007234 return top != null ? top.app : null;
7235 }
7236 }
7237
Riddle Hsua0536432019-02-16 00:38:59 +08007238 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007239 @Override
7240 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007241 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007242 if (mRootActivityContainer != null) {
7243 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007244 }
7245 }
7246 }
7247
7248 @Override
7249 public void scheduleDestroyAllActivities(String reason) {
7250 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007251 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007252 }
7253 }
7254
7255 @Override
7256 public void removeUser(int userId) {
7257 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007258 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007259 }
7260 }
7261
7262 @Override
7263 public boolean switchUser(int userId, UserState userState) {
7264 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007265 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007266 }
7267 }
7268
7269 @Override
7270 public void onHandleAppCrash(WindowProcessController wpc) {
7271 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007272 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007273 }
7274 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007275
7276 @Override
7277 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7278 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007279 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007280 }
7281 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007282
Riddle Hsua0536432019-02-16 00:38:59 +08007283 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007284 @Override
7285 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007286 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007287 }
7288
Riddle Hsua0536432019-02-16 00:38:59 +08007289 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007290 @Override
7291 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007292 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007293 }
7294
Riddle Hsua0536432019-02-16 00:38:59 +08007295 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007296 @Override
7297 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007298 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007299 }
7300
Riddle Hsua0536432019-02-16 00:38:59 +08007301 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007302 @Override
7303 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007304 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007305 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007306
7307 @Override
7308 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007309 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007310 mPendingTempWhitelist.put(uid, tag);
7311 }
7312 }
7313
7314 @Override
7315 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007316 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007317 mPendingTempWhitelist.remove(uid);
7318 }
7319 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007320
7321 @Override
7322 public boolean handleAppCrashInActivityController(String processName, int pid,
7323 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7324 Runnable killCrashingAppCallback) {
7325 synchronized (mGlobalLock) {
7326 if (mController == null) {
7327 return false;
7328 }
7329
7330 try {
7331 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7332 stackTrace)) {
7333 killCrashingAppCallback.run();
7334 return true;
7335 }
7336 } catch (RemoteException e) {
7337 mController = null;
7338 Watchdog.getInstance().setActivityController(null);
7339 }
7340 return false;
7341 }
7342 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007343
7344 @Override
7345 public void removeRecentTasksByPackageName(String packageName, int userId) {
7346 synchronized (mGlobalLock) {
7347 mRecentTasks.removeTasksByPackageName(packageName, userId);
7348 }
7349 }
7350
7351 @Override
7352 public void cleanupRecentTasksForUser(int userId) {
7353 synchronized (mGlobalLock) {
7354 mRecentTasks.cleanupLocked(userId);
7355 }
7356 }
7357
7358 @Override
7359 public void loadRecentTasksForUser(int userId) {
7360 synchronized (mGlobalLock) {
7361 mRecentTasks.loadUserRecentsLocked(userId);
7362 }
7363 }
7364
7365 @Override
7366 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7367 synchronized (mGlobalLock) {
7368 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7369 }
7370 }
7371
7372 @Override
7373 public void flushRecentTasks() {
7374 mRecentTasks.flush();
7375 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007376
7377 @Override
7378 public WindowProcessController getHomeProcess() {
7379 synchronized (mGlobalLock) {
7380 return mHomeProcess;
7381 }
7382 }
7383
7384 @Override
7385 public WindowProcessController getPreviousProcess() {
7386 synchronized (mGlobalLock) {
7387 return mPreviousProcess;
7388 }
7389 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007390
7391 @Override
7392 public void clearLockedTasks(String reason) {
7393 synchronized (mGlobalLock) {
7394 getLockTaskController().clearLockedTasks(reason);
7395 }
7396 }
7397
7398 @Override
7399 public void updateUserConfiguration() {
7400 synchronized (mGlobalLock) {
7401 final Configuration configuration = new Configuration(getGlobalConfiguration());
7402 final int currentUserId = mAmInternal.getCurrentUserId();
7403 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7404 configuration, currentUserId, Settings.System.canWrite(mContext));
7405 updateConfigurationLocked(configuration, null /* starting */,
7406 false /* initLocale */, false /* persistent */, currentUserId,
7407 false /* deferResume */);
7408 }
7409 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007410
7411 @Override
7412 public boolean canShowErrorDialogs() {
7413 synchronized (mGlobalLock) {
7414 return mShowDialogs && !mSleeping && !mShuttingDown
7415 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7416 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7417 mAmInternal.getCurrentUserId())
7418 && !(UserManager.isDeviceInDemoMode(mContext)
7419 && mAmInternal.getCurrentUser().isDemo());
7420 }
7421 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007422
7423 @Override
7424 public void setProfileApp(String profileApp) {
7425 synchronized (mGlobalLock) {
7426 mProfileApp = profileApp;
7427 }
7428 }
7429
7430 @Override
7431 public void setProfileProc(WindowProcessController wpc) {
7432 synchronized (mGlobalLock) {
7433 mProfileProc = wpc;
7434 }
7435 }
7436
7437 @Override
7438 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7439 synchronized (mGlobalLock) {
7440 mProfilerInfo = profilerInfo;
7441 }
7442 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007443
7444 @Override
7445 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7446 synchronized (mGlobalLock) {
7447 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7448 }
7449 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007450
7451 @Override
7452 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7453 synchronized (mGlobalLock) {
7454 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7455 }
7456 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007457
7458 @Override
7459 public boolean isUidForeground(int uid) {
7460 synchronized (mGlobalLock) {
7461 return ActivityTaskManagerService.this.isUidForeground(uid);
7462 }
7463 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007464
7465 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007466 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007467 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007468 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007469 }
7470 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007471
7472 @Override
7473 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007474 // Translate package names into UIDs
7475 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007476 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007477 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7478 if (uid >= 0) {
7479 result.add(uid);
7480 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007481 }
7482 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007483 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007484 }
7485 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007486 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007487}