blob: 046ab55d015a9d21755a5ca2b4079831641b5aa5 [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;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700249import com.android.server.LocalServices;
250import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700251import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800252import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700254import com.android.server.am.ActivityManagerService;
255import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
256import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
257import com.android.server.am.AppTimeTracker;
258import com.android.server.am.BaseErrorDialog;
259import com.android.server.am.EventLogTags;
260import com.android.server.am.PendingIntentController;
261import com.android.server.am.PendingIntentRecord;
262import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900263import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800266import com.android.server.policy.PermissionPolicyInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700267import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700271import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700275import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700276import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700277import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800278import java.lang.annotation.ElementType;
279import java.lang.annotation.Retention;
280import java.lang.annotation.RetentionPolicy;
281import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700283import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700285import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400287import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700288import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700289import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700290import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700291import java.util.Map;
292import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700293
294/**
295 * System service for managing activities and their containers (task, stacks, displays,... ).
296 *
297 * {@hide}
298 */
299public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700300 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700302 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
303 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
304 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
305 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
306 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700307 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700308
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700312 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Michal Karpinskifc6872e2019-05-21 15:18:44 +0100313 // How long we permit background activity starts after an activity in the process
314 // started or finished.
315 static final long ACTIVITY_BG_START_GRACE_PERIOD_MS = 10 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700316
Wale Ogunwale98875612018-10-12 07:53:02 -0700317 /** Used to indicate that an app transition should be animated. */
318 static final boolean ANIMATE = true;
319
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700320 /** Hardware-reported OpenGLES version. */
321 final int GL_ES_VERSION;
322
Wale Ogunwale31913b52018-10-13 08:29:31 -0700323 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
324 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
325 public static final String DUMP_LASTANR_CMD = "lastanr" ;
326 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
327 public static final String DUMP_STARTER_CMD = "starter" ;
328 public static final String DUMP_CONTAINERS_CMD = "containers" ;
329 public static final String DUMP_RECENTS_CMD = "recents" ;
330 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
331
Wale Ogunwale64258362018-10-16 15:13:37 -0700332 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
333 public static final int RELAUNCH_REASON_NONE = 0;
334 /** This activity is being relaunched due to windowing mode change. */
335 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
336 /** This activity is being relaunched due to a free-resize operation. */
337 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
338
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700339 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700340
Wale Ogunwalef6733932018-06-27 05:14:34 -0700341 /**
342 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
343 * change at runtime. Use mContext for non-UI purposes.
344 */
345 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700347 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700348 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700349 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700350 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700351 private PackageManagerInternal mPmInternal;
Hai Zhangf4da9be2019-05-01 13:46:06 +0800352 private PermissionPolicyInternal mPermissionPolicyInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800353 @VisibleForTesting
354 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700355 PowerManagerInternal mPowerManagerInternal;
356 private UsageStatsManagerInternal mUsageStatsInternal;
357
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700358 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700359 IntentFirewall mIntentFirewall;
360
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700361 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800362 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800363 /**
364 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
365 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
366 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
367 *
368 * @see WindowManagerThreadPriorityBooster
369 */
370 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700371 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800372 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700373 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700374 private UserManagerService mUserManager;
375 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700376 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800377 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700378 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700379 /** All processes currently running that might have a window organized by name. */
380 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100381 /** All processes we currently have running mapped by pid and uid */
382 final WindowProcessControllerMap mProcessMap = new WindowProcessControllerMap();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700383 /** This is the process holding what we currently consider to be the "home" activity. */
384 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700385 /** The currently running heavy-weight process, if any. */
386 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700387 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700388 /**
389 * This is the process holding the activity the user last visited that is in a different process
390 * from the one they are currently in.
391 */
392 WindowProcessController mPreviousProcess;
393 /** The time at which the previous process was last visible. */
394 long mPreviousProcessVisibleTime;
395
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700396 /** List of intents that were used to start the most recent tasks. */
397 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700398 /** State of external calls telling us if the device is awake or asleep. */
399 private boolean mKeyguardShown = false;
400
401 // Wrapper around VoiceInteractionServiceManager
402 private AssistUtils mAssistUtils;
403
404 // VoiceInteraction session ID that changes for each new request except when
405 // being called for multi-window assist in a single session.
406 private int mViSessionId = 1000;
407
408 // How long to wait in getAssistContextExtras for the activity and foreground services
409 // to respond with the result.
410 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
411
412 // How long top wait when going through the modern assist (which doesn't need to block
413 // on getting this result before starting to launch its UI).
414 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
415
416 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
417 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
418
Alison Cichowlas3e340502018-08-07 17:15:01 -0400419 // Permission tokens are used to temporarily granted a trusted app the ability to call
420 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
421 // showing any appropriate error messages to the user.
422 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
423 10 * MINUTE_IN_MILLIS;
424
425 // How long before the service actually expires a token. This is slightly longer than
426 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
427 // expiration exception.
428 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
429 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
430
431 // How long the service will remember expired tokens, for the purpose of providing error
432 // messaging when a client uses an expired token.
433 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
434 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
435
436 // Activity tokens of system activities that are delegating their call to
437 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
438 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
439
440 // Permission tokens that have expired, but we remember for error reporting.
441 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
442
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700443 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
444
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445 // Keeps track of the active voice interaction service component, notified from
446 // VoiceInteractionManagerService
447 ComponentName mActiveVoiceInteractionServiceComponent;
448
Michal Karpinskida34cd42019-04-02 19:46:52 +0100449 // A map userId and all its companion app uids
450 private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +0000451
Wale Ogunwalee2172292018-10-25 10:11:10 -0700452 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453 KeyguardController mKeyguardController;
454 private final ClientLifecycleManager mLifecycleManager;
455 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700456 /** The controller for all operations related to locktask. */
457 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700458 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700459
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700460 boolean mSuppressResizeConfigChanges;
461
462 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
463 new UpdateConfigurationResult();
464
465 static final class UpdateConfigurationResult {
466 // Configuration changes that were updated.
467 int changes;
468 // If the activity was relaunched to match the new configuration.
469 boolean activityRelaunched;
470
471 void reset() {
472 changes = 0;
473 activityRelaunched = false;
474 }
475 }
476
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700477 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 private int mConfigurationSeq;
479 // To cache the list of supported system locales
480 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700481
482 /**
483 * Temp object used when global and/or display override configuration is updated. It is also
484 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
485 * anyone...
486 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 private Configuration mTempConfig = new Configuration();
488
Wale Ogunwalef6733932018-06-27 05:14:34 -0700489 /** Temporary to avoid allocations. */
490 final StringBuilder mStringBuilder = new StringBuilder(256);
491
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492 // Amount of time after a call to stopAppSwitches() during which we will
493 // prevent further untrusted switches from happening.
494 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
495
496 /**
497 * The time at which we will allow normal application switches again,
498 * after a call to {@link #stopAppSwitches()}.
499 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700500 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
502 * This is set to true after the first switch after mAppSwitchesAllowedTime
503 * is set; any switches after that will clear the time.
504 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700505 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700506
Ricky Wai906af482019-06-03 17:25:28 +0100507 /**
508 * Last stop app switches time, apps finished before this time cannot start background activity
509 * even if they are in grace period.
510 */
511 private long mLastStopAppSwitchesTime;
512
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700513 IActivityController mController = null;
514 boolean mControllerIsAMonkey = false;
515
Wale Ogunwale214f3482018-10-04 11:00:47 -0700516 final int mFactoryTest;
517
518 /** Used to control how we initialize the service. */
519 ComponentName mTopComponent;
520 String mTopAction = Intent.ACTION_MAIN;
521 String mTopData;
522
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800523 /** Profiling app information. */
524 String mProfileApp = null;
525 WindowProcessController mProfileProc = null;
526 ProfilerInfo mProfilerInfo = null;
527
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700528 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700529 * Dump of the activity state at the time of the last ANR. Cleared after
530 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
531 */
532 String mLastANRState;
533
534 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700535 * Used to retain an update lock when the foreground activity is in
536 * immersive mode.
537 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700538 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700539
540 /**
541 * Packages that are being allowed to perform unrestricted app switches. Mapping is
542 * User -> Type -> uid.
543 */
544 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
545
546 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700547 private int mThumbnailWidth;
548 private int mThumbnailHeight;
549 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700550
551 /**
552 * Flag that indicates if multi-window is enabled.
553 *
554 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
555 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
556 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
557 * At least one of the forms of multi-window must be enabled in order for this flag to be
558 * initialized to 'true'.
559 *
560 * @see #mSupportsSplitScreenMultiWindow
561 * @see #mSupportsFreeformWindowManagement
562 * @see #mSupportsPictureInPicture
563 * @see #mSupportsMultiDisplay
564 */
565 boolean mSupportsMultiWindow;
566 boolean mSupportsSplitScreenMultiWindow;
567 boolean mSupportsFreeformWindowManagement;
568 boolean mSupportsPictureInPicture;
569 boolean mSupportsMultiDisplay;
570 boolean mForceResizableActivities;
571
572 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
573
574 // VR Vr2d Display Id.
575 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700576
Wale Ogunwalef6733932018-06-27 05:14:34 -0700577 /**
578 * Set while we are wanting to sleep, to prevent any
579 * activities from being started/resumed.
580 *
581 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
582 *
583 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
584 * while in the sleep state until there is a pending transition out of sleep, in which case
585 * mSleeping is set to false, and remains false while awake.
586 *
587 * Whether mSleeping can quickly toggled between true/false without the device actually
588 * display changing states is undefined.
589 */
590 private boolean mSleeping = false;
591
592 /**
593 * The process state used for processes that are running the top activities.
594 * This changes between TOP and TOP_SLEEPING to following mSleeping.
595 */
596 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
597
598 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
599 // automatically. Important for devices without direct input devices.
600 private boolean mShowDialogs = true;
601
602 /** Set if we are shutting down the system, similar to sleeping. */
603 boolean mShuttingDown = false;
604
605 /**
606 * We want to hold a wake lock while running a voice interaction session, since
607 * this may happen with the screen off and we need to keep the CPU running to
608 * be able to continue to interact with the user.
609 */
610 PowerManager.WakeLock mVoiceWakeLock;
611
612 /**
613 * Set while we are running a voice interaction. This overrides sleeping while it is active.
614 */
615 IVoiceInteractionSession mRunningVoice;
616
617 /**
618 * The last resumed activity. This is identical to the current resumed activity most
619 * of the time but could be different when we're pausing one activity before we resume
620 * another activity.
621 */
622 ActivityRecord mLastResumedActivity;
623
624 /**
625 * The activity that is currently being traced as the active resumed activity.
626 *
627 * @see #updateResumedAppTrace
628 */
629 private @Nullable ActivityRecord mTracedResumedActivity;
630
631 /** If non-null, we are tracking the time the user spends in the currently focused app. */
632 AppTimeTracker mCurAppTimeTracker;
633
Wale Ogunwale008163e2018-07-23 23:11:08 -0700634 private AppWarnings mAppWarnings;
635
Wale Ogunwale53783742018-09-16 10:21:51 -0700636 /**
637 * Packages that the user has asked to have run in screen size
638 * compatibility mode instead of filling the screen.
639 */
640 CompatModePackages mCompatModePackages;
641
Wale Ogunwalef6733932018-06-27 05:14:34 -0700642 private FontScaleSettingObserver mFontScaleSettingObserver;
643
Ricky Wai96f5c352019-04-10 18:40:17 +0100644 private int mDeviceOwnerUid = Process.INVALID_UID;
Michal Karpinski4026cae2019-02-12 11:51:47 +0000645
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 private final class FontScaleSettingObserver extends ContentObserver {
647 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
648 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
649
650 public FontScaleSettingObserver() {
651 super(mH);
652 final ContentResolver resolver = mContext.getContentResolver();
653 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
654 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
655 UserHandle.USER_ALL);
656 }
657
658 @Override
659 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
660 if (mFontScaleUri.equals(uri)) {
661 updateFontScaleIfNeeded(userId);
662 } else if (mHideErrorDialogsUri.equals(uri)) {
663 synchronized (mGlobalLock) {
664 updateShouldShowDialogsLocked(getGlobalConfiguration());
665 }
666 }
667 }
668 }
669
Riddle Hsua0536432019-02-16 00:38:59 +0800670 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
671 @Target(ElementType.METHOD)
672 @Retention(RetentionPolicy.SOURCE)
673 @interface HotPath {
674 int NONE = 0;
675 int OOM_ADJUSTMENT = 1;
676 int LRU_UPDATE = 2;
677 int PROCESS_CHANGE = 3;
678 int caller() default NONE;
679 }
680
Charles Chen8d98dd22018-12-26 17:36:54 +0800681 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
682 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700683 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700684 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700685 mSystemThread = ActivityThread.currentActivityThread();
686 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700687 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800688 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700689 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700690 }
691
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700692 public void onSystemReady() {
693 synchronized (mGlobalLock) {
694 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
695 PackageManager.FEATURE_CANT_SAVE_STATE);
696 mAssistUtils = new AssistUtils(mContext);
697 mVrController.onSystemReady();
698 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700699 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700700 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700701 }
702
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700703 public void onInitPowerManagement() {
704 synchronized (mGlobalLock) {
705 mStackSupervisor.initPowerManagement();
706 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
707 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
708 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
709 mVoiceWakeLock.setReferenceCounted(false);
710 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700711 }
712
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700713 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700714 mFontScaleSettingObserver = new FontScaleSettingObserver();
715 }
716
Wale Ogunwale59507092018-10-29 09:00:30 -0700717 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700718 final boolean freeformWindowManagement =
719 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
720 || Settings.Global.getInt(
721 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
722
723 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
724 final boolean supportsPictureInPicture = supportsMultiWindow &&
725 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
726 final boolean supportsSplitScreenMultiWindow =
727 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
728 final boolean supportsMultiDisplay = mContext.getPackageManager()
729 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700730 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
731 final boolean forceResizable = Settings.Global.getInt(
732 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700733 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700734
735 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900736 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737
738 final Configuration configuration = new Configuration();
739 Settings.System.getConfiguration(resolver, configuration);
740 if (forceRtl) {
741 // This will take care of setting the correct layout direction flags
742 configuration.setLayoutDirection(configuration.locale);
743 }
744
745 synchronized (mGlobalLock) {
746 mForceResizableActivities = forceResizable;
747 final boolean multiWindowFormEnabled = freeformWindowManagement
748 || supportsSplitScreenMultiWindow
749 || supportsPictureInPicture
750 || supportsMultiDisplay;
751 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
752 mSupportsMultiWindow = true;
753 mSupportsFreeformWindowManagement = freeformWindowManagement;
754 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
755 mSupportsPictureInPicture = supportsPictureInPicture;
756 mSupportsMultiDisplay = supportsMultiDisplay;
757 } else {
758 mSupportsMultiWindow = false;
759 mSupportsFreeformWindowManagement = false;
760 mSupportsSplitScreenMultiWindow = false;
761 mSupportsPictureInPicture = false;
762 mSupportsMultiDisplay = false;
763 }
764 mWindowManager.setForceResizableTasks(mForceResizableActivities);
765 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700766 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
767 mWindowManager.setIsPc(isPc);
Garfield Tanb5910b42019-03-14 14:50:59 -0700768 mWindowManager.mRoot.onSettingsRetrieved();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700769 // This happens before any activities are started, so we can change global configuration
770 // in-place.
771 updateConfigurationLocked(configuration, null, true);
772 final Configuration globalConfig = getGlobalConfiguration();
773 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
774
775 // Load resources only after the current configuration has been set.
776 final Resources res = mContext.getResources();
777 mThumbnailWidth = res.getDimensionPixelSize(
778 com.android.internal.R.dimen.thumbnail_width);
779 mThumbnailHeight = res.getDimensionPixelSize(
780 com.android.internal.R.dimen.thumbnail_height);
781
782 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
783 mFullscreenThumbnailScale = (float) res
784 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
785 (float) globalConfig.screenWidthDp;
786 } else {
787 mFullscreenThumbnailScale = res.getFraction(
788 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
789 }
790 }
791 }
792
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800793 public WindowManagerGlobalLock getGlobalLock() {
794 return mGlobalLock;
795 }
796
Yunfan Chen585f2932019-01-29 16:04:45 +0900797 /** For test purpose only. */
798 @VisibleForTesting
799 public ActivityTaskManagerInternal getAtmInternal() {
800 return mInternal;
801 }
802
Riddle Hsud93a6c42018-11-29 21:50:06 +0800803 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
804 Looper looper) {
805 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700806 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700807 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700808 final File systemDir = SystemServiceManager.ensureSystemDir();
809 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
810 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700812
813 mTempConfig.setToDefaults();
814 mTempConfig.setLocales(LocaleList.getDefault());
815 mConfigurationSeq = mTempConfig.seq = 1;
816 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800817 mRootActivityContainer = new RootActivityContainer(this);
818 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700819
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700820 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700821 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700822 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700823 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700824 mRecentTasks = createRecentTasks();
825 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700826 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700827 mKeyguardController = mStackSupervisor.getKeyguardController();
828 }
829
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700830 public void onActivityManagerInternalAdded() {
831 synchronized (mGlobalLock) {
832 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
833 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
834 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700835 }
836
Yunfan Chen75157d72018-07-27 14:47:21 +0900837 int increaseConfigurationSeqLocked() {
838 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
839 return mConfigurationSeq;
840 }
841
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700842 protected ActivityStackSupervisor createStackSupervisor() {
843 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
844 supervisor.initialize();
845 return supervisor;
846 }
847
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700848 public void setWindowManager(WindowManagerService wm) {
849 synchronized (mGlobalLock) {
850 mWindowManager = wm;
851 mLockTaskController.setWindowManager(wm);
852 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800853 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700854 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700855 }
856
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700857 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
858 synchronized (mGlobalLock) {
859 mUsageStatsInternal = usageStatsManager;
860 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700861 }
862
Wale Ogunwalef6733932018-06-27 05:14:34 -0700863 UserManagerService getUserManager() {
864 if (mUserManager == null) {
865 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
866 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
867 }
868 return mUserManager;
869 }
870
871 AppOpsService getAppOpsService() {
872 if (mAppOpsService == null) {
873 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
874 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
875 }
876 return mAppOpsService;
877 }
878
879 boolean hasUserRestriction(String restriction, int userId) {
880 return getUserManager().hasUserRestriction(restriction, userId);
881 }
882
Michal Karpinski15486842019-04-25 17:33:42 +0100883 boolean hasSystemAlertWindowPermission(int callingUid, int callingPid, String callingPackage) {
884 final int mode = getAppOpsService().noteOperation(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
885 callingUid, callingPackage);
886 if (mode == AppOpsManager.MODE_DEFAULT) {
887 return checkPermission(Manifest.permission.SYSTEM_ALERT_WINDOW, callingPid, callingUid)
888 == PERMISSION_GRANTED;
889 }
890 return mode == AppOpsManager.MODE_ALLOWED;
891 }
892
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700893 protected RecentTasks createRecentTasks() {
894 return new RecentTasks(this, mStackSupervisor);
895 }
896
897 RecentTasks getRecentTasks() {
898 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700899 }
900
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700901 ClientLifecycleManager getLifecycleManager() {
902 return mLifecycleManager;
903 }
904
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700905 ActivityStartController getActivityStartController() {
906 return mActivityStartController;
907 }
908
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700909 TaskChangeNotificationController getTaskChangeNotificationController() {
910 return mTaskChangeNotificationController;
911 }
912
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700913 LockTaskController getLockTaskController() {
914 return mLockTaskController;
915 }
916
Yunfan Chen75157d72018-07-27 14:47:21 +0900917 /**
918 * Return the global configuration used by the process corresponding to the input pid. This is
919 * usually the global configuration with some overrides specific to that process.
920 */
921 Configuration getGlobalConfigurationForCallingPid() {
922 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800923 return getGlobalConfigurationForPid(pid);
924 }
925
926 /**
927 * Return the global configuration used by the process corresponding to the given pid.
928 */
929 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900930 if (pid == MY_PID || pid < 0) {
931 return getGlobalConfiguration();
932 }
933 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +0100934 final WindowProcessController app = mProcessMap.getProcess(pid);
Yunfan Chen75157d72018-07-27 14:47:21 +0900935 return app != null ? app.getConfiguration() : getGlobalConfiguration();
936 }
937 }
938
939 /**
940 * Return the device configuration info used by the process corresponding to the input pid.
941 * The value is consistent with the global configuration for the process.
942 */
943 @Override
944 public ConfigurationInfo getDeviceConfigurationInfo() {
945 ConfigurationInfo config = new ConfigurationInfo();
946 synchronized (mGlobalLock) {
947 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
948 config.reqTouchScreen = globalConfig.touchscreen;
949 config.reqKeyboardType = globalConfig.keyboard;
950 config.reqNavigation = globalConfig.navigation;
951 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
952 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
953 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
954 }
955 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
956 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
957 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
958 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700959 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900960 }
961 return config;
962 }
963
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700964 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700965 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700966 }
967
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700968 public static final class Lifecycle extends SystemService {
969 private final ActivityTaskManagerService mService;
970
971 public Lifecycle(Context context) {
972 super(context);
973 mService = new ActivityTaskManagerService(context);
974 }
975
976 @Override
977 public void onStart() {
978 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700979 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700980 }
981
Garfield Tan891146c2018-10-09 12:14:00 -0700982 @Override
983 public void onUnlockUser(int userId) {
984 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800985 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700986 }
987 }
988
989 @Override
990 public void onCleanupUser(int userId) {
991 synchronized (mService.getGlobalLock()) {
992 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
993 }
994 }
995
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700996 public ActivityTaskManagerService getService() {
997 return mService;
998 }
999 }
1000
1001 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001002 public final int startActivity(IApplicationThread caller, String callingPackage,
1003 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1004 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
1005 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1006 resultWho, requestCode, startFlags, profilerInfo, bOptions,
1007 UserHandle.getCallingUserId());
1008 }
1009
1010 @Override
1011 public final int startActivities(IApplicationThread caller, String callingPackage,
1012 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
1013 int userId) {
1014 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 enforceNotIsolatedCaller(reason);
1016 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00001018 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
1019 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
1020 reason, null /* originatingPendingIntent */,
1021 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 }
1023
1024 @Override
1025 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1026 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1027 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1028 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1029 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1030 true /*validateIncomingUser*/);
1031 }
1032
1033 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1034 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1035 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1036 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001037 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001038
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001039 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1041
1042 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001043 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 .setCaller(caller)
1045 .setCallingPackage(callingPackage)
1046 .setResolvedType(resolvedType)
1047 .setResultTo(resultTo)
1048 .setResultWho(resultWho)
1049 .setRequestCode(requestCode)
1050 .setStartFlags(startFlags)
1051 .setProfilerInfo(profilerInfo)
1052 .setActivityOptions(bOptions)
1053 .setMayWait(userId)
1054 .execute();
1055
1056 }
1057
1058 @Override
1059 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1060 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001061 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1062 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 // Refuse possible leaked file descriptors
1064 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1065 throw new IllegalArgumentException("File descriptors passed in Intent");
1066 }
1067
1068 if (!(target instanceof PendingIntentRecord)) {
1069 throw new IllegalArgumentException("Bad PendingIntent object");
1070 }
1071
1072 PendingIntentRecord pir = (PendingIntentRecord)target;
1073
1074 synchronized (mGlobalLock) {
1075 // If this is coming from the currently resumed activity, it is
1076 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001077 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001078 if (stack.mResumedActivity != null &&
1079 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001080 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 }
1082 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001083 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001084 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001085 }
1086
1087 @Override
1088 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1089 Bundle bOptions) {
1090 // Refuse possible leaked file descriptors
1091 if (intent != null && intent.hasFileDescriptors()) {
1092 throw new IllegalArgumentException("File descriptors passed in Intent");
1093 }
1094 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1095
1096 synchronized (mGlobalLock) {
1097 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1098 if (r == null) {
1099 SafeActivityOptions.abort(options);
1100 return false;
1101 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001102 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001103 // The caller is not running... d'oh!
1104 SafeActivityOptions.abort(options);
1105 return false;
1106 }
1107 intent = new Intent(intent);
1108 // The caller is not allowed to change the data.
1109 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1110 // And we are resetting to find the next component...
1111 intent.setComponent(null);
1112
1113 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1114
1115 ActivityInfo aInfo = null;
1116 try {
1117 List<ResolveInfo> resolves =
1118 AppGlobals.getPackageManager().queryIntentActivities(
1119 intent, r.resolvedType,
1120 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1121 UserHandle.getCallingUserId()).getList();
1122
1123 // Look for the original activity in the list...
1124 final int N = resolves != null ? resolves.size() : 0;
1125 for (int i=0; i<N; i++) {
1126 ResolveInfo rInfo = resolves.get(i);
1127 if (rInfo.activityInfo.packageName.equals(r.packageName)
1128 && rInfo.activityInfo.name.equals(r.info.name)) {
1129 // We found the current one... the next matching is
1130 // after it.
1131 i++;
1132 if (i<N) {
1133 aInfo = resolves.get(i).activityInfo;
1134 }
1135 if (debug) {
1136 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1137 + "/" + r.info.name);
1138 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1139 ? "null" : aInfo.packageName + "/" + aInfo.name));
1140 }
1141 break;
1142 }
1143 }
1144 } catch (RemoteException e) {
1145 }
1146
1147 if (aInfo == null) {
1148 // Nobody who is next!
1149 SafeActivityOptions.abort(options);
1150 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1151 return false;
1152 }
1153
1154 intent.setComponent(new ComponentName(
1155 aInfo.applicationInfo.packageName, aInfo.name));
1156 intent.setFlags(intent.getFlags()&~(
1157 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1158 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1159 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1160 FLAG_ACTIVITY_NEW_TASK));
1161
1162 // Okay now we need to start the new activity, replacing the currently running activity.
1163 // This is a little tricky because we want to start the new one as if the current one is
1164 // finished, but not finish the current one first so that there is no flicker.
1165 // And thus...
1166 final boolean wasFinishing = r.finishing;
1167 r.finishing = true;
1168
1169 // Propagate reply information over to the new activity.
1170 final ActivityRecord resultTo = r.resultTo;
1171 final String resultWho = r.resultWho;
1172 final int requestCode = r.requestCode;
1173 r.resultTo = null;
1174 if (resultTo != null) {
1175 resultTo.removeResultsLocked(r, resultWho, requestCode);
1176 }
1177
1178 final long origId = Binder.clearCallingIdentity();
1179 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001180 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001181 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001182 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001183 .setResolvedType(r.resolvedType)
1184 .setActivityInfo(aInfo)
1185 .setResultTo(resultTo != null ? resultTo.appToken : null)
1186 .setResultWho(resultWho)
1187 .setRequestCode(requestCode)
1188 .setCallingPid(-1)
1189 .setCallingUid(r.launchedFromUid)
1190 .setCallingPackage(r.launchedFromPackage)
1191 .setRealCallingPid(-1)
1192 .setRealCallingUid(r.launchedFromUid)
1193 .setActivityOptions(options)
1194 .execute();
1195 Binder.restoreCallingIdentity(origId);
1196
1197 r.finishing = wasFinishing;
1198 if (res != ActivityManager.START_SUCCESS) {
1199 return false;
1200 }
1201 return true;
1202 }
1203 }
1204
1205 @Override
1206 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1207 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1208 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1209 final WaitResult res = new WaitResult();
1210 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001211 enforceNotIsolatedCaller("startActivityAndWait");
1212 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1213 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001214 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001215 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 .setCaller(caller)
1217 .setCallingPackage(callingPackage)
1218 .setResolvedType(resolvedType)
1219 .setResultTo(resultTo)
1220 .setResultWho(resultWho)
1221 .setRequestCode(requestCode)
1222 .setStartFlags(startFlags)
1223 .setActivityOptions(bOptions)
1224 .setMayWait(userId)
1225 .setProfilerInfo(profilerInfo)
1226 .setWaitResult(res)
1227 .execute();
1228 }
1229 return res;
1230 }
1231
1232 @Override
1233 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1235 int startFlags, Configuration config, Bundle bOptions, int userId) {
1236 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001237 enforceNotIsolatedCaller("startActivityWithConfig");
1238 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1239 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001240 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001241 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001242 .setCaller(caller)
1243 .setCallingPackage(callingPackage)
1244 .setResolvedType(resolvedType)
1245 .setResultTo(resultTo)
1246 .setResultWho(resultWho)
1247 .setRequestCode(requestCode)
1248 .setStartFlags(startFlags)
1249 .setGlobalConfiguration(config)
1250 .setActivityOptions(bOptions)
1251 .setMayWait(userId)
1252 .execute();
1253 }
1254 }
1255
Alison Cichowlas3e340502018-08-07 17:15:01 -04001256
1257 @Override
1258 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1259 int callingUid = Binder.getCallingUid();
1260 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1261 throw new SecurityException("Only the system process can request a permission token, "
1262 + "received request from uid: " + callingUid);
1263 }
1264 IBinder permissionToken = new Binder();
1265 synchronized (mGlobalLock) {
1266 mStartActivitySources.put(permissionToken, delegatorToken);
1267 }
1268
1269 Message expireMsg = PooledLambda.obtainMessage(
1270 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1271 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1272
1273 Message forgetMsg = PooledLambda.obtainMessage(
1274 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1275 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1276
1277 return permissionToken;
1278 }
1279
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001280 @Override
1281 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1282 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001283 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1284 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001286 // permission grants) as any app that may launch one of your own activities. So we only
1287 // allow this in two cases:
1288 // 1) The caller is an activity that is part of the core framework, and then only when it
1289 // is running as the system.
1290 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1291 // can only be requested by a system activity, which may then delegate this call to
1292 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001293 final ActivityRecord sourceRecord;
1294 final int targetUid;
1295 final String targetPackage;
1296 final boolean isResolver;
1297 synchronized (mGlobalLock) {
1298 if (resultTo == null) {
1299 throw new SecurityException("Must be called from an activity");
1300 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001301 final IBinder sourceToken;
1302 if (permissionToken != null) {
1303 // To even attempt to use a permissionToken, an app must also have this signature
1304 // permission.
1305 mAmInternal.enforceCallingPermission(
1306 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1307 "startActivityAsCaller");
1308 // If called with a permissionToken, we want the sourceRecord from the delegator
1309 // activity that requested this token.
1310 sourceToken = mStartActivitySources.remove(permissionToken);
1311 if (sourceToken == null) {
1312 // Invalid permissionToken, check if it recently expired.
1313 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1314 throw new SecurityException("Called with expired permission token: "
1315 + permissionToken);
1316 } else {
1317 throw new SecurityException("Called with invalid permission token: "
1318 + permissionToken);
1319 }
1320 }
1321 } else {
1322 // This method was called directly by the source.
1323 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001325
Wale Ogunwaled32da472018-11-16 07:19:28 -08001326 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001327 if (sourceRecord == null) {
1328 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001329 }
1330 if (sourceRecord.app == null) {
1331 throw new SecurityException("Called without a process attached to activity");
1332 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001333
1334 // Whether called directly or from a delegate, the source activity must be from the
1335 // android package.
1336 if (!sourceRecord.info.packageName.equals("android")) {
1337 throw new SecurityException("Must be called from an activity that is "
1338 + "declared in the android package");
1339 }
1340
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001341 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001342 // This is still okay, as long as this activity is running under the
1343 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001344 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001346 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 + " must be system uid or original calling uid "
1348 + sourceRecord.launchedFromUid);
1349 }
1350 }
1351 if (ignoreTargetSecurity) {
1352 if (intent.getComponent() == null) {
1353 throw new SecurityException(
1354 "Component must be specified with ignoreTargetSecurity");
1355 }
1356 if (intent.getSelector() != null) {
1357 throw new SecurityException(
1358 "Selector not allowed with ignoreTargetSecurity");
1359 }
1360 }
1361 targetUid = sourceRecord.launchedFromUid;
1362 targetPackage = sourceRecord.launchedFromPackage;
1363 isResolver = sourceRecord.isResolverOrChildActivity();
1364 }
1365
1366 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001367 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 }
1369
1370 // TODO: Switch to user app stacks here.
1371 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001372 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001373 .setCallingUid(targetUid)
1374 .setCallingPackage(targetPackage)
1375 .setResolvedType(resolvedType)
1376 .setResultTo(resultTo)
1377 .setResultWho(resultWho)
1378 .setRequestCode(requestCode)
1379 .setStartFlags(startFlags)
1380 .setActivityOptions(bOptions)
1381 .setMayWait(userId)
1382 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1383 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
Alan Stokes2f4a4ed2019-05-08 16:56:45 +01001384 // The target may well be in the background, which would normally prevent it
1385 // from starting an activity. Here we definitely want the start to succeed.
1386 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 .execute();
1388 } catch (SecurityException e) {
1389 // XXX need to figure out how to propagate to original app.
1390 // A SecurityException here is generally actually a fault of the original
1391 // calling activity (such as a fairly granting permissions), so propagate it
1392 // back to them.
1393 /*
1394 StringBuilder msg = new StringBuilder();
1395 msg.append("While launching");
1396 msg.append(intent.toString());
1397 msg.append(": ");
1398 msg.append(e.getMessage());
1399 */
1400 throw e;
1401 }
1402 }
1403
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001404 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1405 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1406 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1407 }
1408
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409 @Override
1410 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1411 Intent intent, String resolvedType, IVoiceInteractionSession session,
1412 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1413 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001414 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 if (session == null || interactor == null) {
1416 throw new NullPointerException("null session or interactor");
1417 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001418 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001419 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001420 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 .setCallingUid(callingUid)
1422 .setCallingPackage(callingPackage)
1423 .setResolvedType(resolvedType)
1424 .setVoiceSession(session)
1425 .setVoiceInteractor(interactor)
1426 .setStartFlags(startFlags)
1427 .setProfilerInfo(profilerInfo)
1428 .setActivityOptions(bOptions)
1429 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001430 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001431 .execute();
1432 }
1433
1434 @Override
1435 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1436 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001437 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1438 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001439
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001440 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 .setCallingUid(callingUid)
1442 .setCallingPackage(callingPackage)
1443 .setResolvedType(resolvedType)
1444 .setActivityOptions(bOptions)
1445 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001446 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001447 .execute();
1448 }
1449
1450 @Override
1451 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1452 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 final int callingPid = Binder.getCallingPid();
1455 final long origId = Binder.clearCallingIdentity();
1456 try {
1457 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001458 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1459 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001460
1461 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001462 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1463 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1465 recentsUid, assistDataReceiver);
1466 }
1467 } finally {
1468 Binder.restoreCallingIdentity(origId);
1469 }
1470 }
1471
1472 @Override
1473 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001474 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001475 "startActivityFromRecents()");
1476
1477 final int callingPid = Binder.getCallingPid();
1478 final int callingUid = Binder.getCallingUid();
1479 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1480 final long origId = Binder.clearCallingIdentity();
1481 try {
1482 synchronized (mGlobalLock) {
1483 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1484 safeOptions);
1485 }
1486 } finally {
1487 Binder.restoreCallingIdentity(origId);
1488 }
1489 }
1490
1491 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001492 * Public API to check if the client is allowed to start an activity on specified display.
1493 *
1494 * If the target display is private or virtual, some restrictions will apply.
1495 *
1496 * @param displayId Target display id.
1497 * @param intent Intent used to launch the activity.
1498 * @param resolvedType The MIME type of the intent.
1499 * @param userId The id of the user for whom the call is made.
1500 * @return {@code true} if a call to start an activity on the target display should succeed and
1501 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1502 */
1503 @Override
1504 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1505 String resolvedType, int userId) {
1506 final int callingUid = Binder.getCallingUid();
1507 final int callingPid = Binder.getCallingPid();
1508 final long origId = Binder.clearCallingIdentity();
1509
1510 try {
1511 // Collect information about the target of the Intent.
1512 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1513 0 /* startFlags */, null /* profilerInfo */, userId,
1514 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1515 UserHandle.USER_NULL));
1516 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1517
1518 synchronized (mGlobalLock) {
1519 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1520 aInfo);
1521 }
1522 } finally {
1523 Binder.restoreCallingIdentity(origId);
1524 }
1525 }
1526
1527 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001528 * This is the internal entry point for handling Activity.finish().
1529 *
1530 * @param token The Binder token referencing the Activity we want to finish.
1531 * @param resultCode Result code, if any, from this Activity.
1532 * @param resultData Result data (Intent), if any, from this Activity.
1533 * @param finishTask Whether to finish the task associated with this Activity.
1534 *
1535 * @return Returns true if the activity successfully finished, or false if it is still running.
1536 */
1537 @Override
1538 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1539 int finishTask) {
1540 // Refuse possible leaked file descriptors
1541 if (resultData != null && resultData.hasFileDescriptors()) {
1542 throw new IllegalArgumentException("File descriptors passed in Intent");
1543 }
1544
1545 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001546 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 if (r == null) {
1548 return true;
1549 }
1550 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001551 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 ActivityRecord rootR = tr.getRootActivity();
1553 if (rootR == null) {
1554 Slog.w(TAG, "Finishing task with all activities already finished");
1555 }
1556 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1557 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001558 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001559 return false;
1560 }
1561
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001562 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1563 // We should consolidate.
1564 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001565 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001566 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 if (next != null) {
1568 // ask watcher if this is allowed
1569 boolean resumeOK = true;
1570 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001571 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001572 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001573 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001574 Watchdog.getInstance().setActivityController(null);
1575 }
1576
1577 if (!resumeOK) {
1578 Slog.i(TAG, "Not finishing activity because controller resumed");
1579 return false;
1580 }
1581 }
1582 }
Michal Karpinskifc6872e2019-05-21 15:18:44 +01001583
1584 // note down that the process has finished an activity and is in background activity
1585 // starts grace period
1586 if (r.app != null) {
1587 r.app.setLastActivityFinishTimeIfNeeded(SystemClock.uptimeMillis());
1588 }
1589
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001590 final long origId = Binder.clearCallingIdentity();
1591 try {
1592 boolean res;
1593 final boolean finishWithRootActivity =
1594 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1595 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1596 || (finishWithRootActivity && r == rootR)) {
1597 // If requested, remove the task that is associated to this activity only if it
1598 // was the root activity in the task. The result code and data is ignored
1599 // because we don't support returning them across task boundaries. Also, to
1600 // keep backwards compatibility we remove the task from recents when finishing
1601 // task with root activity.
1602 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1603 finishWithRootActivity, "finish-activity");
1604 if (!res) {
1605 Slog.i(TAG, "Removing task failed to finish activity");
1606 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001607 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001608 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 } else {
1610 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00001611 resultData, "app-request", true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001612 if (!res) {
1613 Slog.i(TAG, "Failed to finish by app-request");
1614 }
1615 }
1616 return res;
1617 } finally {
1618 Binder.restoreCallingIdentity(origId);
1619 }
1620 }
1621 }
1622
1623 @Override
1624 public boolean finishActivityAffinity(IBinder token) {
1625 synchronized (mGlobalLock) {
1626 final long origId = Binder.clearCallingIdentity();
1627 try {
1628 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1629 if (r == null) {
1630 return false;
1631 }
1632
1633 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1634 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001635 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001636 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001637 return false;
1638 }
1639 return task.getStack().finishActivityAffinityLocked(r);
1640 } finally {
1641 Binder.restoreCallingIdentity(origId);
1642 }
1643 }
1644 }
1645
1646 @Override
1647 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1648 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001649 try {
1650 WindowProcessController proc = null;
1651 synchronized (mGlobalLock) {
1652 ActivityStack stack = ActivityRecord.getStackLocked(token);
1653 if (stack == null) {
1654 return;
1655 }
1656 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1657 false /* fromTimeout */, false /* processPausingActivities */, config);
1658 if (r != null) {
1659 proc = r.app;
1660 }
1661 if (stopProfiling && proc != null) {
1662 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663 }
1664 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001665 } finally {
1666 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001667 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001668 }
1669
1670 @Override
1671 public final void activityResumed(IBinder token) {
1672 final long origId = Binder.clearCallingIdentity();
1673 synchronized (mGlobalLock) {
1674 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001675 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 }
1677 Binder.restoreCallingIdentity(origId);
1678 }
1679
1680 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001681 public final void activityTopResumedStateLost() {
1682 final long origId = Binder.clearCallingIdentity();
1683 synchronized (mGlobalLock) {
1684 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1685 }
1686 Binder.restoreCallingIdentity(origId);
1687 }
1688
1689 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001690 public final void activityPaused(IBinder token) {
1691 final long origId = Binder.clearCallingIdentity();
1692 synchronized (mGlobalLock) {
1693 ActivityStack stack = ActivityRecord.getStackLocked(token);
1694 if (stack != null) {
1695 stack.activityPausedLocked(token, false);
1696 }
1697 }
1698 Binder.restoreCallingIdentity(origId);
1699 }
1700
1701 @Override
1702 public final void activityStopped(IBinder token, Bundle icicle,
1703 PersistableBundle persistentState, CharSequence description) {
1704 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1705
1706 // Refuse possible leaked file descriptors
1707 if (icicle != null && icicle.hasFileDescriptors()) {
1708 throw new IllegalArgumentException("File descriptors passed in Bundle");
1709 }
1710
1711 final long origId = Binder.clearCallingIdentity();
1712
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001713 String restartingName = null;
1714 int restartingUid = 0;
1715 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001716 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001717 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001719 if (r.attachedToProcess()
1720 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1721 // The activity was requested to restart from
1722 // {@link #restartActivityProcessIfVisible}.
1723 restartingName = r.app.mName;
1724 restartingUid = r.app.mUid;
1725 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 r.activityStoppedLocked(icicle, persistentState, description);
1727 }
1728 }
1729
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001730 if (restartingName != null) {
1731 // In order to let the foreground activity can be restarted with its saved state from
1732 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1733 // until the activity reports stopped with the state. And the activity record will be
1734 // kept because the record state is restarting, then the activity will be restarted
1735 // immediately if it is still the top one.
1736 mStackSupervisor.removeRestartTimeouts(r);
1737 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1738 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001739 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740
1741 Binder.restoreCallingIdentity(origId);
1742 }
1743
1744 @Override
1745 public final void activityDestroyed(IBinder token) {
1746 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1747 synchronized (mGlobalLock) {
1748 ActivityStack stack = ActivityRecord.getStackLocked(token);
1749 if (stack != null) {
1750 stack.activityDestroyedLocked(token, "activityDestroyed");
1751 }
1752 }
1753 }
1754
1755 @Override
1756 public final void activityRelaunched(IBinder token) {
1757 final long origId = Binder.clearCallingIdentity();
1758 synchronized (mGlobalLock) {
1759 mStackSupervisor.activityRelaunchedLocked(token);
1760 }
1761 Binder.restoreCallingIdentity(origId);
1762 }
1763
1764 public final void activitySlept(IBinder token) {
1765 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1766
1767 final long origId = Binder.clearCallingIdentity();
1768
1769 synchronized (mGlobalLock) {
1770 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1771 if (r != null) {
1772 mStackSupervisor.activitySleptLocked(r);
1773 }
1774 }
1775
1776 Binder.restoreCallingIdentity(origId);
1777 }
1778
1779 @Override
1780 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1781 synchronized (mGlobalLock) {
1782 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1783 if (r == null) {
1784 return;
1785 }
1786 final long origId = Binder.clearCallingIdentity();
1787 try {
1788 r.setRequestedOrientation(requestedOrientation);
1789 } finally {
1790 Binder.restoreCallingIdentity(origId);
1791 }
1792 }
1793 }
1794
1795 @Override
1796 public int getRequestedOrientation(IBinder token) {
1797 synchronized (mGlobalLock) {
1798 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1799 if (r == null) {
1800 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1801 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001802 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001803 }
1804 }
1805
1806 @Override
1807 public void setImmersive(IBinder token, boolean immersive) {
1808 synchronized (mGlobalLock) {
1809 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1810 if (r == null) {
1811 throw new IllegalArgumentException();
1812 }
1813 r.immersive = immersive;
1814
1815 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001816 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001817 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001818 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001819 }
1820 }
1821 }
1822
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001823 void applyUpdateLockStateLocked(ActivityRecord r) {
1824 // Modifications to the UpdateLock state are done on our handler, outside
1825 // the activity manager's locks. The new state is determined based on the
1826 // state *now* of the relevant activity record. The object is passed to
1827 // the handler solely for logging detail, not to be consulted/modified.
1828 final boolean nextState = r != null && r.immersive;
1829 mH.post(() -> {
1830 if (mUpdateLock.isHeld() != nextState) {
1831 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1832 "Applying new update lock state '" + nextState + "' for " + r);
1833 if (nextState) {
1834 mUpdateLock.acquire();
1835 } else {
1836 mUpdateLock.release();
1837 }
1838 }
1839 });
1840 }
1841
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 @Override
1843 public boolean isImmersive(IBinder token) {
1844 synchronized (mGlobalLock) {
1845 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1846 if (r == null) {
1847 throw new IllegalArgumentException();
1848 }
1849 return r.immersive;
1850 }
1851 }
1852
1853 @Override
1854 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001856 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001857 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 return (r != null) ? r.immersive : false;
1859 }
1860 }
1861
1862 @Override
1863 public void overridePendingTransition(IBinder token, String packageName,
1864 int enterAnim, int exitAnim) {
1865 synchronized (mGlobalLock) {
1866 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1867 if (self == null) {
1868 return;
1869 }
1870
1871 final long origId = Binder.clearCallingIdentity();
1872
1873 if (self.isState(
1874 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001875 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001876 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 }
1878
1879 Binder.restoreCallingIdentity(origId);
1880 }
1881 }
1882
1883 @Override
1884 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001885 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001886 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001887 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001888 if (r == null) {
1889 return ActivityManager.COMPAT_MODE_UNKNOWN;
1890 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001891 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 }
1893 }
1894
1895 @Override
1896 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001897 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001898 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001899 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001900 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001901 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001902 if (r == null) {
1903 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1904 return;
1905 }
1906 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001907 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001908 }
1909 }
1910
1911 @Override
1912 public int getLaunchedFromUid(IBinder activityToken) {
1913 ActivityRecord srec;
1914 synchronized (mGlobalLock) {
1915 srec = ActivityRecord.forTokenLocked(activityToken);
1916 }
1917 if (srec == null) {
1918 return -1;
1919 }
1920 return srec.launchedFromUid;
1921 }
1922
1923 @Override
1924 public String getLaunchedFromPackage(IBinder activityToken) {
1925 ActivityRecord srec;
1926 synchronized (mGlobalLock) {
1927 srec = ActivityRecord.forTokenLocked(activityToken);
1928 }
1929 if (srec == null) {
1930 return null;
1931 }
1932 return srec.launchedFromPackage;
1933 }
1934
1935 @Override
1936 public boolean convertFromTranslucent(IBinder token) {
1937 final long origId = Binder.clearCallingIdentity();
1938 try {
1939 synchronized (mGlobalLock) {
1940 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1941 if (r == null) {
1942 return false;
1943 }
1944 final boolean translucentChanged = r.changeWindowTranslucency(true);
1945 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001946 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001947 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001948 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001949 return translucentChanged;
1950 }
1951 } finally {
1952 Binder.restoreCallingIdentity(origId);
1953 }
1954 }
1955
1956 @Override
1957 public boolean convertToTranslucent(IBinder token, Bundle options) {
1958 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1959 final long origId = Binder.clearCallingIdentity();
1960 try {
1961 synchronized (mGlobalLock) {
1962 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1963 if (r == null) {
1964 return false;
1965 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001966 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 int index = task.mActivities.lastIndexOf(r);
1968 if (index > 0) {
1969 ActivityRecord under = task.mActivities.get(index - 1);
1970 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1971 }
1972 final boolean translucentChanged = r.changeWindowTranslucency(false);
1973 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001974 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001975 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001976 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001977 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001978 return translucentChanged;
1979 }
1980 } finally {
1981 Binder.restoreCallingIdentity(origId);
1982 }
1983 }
1984
1985 @Override
1986 public void notifyActivityDrawn(IBinder token) {
1987 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1988 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001989 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001990 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001991 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 }
1993 }
1994 }
1995
1996 @Override
1997 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1998 synchronized (mGlobalLock) {
1999 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2000 if (r == null) {
2001 return;
2002 }
2003 r.reportFullyDrawnLocked(restoredFromBundle);
2004 }
2005 }
2006
2007 @Override
2008 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
2009 synchronized (mGlobalLock) {
2010 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
2011 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
2012 return stack.mDisplayId;
2013 }
2014 return DEFAULT_DISPLAY;
2015 }
2016 }
2017
2018 @Override
2019 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002020 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 long ident = Binder.clearCallingIdentity();
2022 try {
2023 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002024 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002026 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 }
2028 return null;
2029 }
2030 } finally {
2031 Binder.restoreCallingIdentity(ident);
2032 }
2033 }
2034
2035 @Override
2036 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002037 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002038 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2039 final long callingId = Binder.clearCallingIdentity();
2040 try {
2041 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002042 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002043 if (stack == null) {
2044 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2045 return;
2046 }
2047 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002048 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002049 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002050 }
2051 }
2052 } finally {
2053 Binder.restoreCallingIdentity(callingId);
2054 }
2055 }
2056
2057 @Override
2058 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002059 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2061 final long callingId = Binder.clearCallingIdentity();
2062 try {
2063 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002064 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002065 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002066 if (task == null) {
2067 return;
2068 }
2069 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002070 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002071 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 }
2073 }
2074 } finally {
2075 Binder.restoreCallingIdentity(callingId);
2076 }
2077 }
2078
2079 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002080 public void restartActivityProcessIfVisible(IBinder activityToken) {
2081 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2082 final long callingId = Binder.clearCallingIdentity();
2083 try {
2084 synchronized (mGlobalLock) {
2085 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2086 if (r == null) {
2087 return;
2088 }
2089 r.restartProcessIfVisible();
2090 }
2091 } finally {
2092 Binder.restoreCallingIdentity(callingId);
2093 }
2094 }
2095
2096 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002098 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 synchronized (mGlobalLock) {
2100 final long ident = Binder.clearCallingIdentity();
2101 try {
2102 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2103 "remove-task");
2104 } finally {
2105 Binder.restoreCallingIdentity(ident);
2106 }
2107 }
2108 }
2109
2110 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002111 public void removeAllVisibleRecentTasks() {
2112 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2113 synchronized (mGlobalLock) {
2114 final long ident = Binder.clearCallingIdentity();
2115 try {
Winson Chung42fa21f2019-04-02 16:23:46 -07002116 getRecentTasks().removeAllVisibleTasks(mAmInternal.getCurrentUserId());
Winson Chunge6439102018-07-30 15:48:01 -07002117 } finally {
2118 Binder.restoreCallingIdentity(ident);
2119 }
2120 }
2121 }
2122
2123 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002124 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2125 synchronized (mGlobalLock) {
2126 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2127 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002128 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002129 }
2130 }
2131 return false;
2132 }
2133
2134 @Override
2135 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2136 Intent resultData) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002137
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002138 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002139 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2140 if (r != null) {
2141 return r.getActivityStack().navigateUpToLocked(
2142 r, destIntent, resultCode, resultData);
Jeff Sharkey344ce7c2019-05-29 14:52:59 -06002143 }
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00002144 return false;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002145 }
2146 }
2147
2148 /**
2149 * Attempts to move a task backwards in z-order (the order of activities within the task is
2150 * unchanged).
2151 *
2152 * There are several possible results of this call:
2153 * - if the task is locked, then we will show the lock toast
2154 * - if there is a task behind the provided task, then that task is made visible and resumed as
2155 * this task is moved to the back
2156 * - otherwise, if there are no other tasks in the stack:
2157 * - if this task is in the pinned stack, then we remove the stack completely, which will
2158 * have the effect of moving the task to the top or bottom of the fullscreen stack
2159 * (depending on whether it is visible)
2160 * - otherwise, we simply return home and hide this task
2161 *
2162 * @param token A reference to the activity we wish to move
2163 * @param nonRoot If false then this only works if the activity is the root
2164 * of a task; if true it will work for any activity in a task.
2165 * @return Returns true if the move completed, false if not.
2166 */
2167 @Override
2168 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002169 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 synchronized (mGlobalLock) {
2171 final long origId = Binder.clearCallingIdentity();
2172 try {
2173 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002174 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002175 if (task != null) {
2176 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2177 }
2178 } finally {
2179 Binder.restoreCallingIdentity(origId);
2180 }
2181 }
2182 return false;
2183 }
2184
2185 @Override
2186 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002187 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002188 long ident = Binder.clearCallingIdentity();
2189 Rect rect = new Rect();
2190 try {
2191 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002192 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002193 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2194 if (task == null) {
2195 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2196 return rect;
2197 }
2198 if (task.getStack() != null) {
2199 // Return the bounds from window manager since it will be adjusted for various
2200 // things like the presense of a docked stack for tasks that aren't resizeable.
2201 task.getWindowContainerBounds(rect);
2202 } else {
2203 // Task isn't in window manager yet since it isn't associated with a stack.
2204 // Return the persist value from activity manager
2205 if (!task.matchParentBounds()) {
2206 rect.set(task.getBounds());
2207 } else if (task.mLastNonFullscreenBounds != null) {
2208 rect.set(task.mLastNonFullscreenBounds);
2209 }
2210 }
2211 }
2212 } finally {
2213 Binder.restoreCallingIdentity(ident);
2214 }
2215 return rect;
2216 }
2217
2218 @Override
2219 public ActivityManager.TaskDescription getTaskDescription(int id) {
2220 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002221 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002222 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002223 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2225 if (tr != null) {
2226 return tr.lastTaskDescription;
2227 }
2228 }
2229 return null;
2230 }
2231
2232 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002233 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2234 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2235 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2236 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2237 return;
2238 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002239 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002240 synchronized (mGlobalLock) {
2241 final long ident = Binder.clearCallingIdentity();
2242 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002243 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002244 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002245 if (task == null) {
2246 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2247 return;
2248 }
2249
2250 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2251 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2252
2253 if (!task.isActivityTypeStandardOrUndefined()) {
2254 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2255 + " non-standard task " + taskId + " to windowing mode="
2256 + windowingMode);
2257 }
2258
2259 final ActivityStack stack = task.getStack();
2260 if (toTop) {
2261 stack.moveToFront("setTaskWindowingMode", task);
2262 }
2263 stack.setWindowingMode(windowingMode);
2264 } finally {
2265 Binder.restoreCallingIdentity(ident);
2266 }
2267 }
2268 }
2269
2270 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002271 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002272 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002273 ActivityRecord r = getCallingRecordLocked(token);
2274 return r != null ? r.info.packageName : null;
2275 }
2276 }
2277
2278 @Override
2279 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002280 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002281 ActivityRecord r = getCallingRecordLocked(token);
2282 return r != null ? r.intent.getComponent() : null;
2283 }
2284 }
2285
2286 private ActivityRecord getCallingRecordLocked(IBinder token) {
2287 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2288 if (r == null) {
2289 return null;
2290 }
2291 return r.resultTo;
2292 }
2293
2294 @Override
2295 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002296 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002297
2298 synchronized (mGlobalLock) {
2299 final long origId = Binder.clearCallingIdentity();
2300 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002301 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002302 } finally {
2303 Binder.restoreCallingIdentity(origId);
2304 }
2305 }
2306 }
2307
Mark Renouf446251d2019-04-26 10:22:41 -04002308 @Override
2309 public void onBackPressedOnTaskRoot(IBinder token, IRequestFinishCallback callback) {
2310 synchronized (mGlobalLock) {
2311 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2312 if (r == null) {
2313 return;
2314 }
2315 ActivityStack stack = r.getActivityStack();
2316 if (stack != null && stack.isSingleTaskInstance()) {
2317 // Single-task stacks are used for activities which are presented in floating
2318 // windows above full screen activities. Instead of directly finishing the
2319 // task, a task change listener is used to notify SystemUI so the action can be
2320 // handled specially.
2321 final TaskRecord task = r.getTaskRecord();
2322 mTaskChangeNotificationController
2323 .notifyBackPressedOnTaskRoot(task.getTaskInfo());
2324 } else {
2325 try {
2326 callback.requestFinish();
2327 } catch (RemoteException e) {
2328 Slog.e(TAG, "Failed to invoke request finish callback", e);
2329 }
2330 }
2331 }
2332 }
2333
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002334 /**
2335 * TODO: Add mController hook
2336 */
2337 @Override
Ricky Waiaca8a772019-04-04 16:01:06 +01002338 public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
2339 int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002340 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002341
2342 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2343 synchronized (mGlobalLock) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002344 moveTaskToFrontLocked(appThread, callingPackage, taskId, flags,
2345 SafeActivityOptions.fromBundle(bOptions), false /* fromRecents */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002346 }
2347 }
2348
Ricky Waiaca8a772019-04-04 16:01:06 +01002349 void moveTaskToFrontLocked(@Nullable IApplicationThread appThread,
2350 @Nullable String callingPackage, int taskId, int flags, SafeActivityOptions options,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002351 boolean fromRecents) {
2352
Ricky Waiaca8a772019-04-04 16:01:06 +01002353 final int callingPid = Binder.getCallingPid();
2354 final int callingUid = Binder.getCallingUid();
2355 if (!isSameApp(callingUid, callingPackage)) {
2356 String msg = "Permission Denial: moveTaskToFrontLocked() from pid="
2357 + Binder.getCallingPid() + " as package " + callingPackage;
2358 Slog.w(TAG, msg);
2359 throw new SecurityException(msg);
2360 }
2361 if (!checkAppSwitchAllowedLocked(callingPid, callingUid, -1, -1, "Task to front")) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002362 SafeActivityOptions.abort(options);
2363 return;
2364 }
2365 final long origId = Binder.clearCallingIdentity();
Ricky Waiaca8a772019-04-04 16:01:06 +01002366 WindowProcessController callerApp = null;
2367 if (appThread != null) {
2368 callerApp = getProcessController(appThread);
2369 }
2370 final ActivityStarter starter = getActivityStartController().obtainStarter(
2371 null /* intent */, "moveTaskToFront");
2372 if (starter.shouldAbortBackgroundActivityStart(callingUid, callingPid, callingPackage, -1,
2373 -1, callerApp, null, false, null)) {
Alan Stokes9e245762019-05-21 14:54:28 +01002374 if (!isBackgroundActivityStartsEnabled()) {
Ricky Waiaca8a772019-04-04 16:01:06 +01002375 return;
2376 }
2377 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002378 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002379 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380 if (task == null) {
2381 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002382 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002383 return;
2384 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002385 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002386 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002387 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002388 return;
2389 }
2390 ActivityOptions realOptions = options != null
2391 ? options.getOptions(mStackSupervisor)
2392 : null;
2393 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2394 false /* forceNonResizable */);
2395
2396 final ActivityRecord topActivity = task.getTopActivity();
2397 if (topActivity != null) {
2398
2399 // We are reshowing a task, use a starting window to hide the initial draw delay
2400 // so the transition can start earlier.
2401 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2402 true /* taskSwitch */, fromRecents);
2403 }
2404 } finally {
2405 Binder.restoreCallingIdentity(origId);
2406 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002407 }
2408
Ricky Waiaca8a772019-04-04 16:01:06 +01002409 /**
2410 * Return true if callingUid is system, or packageName belongs to that callingUid.
2411 */
2412 boolean isSameApp(int callingUid, @Nullable String packageName) {
2413 try {
2414 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2415 if (packageName == null) {
2416 return false;
2417 }
2418 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
2419 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2420 UserHandle.getUserId(callingUid));
2421 return UserHandle.isSameApp(callingUid, uid);
2422 }
2423 } catch (RemoteException e) {
2424 // Should not happen
2425 }
2426 return true;
2427 }
2428
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002429 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2430 int callingPid, int callingUid, String name) {
2431 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2432 return true;
2433 }
2434
2435 if (getRecentTasks().isCallerRecents(sourceUid)) {
2436 return true;
2437 }
2438
2439 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2440 if (perm == PackageManager.PERMISSION_GRANTED) {
2441 return true;
2442 }
2443 if (checkAllowAppSwitchUid(sourceUid)) {
2444 return true;
2445 }
2446
2447 // If the actual IPC caller is different from the logical source, then
2448 // also see if they are allowed to control app switches.
2449 if (callingUid != -1 && callingUid != sourceUid) {
2450 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2451 if (perm == PackageManager.PERMISSION_GRANTED) {
2452 return true;
2453 }
2454 if (checkAllowAppSwitchUid(callingUid)) {
2455 return true;
2456 }
2457 }
2458
2459 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2460 return false;
2461 }
2462
2463 private boolean checkAllowAppSwitchUid(int uid) {
2464 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2465 if (types != null) {
2466 for (int i = types.size() - 1; i >= 0; i--) {
2467 if (types.valueAt(i).intValue() == uid) {
2468 return true;
2469 }
2470 }
2471 }
2472 return false;
2473 }
2474
2475 @Override
2476 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2477 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2478 "setActivityController()");
2479 synchronized (mGlobalLock) {
2480 mController = controller;
2481 mControllerIsAMonkey = imAMonkey;
2482 Watchdog.getInstance().setActivityController(controller);
2483 }
2484 }
2485
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002486 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002487 synchronized (mGlobalLock) {
2488 return mController != null && mControllerIsAMonkey;
2489 }
2490 }
2491
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002492 @Override
2493 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2494 synchronized (mGlobalLock) {
2495 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2496 }
2497 }
2498
2499 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002500 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2501 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2502 }
2503
2504 @Override
2505 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2506 @WindowConfiguration.ActivityType int ignoreActivityType,
2507 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2508 final int callingUid = Binder.getCallingUid();
2509 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2510
2511 synchronized (mGlobalLock) {
2512 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2513
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002514 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002515 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002516 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 ignoreWindowingMode, callingUid, allowed);
2518 }
2519
2520 return list;
2521 }
2522
2523 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2525 synchronized (mGlobalLock) {
2526 final long origId = Binder.clearCallingIdentity();
2527 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2528 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002529 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 }
2531 Binder.restoreCallingIdentity(origId);
2532 }
2533 }
2534
2535 @Override
2536 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002537 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 ActivityStack stack = ActivityRecord.getStackLocked(token);
2539 if (stack != null) {
2540 return stack.willActivityBeVisibleLocked(token);
2541 }
2542 return false;
2543 }
2544 }
2545
2546 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002547 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002548 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 synchronized (mGlobalLock) {
2550 final long ident = Binder.clearCallingIdentity();
2551 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002552 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002553 if (task == null) {
2554 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2555 return;
2556 }
2557
2558 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2559 + " to stackId=" + stackId + " toTop=" + toTop);
2560
Wale Ogunwaled32da472018-11-16 07:19:28 -08002561 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002562 if (stack == null) {
2563 throw new IllegalStateException(
2564 "moveTaskToStack: No stack for stackId=" + stackId);
2565 }
2566 if (!stack.isActivityTypeStandardOrUndefined()) {
2567 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2568 + taskId + " to stack " + stackId);
2569 }
2570 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2573 }
2574 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2575 "moveTaskToStack");
2576 } finally {
2577 Binder.restoreCallingIdentity(ident);
2578 }
2579 }
2580 }
2581
2582 @Override
2583 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2584 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002585 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002586
2587 final long ident = Binder.clearCallingIdentity();
2588 try {
2589 synchronized (mGlobalLock) {
2590 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002591 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002592 if (stack == null) {
2593 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2594 return;
2595 }
2596 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2597 throw new IllegalArgumentException("Stack: " + stackId
2598 + " doesn't support animated resize.");
2599 }
2600 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2601 animationDuration, false /* fromFullscreen */);
2602 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002603 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002604 if (stack == null) {
2605 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2606 return;
2607 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002608 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002609 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2610 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2611 }
2612 }
2613 } finally {
2614 Binder.restoreCallingIdentity(ident);
2615 }
2616 }
2617
wilsonshih5c4cf522019-01-25 09:03:47 +08002618 @Override
2619 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2620 int animationDuration) {
2621 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2622
2623 final long ident = Binder.clearCallingIdentity();
2624 try {
2625 synchronized (mGlobalLock) {
2626 if (xOffset == 0 && yOffset == 0) {
2627 return;
2628 }
2629 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2630 if (stack == null) {
2631 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2632 return;
2633 }
2634 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2635 throw new IllegalArgumentException("Stack: " + stackId
2636 + " doesn't support animated resize.");
2637 }
2638 final Rect destBounds = new Rect();
2639 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002640 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002641 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2642 return;
2643 }
2644 destBounds.offset(xOffset, yOffset);
2645 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2646 animationDuration, false /* fromFullscreen */);
2647 }
2648 } finally {
2649 Binder.restoreCallingIdentity(ident);
2650 }
2651 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002652 /**
2653 * Moves the specified task to the primary-split-screen stack.
2654 *
2655 * @param taskId Id of task to move.
2656 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2657 * exist already. See
2658 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2659 * and
2660 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2661 * @param toTop If the task and stack should be moved to the top.
2662 * @param animate Whether we should play an animation for the moving the task.
2663 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2664 * stack. Pass {@code null} to use default bounds.
2665 * @param showRecents If the recents activity should be shown on the other side of the task
2666 * going into split-screen mode.
2667 */
2668 @Override
2669 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2670 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002671 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002672 "setTaskWindowingModeSplitScreenPrimary()");
2673 synchronized (mGlobalLock) {
2674 final long ident = Binder.clearCallingIdentity();
2675 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002676 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002677 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002678 if (task == null) {
2679 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2680 return false;
2681 }
2682 if (DEBUG_STACK) Slog.d(TAG_STACK,
2683 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2684 + " to createMode=" + createMode + " toTop=" + toTop);
2685 if (!task.isActivityTypeStandardOrUndefined()) {
2686 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2687 + " non-standard task " + taskId + " to split-screen windowing mode");
2688 }
2689
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002690 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002691 final int windowingMode = task.getWindowingMode();
2692 final ActivityStack stack = task.getStack();
2693 if (toTop) {
2694 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2695 }
2696 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002697 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2698 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002699 return windowingMode != task.getWindowingMode();
2700 } finally {
2701 Binder.restoreCallingIdentity(ident);
2702 }
2703 }
2704 }
2705
2706 /**
2707 * Removes stacks in the input windowing modes from the system if they are of activity type
2708 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2709 */
2710 @Override
2711 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002712 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002713 "removeStacksInWindowingModes()");
2714
2715 synchronized (mGlobalLock) {
2716 final long ident = Binder.clearCallingIdentity();
2717 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002718 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002719 } finally {
2720 Binder.restoreCallingIdentity(ident);
2721 }
2722 }
2723 }
2724
2725 @Override
2726 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002727 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002728 "removeStacksWithActivityTypes()");
2729
2730 synchronized (mGlobalLock) {
2731 final long ident = Binder.clearCallingIdentity();
2732 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002733 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002734 } finally {
2735 Binder.restoreCallingIdentity(ident);
2736 }
2737 }
2738 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002739
2740 @Override
2741 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2742 int userId) {
2743 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002744 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2745 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002746 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002747 final boolean detailed = checkGetTasksPermission(
2748 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2749 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 == PackageManager.PERMISSION_GRANTED;
2751
2752 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002753 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002754 callingUid);
2755 }
2756 }
2757
2758 @Override
2759 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002760 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 long ident = Binder.clearCallingIdentity();
2762 try {
2763 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002764 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 }
2766 } finally {
2767 Binder.restoreCallingIdentity(ident);
2768 }
2769 }
2770
2771 @Override
2772 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002773 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 long ident = Binder.clearCallingIdentity();
2775 try {
2776 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002777 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002778 }
2779 } finally {
2780 Binder.restoreCallingIdentity(ident);
2781 }
2782 }
2783
2784 @Override
2785 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002786 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 final long callingUid = Binder.getCallingUid();
2788 final long origId = Binder.clearCallingIdentity();
2789 try {
2790 synchronized (mGlobalLock) {
2791 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002792 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002793 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2794 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(origId);
2798 }
2799 }
2800
2801 @Override
2802 public void startLockTaskModeByToken(IBinder token) {
2803 synchronized (mGlobalLock) {
2804 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2805 if (r == null) {
2806 return;
2807 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002808 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810 }
2811
2812 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002813 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002814 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 // This makes inner call to look as if it was initiated by system.
2816 long ident = Binder.clearCallingIdentity();
2817 try {
2818 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002819 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002820 MATCH_TASK_IN_STACKS_ONLY);
2821 if (task == null) {
2822 return;
2823 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002824
2825 // When starting lock task mode the stack must be in front and focused
2826 task.getStack().moveToFront("startSystemLockTaskMode");
2827 startLockTaskModeLocked(task, true /* isSystemCaller */);
2828 }
2829 } finally {
2830 Binder.restoreCallingIdentity(ident);
2831 }
2832 }
2833
2834 @Override
2835 public void stopLockTaskModeByToken(IBinder token) {
2836 synchronized (mGlobalLock) {
2837 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2838 if (r == null) {
2839 return;
2840 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002841 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002842 }
2843 }
2844
2845 /**
2846 * This API should be called by SystemUI only when user perform certain action to dismiss
2847 * lock task mode. We should only dismiss pinned lock task mode in this case.
2848 */
2849 @Override
2850 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002851 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2853 }
2854
2855 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2856 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2857 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2858 return;
2859 }
2860
Wale Ogunwaled32da472018-11-16 07:19:28 -08002861 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002862 if (stack == null || task != stack.topTask()) {
2863 throw new IllegalArgumentException("Invalid task, not in foreground");
2864 }
2865
2866 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2867 // system or a specific app.
2868 // * System-initiated requests will only start the pinned mode (screen pinning)
2869 // * App-initiated requests
2870 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2871 // - will start the pinned mode, otherwise
2872 final int callingUid = Binder.getCallingUid();
2873 long ident = Binder.clearCallingIdentity();
2874 try {
2875 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002876 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002878 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 } finally {
2880 Binder.restoreCallingIdentity(ident);
2881 }
2882 }
2883
2884 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2885 final int callingUid = Binder.getCallingUid();
2886 long ident = Binder.clearCallingIdentity();
2887 try {
2888 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002889 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002890 }
2891 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2892 // task and jumping straight into a call in the case of emergency call back.
2893 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2894 if (tm != null) {
2895 tm.showInCallScreen(false);
2896 }
2897 } finally {
2898 Binder.restoreCallingIdentity(ident);
2899 }
2900 }
2901
2902 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002903 public void updateLockTaskPackages(int userId, String[] packages) {
2904 final int callingUid = Binder.getCallingUid();
2905 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2906 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2907 "updateLockTaskPackages()");
2908 }
2909 synchronized (this) {
2910 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2911 + Arrays.toString(packages));
2912 getLockTaskController().updateLockTaskPackages(userId, packages);
2913 }
2914 }
2915
2916 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 public boolean isInLockTaskMode() {
2918 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2919 }
2920
2921 @Override
2922 public int getLockTaskModeState() {
2923 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002924 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 }
2926 }
2927
2928 @Override
2929 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2930 synchronized (mGlobalLock) {
2931 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2932 if (r != null) {
2933 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002934 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002936 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 }
2938 }
2939 }
2940
2941 @Override
2942 public Bundle getActivityOptions(IBinder token) {
2943 final long origId = Binder.clearCallingIdentity();
2944 try {
2945 synchronized (mGlobalLock) {
2946 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2947 if (r != null) {
Jorim Jaggi346702a2019-05-08 17:49:33 +02002948 final ActivityOptions activityOptions = r.takeOptionsLocked(
2949 true /* fromClient */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002950 return activityOptions == null ? null : activityOptions.toBundle();
2951 }
2952 return null;
2953 }
2954 } finally {
2955 Binder.restoreCallingIdentity(origId);
2956 }
2957 }
2958
2959 @Override
2960 public List<IBinder> getAppTasks(String callingPackage) {
2961 int callingUid = Binder.getCallingUid();
2962 long ident = Binder.clearCallingIdentity();
2963 try {
2964 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002965 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002966 }
2967 } finally {
2968 Binder.restoreCallingIdentity(ident);
2969 }
2970 }
2971
2972 @Override
2973 public void finishVoiceTask(IVoiceInteractionSession session) {
2974 synchronized (mGlobalLock) {
2975 final long origId = Binder.clearCallingIdentity();
2976 try {
2977 // TODO: VI Consider treating local voice interactions and voice tasks
2978 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002979 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 } finally {
2981 Binder.restoreCallingIdentity(origId);
2982 }
2983 }
2984
2985 }
2986
2987 @Override
2988 public boolean isTopOfTask(IBinder token) {
2989 synchronized (mGlobalLock) {
2990 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002991 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void notifyLaunchTaskBehindComplete(IBinder token) {
2997 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2998 }
2999
3000 @Override
3001 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003002 mH.post(() -> {
3003 synchronized (mGlobalLock) {
3004 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003005 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003006 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003007 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003008 } catch (RemoteException e) {
3009 }
3010 }
3011 }
3012
3013 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 }
3015
3016 /** Called from an app when assist data is ready. */
3017 @Override
3018 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
3019 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003020 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 synchronized (pae) {
3022 pae.result = extras;
3023 pae.structure = structure;
3024 pae.content = content;
3025 if (referrer != null) {
3026 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
3027 }
3028 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07003029 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003030 structure.setTaskId(pae.activity.getTaskRecord().taskId);
3031 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 structure.setHomeActivity(pae.isHome);
3033 }
3034 pae.haveResult = true;
3035 pae.notifyAll();
3036 if (pae.intent == null && pae.receiver == null) {
3037 // Caller is just waiting for the result.
3038 return;
3039 }
3040 }
3041 // We are now ready to launch the assist activity.
3042 IAssistDataReceiver sendReceiver = null;
3043 Bundle sendBundle = null;
3044 synchronized (mGlobalLock) {
3045 buildAssistBundleLocked(pae, extras);
3046 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003047 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003048 if (!exists) {
3049 // Timed out.
3050 return;
3051 }
3052
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003053 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003054 // Caller wants result sent back to them.
3055 sendBundle = new Bundle();
Sunny Goyald40c3452019-03-20 12:46:55 -07003056 sendBundle.putInt(ActivityTaskManagerInternal.ASSIST_TASK_ID,
3057 pae.activity.getTaskRecord().taskId);
3058 sendBundle.putBinder(ActivityTaskManagerInternal.ASSIST_ACTIVITY_ID,
3059 pae.activity.assistToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
3061 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
3062 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
3063 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3064 }
3065 }
3066 if (sendReceiver != null) {
3067 try {
3068 sendReceiver.onHandleAssistData(sendBundle);
3069 } catch (RemoteException e) {
3070 }
3071 return;
3072 }
3073
3074 final long ident = Binder.clearCallingIdentity();
3075 try {
3076 if (TextUtils.equals(pae.intent.getAction(),
3077 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
Galia Peychevabffbfc32019-06-18 10:11:35 +02003078 // Start voice interaction through VoiceInteractionManagerService.
3079 mAssistUtils.showSessionForActiveService(sendBundle, SHOW_SOURCE_APPLICATION,
3080 null, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003081 } else {
3082 pae.intent.replaceExtras(pae.extras);
3083 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
3084 | Intent.FLAG_ACTIVITY_SINGLE_TOP
3085 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07003086 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003087
3088 try {
3089 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
3090 } catch (ActivityNotFoundException e) {
3091 Slog.w(TAG, "No activity to handle assist action.", e);
3092 }
3093 }
3094 } finally {
3095 Binder.restoreCallingIdentity(ident);
3096 }
3097 }
3098
3099 @Override
3100 public int addAppTask(IBinder activityToken, Intent intent,
3101 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3102 final int callingUid = Binder.getCallingUid();
3103 final long callingIdent = Binder.clearCallingIdentity();
3104
3105 try {
3106 synchronized (mGlobalLock) {
3107 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3108 if (r == null) {
3109 throw new IllegalArgumentException("Activity does not exist; token="
3110 + activityToken);
3111 }
3112 ComponentName comp = intent.getComponent();
3113 if (comp == null) {
3114 throw new IllegalArgumentException("Intent " + intent
3115 + " must specify explicit component");
3116 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003117 if (thumbnail.getWidth() != mThumbnailWidth
3118 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003119 throw new IllegalArgumentException("Bad thumbnail size: got "
3120 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003121 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003122 }
3123 if (intent.getSelector() != null) {
3124 intent.setSelector(null);
3125 }
3126 if (intent.getSourceBounds() != null) {
3127 intent.setSourceBounds(null);
3128 }
3129 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3130 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3131 // The caller has added this as an auto-remove task... that makes no
3132 // sense, so turn off auto-remove.
3133 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3134 }
3135 }
3136 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3137 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3138 if (ainfo.applicationInfo.uid != callingUid) {
3139 throw new SecurityException(
3140 "Can't add task for another application: target uid="
3141 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3142 }
3143
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003144 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003146 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003148 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 // The app has too many tasks already and we can't add any more
3150 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3151 return INVALID_TASK_ID;
3152 }
3153 task.lastTaskDescription.copyFrom(description);
3154
3155 // TODO: Send the thumbnail to WM to store it.
3156
3157 return task.taskId;
3158 }
3159 } finally {
3160 Binder.restoreCallingIdentity(callingIdent);
3161 }
3162 }
3163
3164 @Override
3165 public Point getAppTaskThumbnailSize() {
3166 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003167 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003168 }
3169 }
3170
3171 @Override
3172 public void setTaskResizeable(int taskId, int resizeableMode) {
3173 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003174 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003175 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3176 if (task == null) {
3177 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3178 return;
3179 }
3180 task.setResizeMode(resizeableMode);
3181 }
3182 }
3183
3184 @Override
3185 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003186 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 long ident = Binder.clearCallingIdentity();
3188 try {
3189 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003190 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003191 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003192 if (task == null) {
3193 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3194 return;
3195 }
3196 // Place the task in the right stack if it isn't there already based on
3197 // the requested bounds.
3198 // The stack transition logic is:
3199 // - a null bounds on a freeform task moves that task to fullscreen
3200 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3201 // that task to freeform
3202 // - otherwise the task is not moved
3203 ActivityStack stack = task.getStack();
3204 if (!task.getWindowConfiguration().canResizeTask()) {
3205 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3206 }
3207 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3208 stack = stack.getDisplay().getOrCreateStack(
3209 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3210 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3211 stack = stack.getDisplay().getOrCreateStack(
3212 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3213 }
3214
3215 // Reparent the task to the right stack if necessary
3216 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3217 if (stack != task.getStack()) {
3218 // Defer resume until the task is resized below
3219 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3220 DEFER_RESUME, "resizeTask");
3221 preserveWindow = false;
3222 }
3223
3224 // After reparenting (which only resizes the task to the stack bounds), resize the
3225 // task to the actual bounds provided
3226 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3227 }
3228 } finally {
3229 Binder.restoreCallingIdentity(ident);
3230 }
3231 }
3232
3233 @Override
3234 public boolean releaseActivityInstance(IBinder token) {
3235 synchronized (mGlobalLock) {
3236 final long origId = Binder.clearCallingIdentity();
3237 try {
3238 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3239 if (r == null) {
3240 return false;
3241 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003242 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 } finally {
3244 Binder.restoreCallingIdentity(origId);
3245 }
3246 }
3247 }
3248
3249 @Override
3250 public void releaseSomeActivities(IApplicationThread appInt) {
3251 synchronized (mGlobalLock) {
3252 final long origId = Binder.clearCallingIdentity();
3253 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003254 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003255 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003256 } finally {
3257 Binder.restoreCallingIdentity(origId);
3258 }
3259 }
3260 }
3261
3262 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003263 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003264 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003265 != PackageManager.PERMISSION_GRANTED) {
3266 throw new SecurityException("Requires permission "
3267 + android.Manifest.permission.DEVICE_POWER);
3268 }
3269
3270 synchronized (mGlobalLock) {
3271 long ident = Binder.clearCallingIdentity();
3272 if (mKeyguardShown != keyguardShowing) {
3273 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003274 final Message msg = PooledLambda.obtainMessage(
3275 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3276 keyguardShowing);
3277 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003278 }
3279 try {
wilsonshih177261f2019-02-22 12:02:18 +08003280 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003281 } finally {
3282 Binder.restoreCallingIdentity(ident);
3283 }
3284 }
3285
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003286 mH.post(() -> {
3287 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3288 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3289 }
3290 });
3291 }
3292
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003293 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003294 mH.post(() -> {
3295 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3296 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3297 }
3298 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 }
3300
3301 @Override
3302 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003303 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3304 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003305
3306 final File passedIconFile = new File(filePath);
3307 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3308 passedIconFile.getName());
3309 if (!legitIconFile.getPath().equals(filePath)
3310 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3311 throw new IllegalArgumentException("Bad file path: " + filePath
3312 + " passed for userId " + userId);
3313 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003314 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 }
3316
3317 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003318 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3320 final ActivityOptions activityOptions = safeOptions != null
3321 ? safeOptions.getOptions(mStackSupervisor)
3322 : null;
3323 if (activityOptions == null
3324 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3325 || activityOptions.getCustomInPlaceResId() == 0) {
3326 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3327 "with valid animation");
3328 }
lumark588a3e82018-07-20 18:53:54 +08003329 // Get top display of front most application.
3330 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3331 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003332 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3333 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3334 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003335 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003336 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003337 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003338 }
3339
3340 @Override
3341 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003342 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 synchronized (mGlobalLock) {
3344 final long ident = Binder.clearCallingIdentity();
3345 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003346 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003347 if (stack == null) {
3348 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3349 return;
3350 }
3351 if (!stack.isActivityTypeStandardOrUndefined()) {
3352 throw new IllegalArgumentException(
3353 "Removing non-standard stack is not allowed.");
3354 }
3355 mStackSupervisor.removeStack(stack);
3356 } finally {
3357 Binder.restoreCallingIdentity(ident);
3358 }
3359 }
3360 }
3361
3362 @Override
3363 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003364 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365
3366 synchronized (mGlobalLock) {
3367 final long ident = Binder.clearCallingIdentity();
3368 try {
3369 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3370 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003371 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 } finally {
3373 Binder.restoreCallingIdentity(ident);
3374 }
3375 }
3376 }
3377
3378 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003379 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380 synchronized (mGlobalLock) {
3381 long ident = Binder.clearCallingIdentity();
3382 try {
3383 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3384 if (r == null) {
3385 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003386 "toggleFreeformWindowingMode: No activity record matching token="
3387 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003388 }
3389
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003390 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003391 if (stack == null) {
3392 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3393 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003394 }
3395
Yunfan Chend967af82019-01-17 18:30:18 +09003396 if (!stack.inFreeformWindowingMode()
3397 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3398 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3399 + "toggle between fullscreen and freeform.");
3400 }
3401
3402 if (stack.inFreeformWindowingMode()) {
3403 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
Yunfan Chene9c1c312019-04-18 14:49:15 +09003404 } else if (stack.getParent().inFreeformWindowingMode()) {
3405 // If the window is on a freeform display, set it to undefined. It will be
3406 // resolved to freeform and it can adjust windowing mode when the display mode
3407 // changes in runtime.
3408 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Yunfan Chend967af82019-01-17 18:30:18 +09003409 } else {
3410 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3411 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003412 } finally {
3413 Binder.restoreCallingIdentity(ident);
3414 }
3415 }
3416 }
3417
3418 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3419 @Override
3420 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003421 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003423 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 }
3425
3426 /** Unregister a task stack listener so that it stops receiving callbacks. */
3427 @Override
3428 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003429 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003430 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003431 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003434 @Override
3435 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3436 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3437 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3438 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3439 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3440 }
3441
3442 @Override
3443 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3444 IBinder activityToken, int flags) {
3445 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3446 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3447 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3448 }
3449
3450 @Override
3451 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3452 Bundle args) {
3453 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3454 true /* focused */, true /* newSessionId */, userHandle, args,
3455 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3456 }
3457
3458 @Override
3459 public Bundle getAssistContextExtras(int requestType) {
3460 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3461 null, null, true /* focused */, true /* newSessionId */,
3462 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3463 if (pae == null) {
3464 return null;
3465 }
3466 synchronized (pae) {
3467 while (!pae.haveResult) {
3468 try {
3469 pae.wait();
3470 } catch (InterruptedException e) {
3471 }
3472 }
3473 }
3474 synchronized (mGlobalLock) {
3475 buildAssistBundleLocked(pae, pae.result);
3476 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003477 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 }
3479 return pae.extras;
3480 }
3481
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003482 /**
3483 * Binder IPC calls go through the public entry point.
3484 * This can be called with or without the global lock held.
3485 */
3486 private static int checkCallingPermission(String permission) {
3487 return checkPermission(
3488 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3489 }
3490
3491 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003492 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003493 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3494 mAmInternal.enforceCallingPermission(permission, func);
3495 }
3496 }
3497
3498 @VisibleForTesting
3499 int checkGetTasksPermission(String permission, int pid, int uid) {
3500 return checkPermission(permission, pid, uid);
3501 }
3502
3503 static int checkPermission(String permission, int pid, int uid) {
3504 if (permission == null) {
3505 return PackageManager.PERMISSION_DENIED;
3506 }
3507 return checkComponentPermission(permission, pid, uid, -1, true);
3508 }
3509
Wale Ogunwale214f3482018-10-04 11:00:47 -07003510 public static int checkComponentPermission(String permission, int pid, int uid,
3511 int owningUid, boolean exported) {
3512 return ActivityManagerService.checkComponentPermission(
3513 permission, pid, uid, owningUid, exported);
3514 }
3515
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003516 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3517 if (getRecentTasks().isCallerRecents(callingUid)) {
3518 // Always allow the recents component to get tasks
3519 return true;
3520 }
3521
3522 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3523 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3524 if (!allowed) {
3525 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3526 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3527 // Temporary compatibility: some existing apps on the system image may
3528 // still be requesting the old permission and not switched to the new
3529 // one; if so, we'll still allow them full access. This means we need
3530 // to see if they are holding the old permission and are a system app.
3531 try {
3532 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3533 allowed = true;
3534 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3535 + " is using old GET_TASKS but privileged; allowing");
3536 }
3537 } catch (RemoteException e) {
3538 }
3539 }
3540 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3541 + " does not hold REAL_GET_TASKS; limiting output");
3542 }
3543 return allowed;
3544 }
3545
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003546 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3547 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3548 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3549 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003550 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003551 "enqueueAssistContext()");
3552
3553 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003554 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 if (activity == null) {
3556 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3557 return null;
3558 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003559 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003560 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3561 return null;
3562 }
3563 if (focused) {
3564 if (activityToken != null) {
3565 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3566 if (activity != caller) {
3567 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3568 + " is not current top " + activity);
3569 return null;
3570 }
3571 }
3572 } else {
3573 activity = ActivityRecord.forTokenLocked(activityToken);
3574 if (activity == null) {
3575 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3576 + " couldn't be found");
3577 return null;
3578 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003579 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003580 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3581 return null;
3582 }
3583 }
3584
3585 PendingAssistExtras pae;
3586 Bundle extras = new Bundle();
3587 if (args != null) {
3588 extras.putAll(args);
3589 }
3590 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003591 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003592
3593 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3594 userHandle);
3595 pae.isHome = activity.isActivityTypeHome();
3596
3597 // Increment the sessionId if necessary
3598 if (newSessionId) {
3599 mViSessionId++;
3600 }
3601 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003602 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3603 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003604 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003605 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 } catch (RemoteException e) {
3607 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3608 return null;
3609 }
3610 return pae;
3611 }
3612 }
3613
3614 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3615 if (result != null) {
3616 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3617 }
3618 if (pae.hint != null) {
3619 pae.extras.putBoolean(pae.hint, true);
3620 }
3621 }
3622
3623 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3624 IAssistDataReceiver receiver;
3625 synchronized (mGlobalLock) {
3626 mPendingAssistExtras.remove(pae);
3627 receiver = pae.receiver;
3628 }
3629 if (receiver != null) {
3630 // Caller wants result sent back to them.
3631 Bundle sendBundle = new Bundle();
3632 // At least return the receiver extras
3633 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3634 try {
3635 pae.receiver.onHandleAssistData(sendBundle);
3636 } catch (RemoteException e) {
3637 }
3638 }
3639 }
3640
3641 public class PendingAssistExtras extends Binder implements Runnable {
3642 public final ActivityRecord activity;
3643 public boolean isHome;
3644 public final Bundle extras;
3645 public final Intent intent;
3646 public final String hint;
3647 public final IAssistDataReceiver receiver;
3648 public final int userHandle;
3649 public boolean haveResult = false;
3650 public Bundle result = null;
3651 public AssistStructure structure = null;
3652 public AssistContent content = null;
3653 public Bundle receiverExtras;
3654
3655 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3656 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3657 int _userHandle) {
3658 activity = _activity;
3659 extras = _extras;
3660 intent = _intent;
3661 hint = _hint;
3662 receiver = _receiver;
3663 receiverExtras = _receiverExtras;
3664 userHandle = _userHandle;
3665 }
3666
3667 @Override
3668 public void run() {
3669 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3670 synchronized (this) {
3671 haveResult = true;
3672 notifyAll();
3673 }
3674 pendingAssistExtrasTimedOut(this);
3675 }
3676 }
3677
3678 @Override
3679 public boolean isAssistDataAllowedOnCurrentActivity() {
3680 int userId;
3681 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003682 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003683 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3684 return false;
3685 }
3686
3687 final ActivityRecord activity = focusedStack.getTopActivity();
3688 if (activity == null) {
3689 return false;
3690 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003691 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003692 }
3693 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3694 }
3695
3696 @Override
3697 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3698 long ident = Binder.clearCallingIdentity();
3699 try {
3700 synchronized (mGlobalLock) {
3701 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003702 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003703 if (top != caller) {
3704 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3705 + " is not current top " + top);
3706 return false;
3707 }
3708 if (!top.nowVisible) {
3709 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3710 + " is not visible");
3711 return false;
3712 }
3713 }
3714 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3715 token);
3716 } finally {
3717 Binder.restoreCallingIdentity(ident);
3718 }
3719 }
3720
3721 @Override
3722 public boolean isRootVoiceInteraction(IBinder token) {
3723 synchronized (mGlobalLock) {
3724 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3725 if (r == null) {
3726 return false;
3727 }
3728 return r.rootVoiceInteraction;
3729 }
3730 }
3731
Wale Ogunwalef6733932018-06-27 05:14:34 -07003732 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3733 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3734 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3735 if (activityToCallback == null) return;
3736 activityToCallback.setVoiceSessionLocked(voiceSession);
3737
3738 // Inform the activity
3739 try {
3740 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3741 voiceInteractor);
3742 long token = Binder.clearCallingIdentity();
3743 try {
Andrii Kulianeceebbf2019-06-26 17:36:51 -07003744 startRunningVoiceLocked(voiceSession, activityToCallback.info.applicationInfo.uid);
Wale Ogunwalef6733932018-06-27 05:14:34 -07003745 } finally {
3746 Binder.restoreCallingIdentity(token);
3747 }
3748 // TODO: VI Should we cache the activity so that it's easier to find later
3749 // rather than scan through all the stacks and activities?
3750 } catch (RemoteException re) {
3751 activityToCallback.clearVoiceSessionLocked();
3752 // TODO: VI Should this terminate the voice session?
3753 }
3754 }
3755
3756 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3757 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3758 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3759 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3760 boolean wasRunningVoice = mRunningVoice != null;
3761 mRunningVoice = session;
3762 if (!wasRunningVoice) {
3763 mVoiceWakeLock.acquire();
3764 updateSleepIfNeededLocked();
3765 }
3766 }
3767 }
3768
3769 void finishRunningVoiceLocked() {
3770 if (mRunningVoice != null) {
3771 mRunningVoice = null;
3772 mVoiceWakeLock.release();
3773 updateSleepIfNeededLocked();
3774 }
3775 }
3776
3777 @Override
3778 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3779 synchronized (mGlobalLock) {
3780 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3781 if (keepAwake) {
3782 mVoiceWakeLock.acquire();
3783 } else {
3784 mVoiceWakeLock.release();
3785 }
3786 }
3787 }
3788 }
3789
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003790 @Override
3791 public ComponentName getActivityClassForToken(IBinder token) {
3792 synchronized (mGlobalLock) {
3793 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3794 if (r == null) {
3795 return null;
3796 }
3797 return r.intent.getComponent();
3798 }
3799 }
3800
3801 @Override
3802 public String getPackageForToken(IBinder token) {
3803 synchronized (mGlobalLock) {
3804 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3805 if (r == null) {
3806 return null;
3807 }
3808 return r.packageName;
3809 }
3810 }
3811
3812 @Override
3813 public void showLockTaskEscapeMessage(IBinder token) {
3814 synchronized (mGlobalLock) {
3815 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3816 if (r == null) {
3817 return;
3818 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003819 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003820 }
3821 }
3822
3823 @Override
3824 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003825 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003826 final long token = Binder.clearCallingIdentity();
3827 try {
3828 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003829 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003830 }
3831 } finally {
3832 Binder.restoreCallingIdentity(token);
3833 }
3834 }
3835
3836 /**
3837 * Try to place task to provided position. The final position might be different depending on
3838 * current user and stacks state. The task will be moved to target stack if it's currently in
3839 * different stack.
3840 */
3841 @Override
3842 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003843 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003844 synchronized (mGlobalLock) {
3845 long ident = Binder.clearCallingIdentity();
3846 try {
3847 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3848 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003849 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 if (task == null) {
3851 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3852 + taskId);
3853 }
3854
Wale Ogunwaled32da472018-11-16 07:19:28 -08003855 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003856
3857 if (stack == null) {
3858 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3859 + stackId);
3860 }
3861 if (!stack.isActivityTypeStandardOrUndefined()) {
3862 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3863 + " the position of task " + taskId + " in/to non-standard stack");
3864 }
3865
3866 // TODO: Have the callers of this API call a separate reparent method if that is
3867 // what they intended to do vs. having this method also do reparenting.
3868 if (task.getStack() == stack) {
3869 // Change position in current stack.
3870 stack.positionChildAt(task, position);
3871 } else {
3872 // Reparent to new stack.
3873 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3874 !DEFER_RESUME, "positionTaskInStack");
3875 }
3876 } finally {
3877 Binder.restoreCallingIdentity(ident);
3878 }
3879 }
3880 }
3881
3882 @Override
3883 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3884 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3885 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
Yuichiro Hanadae7e930b2019-06-06 19:07:21 +09003886 + Arrays.toString(horizontalSizeConfiguration) + " "
3887 + Arrays.toString(verticalSizeConfigurations));
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 synchronized (mGlobalLock) {
3889 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3890 if (record == null) {
3891 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3892 + "found for: " + token);
3893 }
3894 record.setSizeConfigurations(horizontalSizeConfiguration,
3895 verticalSizeConfigurations, smallestSizeConfigurations);
3896 }
3897 }
3898
3899 /**
3900 * Dismisses split-screen multi-window mode.
3901 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3902 */
3903 @Override
3904 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003905 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003906 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3907 final long ident = Binder.clearCallingIdentity();
3908 try {
3909 synchronized (mGlobalLock) {
3910 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003911 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 if (stack == null) {
3913 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3914 return;
3915 }
3916
3917 if (toTop) {
3918 // Caller wants the current split-screen primary stack to be the top stack after
3919 // it goes fullscreen, so move it to the front.
3920 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003921 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003922 // In this case the current split-screen primary stack shouldn't be the top
3923 // stack after it goes fullscreen, but it current has focus, so we move the
3924 // focus to the top-most split-screen secondary stack next to it.
3925 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3926 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3927 if (otherStack != null) {
3928 otherStack.moveToFront("dismissSplitScreenMode_other");
3929 }
3930 }
3931
Evan Rosky10475742018-09-05 19:02:48 -07003932 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 }
3934 } finally {
3935 Binder.restoreCallingIdentity(ident);
3936 }
3937 }
3938
3939 /**
3940 * Dismisses Pip
3941 * @param animate True if the dismissal should be animated.
3942 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3943 * default animation duration should be used.
3944 */
3945 @Override
3946 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003947 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 final long ident = Binder.clearCallingIdentity();
3949 try {
3950 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003951 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003952 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003953 if (stack == null) {
3954 Slog.w(TAG, "dismissPip: pinned stack not found.");
3955 return;
3956 }
3957 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3958 throw new IllegalArgumentException("Stack: " + stack
3959 + " doesn't support animated resize.");
3960 }
3961 if (animate) {
3962 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3963 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3964 } else {
3965 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3966 }
3967 }
3968 } finally {
3969 Binder.restoreCallingIdentity(ident);
3970 }
3971 }
3972
3973 @Override
3974 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003975 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 synchronized (mGlobalLock) {
3977 mSuppressResizeConfigChanges = suppress;
3978 }
3979 }
3980
3981 /**
3982 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3983 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3984 * activity and clearing the task at the same time.
3985 */
3986 @Override
3987 // TODO: API should just be about changing windowing modes...
3988 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003989 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003990 "moveTasksToFullscreenStack()");
3991 synchronized (mGlobalLock) {
3992 final long origId = Binder.clearCallingIdentity();
3993 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003994 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003995 if (stack != null){
3996 if (!stack.isActivityTypeStandardOrUndefined()) {
3997 throw new IllegalArgumentException(
3998 "You can't move tasks from non-standard stacks.");
3999 }
4000 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
4001 }
4002 } finally {
4003 Binder.restoreCallingIdentity(origId);
4004 }
4005 }
4006 }
4007
4008 /**
4009 * Moves the top activity in the input stackId to the pinned stack.
4010 *
4011 * @param stackId Id of stack to move the top activity to pinned stack.
4012 * @param bounds Bounds to use for pinned stack.
4013 *
4014 * @return True if the top activity of the input stack was successfully moved to the pinned
4015 * stack.
4016 */
4017 @Override
4018 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004019 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 "moveTopActivityToPinnedStack()");
4021 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004022 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 throw new IllegalStateException("moveTopActivityToPinnedStack:"
4024 + "Device doesn't support picture-in-picture mode");
4025 }
4026
4027 long ident = Binder.clearCallingIdentity();
4028 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004029 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004030 } finally {
4031 Binder.restoreCallingIdentity(ident);
4032 }
4033 }
4034 }
4035
4036 @Override
4037 public boolean isInMultiWindowMode(IBinder token) {
4038 final long origId = Binder.clearCallingIdentity();
4039 try {
4040 synchronized (mGlobalLock) {
4041 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4042 if (r == null) {
4043 return false;
4044 }
4045 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
4046 return r.inMultiWindowMode();
4047 }
4048 } finally {
4049 Binder.restoreCallingIdentity(origId);
4050 }
4051 }
4052
4053 @Override
4054 public boolean isInPictureInPictureMode(IBinder token) {
4055 final long origId = Binder.clearCallingIdentity();
4056 try {
4057 synchronized (mGlobalLock) {
4058 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
4059 }
4060 } finally {
4061 Binder.restoreCallingIdentity(origId);
4062 }
4063 }
4064
4065 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004066 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
4067 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 return false;
4069 }
4070
4071 // If we are animating to fullscreen then we have already dispatched the PIP mode
4072 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08004073 final TaskStack taskStack = r.getActivityStack().getTaskStack();
4074 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 }
4076
4077 @Override
4078 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
4079 final long origId = Binder.clearCallingIdentity();
4080 try {
4081 synchronized (mGlobalLock) {
4082 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4083 "enterPictureInPictureMode", token, params);
4084
4085 // If the activity is already in picture in picture mode, then just return early
4086 if (isInPictureInPictureMode(r)) {
4087 return true;
4088 }
4089
4090 // Activity supports picture-in-picture, now check that we can enter PiP at this
4091 // point, if it is
4092 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4093 false /* beforeStopping */)) {
4094 return false;
4095 }
4096
4097 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004098 synchronized (mGlobalLock) {
4099 // Only update the saved args from the args that are set
4100 r.pictureInPictureArgs.copyOnlySet(params);
4101 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4102 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4103 // Adjust the source bounds by the insets for the transition down
4104 final Rect sourceBounds = new Rect(
4105 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004106 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004107 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004108 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004109 stack.setPictureInPictureAspectRatio(aspectRatio);
4110 stack.setPictureInPictureActions(actions);
Andrii Kulianeceebbf2019-06-26 17:36:51 -07004111 MetricsLoggerWrapper.logPictureInPictureEnter(mContext,
4112 r.info.applicationInfo.uid, r.shortComponentName,
4113 r.supportsEnterPipOnTaskSwitch);
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004114 logPictureInPictureArgs(params);
4115 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 };
4117
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004118 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004119 // If the keyguard is showing or occluded, then try and dismiss it before
4120 // entering picture-in-picture (this will prompt the user to authenticate if the
4121 // device is currently locked).
4122 dismissKeyguard(token, new KeyguardDismissCallback() {
4123 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004124 public void onDismissSucceeded() {
4125 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004126 }
4127 }, null /* message */);
4128 } else {
4129 // Enter picture in picture immediately otherwise
4130 enterPipRunnable.run();
4131 }
4132 return true;
4133 }
4134 } finally {
4135 Binder.restoreCallingIdentity(origId);
4136 }
4137 }
4138
4139 @Override
4140 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4141 final long origId = Binder.clearCallingIdentity();
4142 try {
4143 synchronized (mGlobalLock) {
4144 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4145 "setPictureInPictureParams", token, params);
4146
4147 // Only update the saved args from the args that are set
4148 r.pictureInPictureArgs.copyOnlySet(params);
4149 if (r.inPinnedWindowingMode()) {
4150 // If the activity is already in picture-in-picture, update the pinned stack now
4151 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4152 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004153 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 if (!stack.isAnimatingBoundsToFullscreen()) {
4155 stack.setPictureInPictureAspectRatio(
4156 r.pictureInPictureArgs.getAspectRatio());
4157 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4158 }
4159 }
4160 logPictureInPictureArgs(params);
4161 }
4162 } finally {
4163 Binder.restoreCallingIdentity(origId);
4164 }
4165 }
4166
4167 @Override
4168 public int getMaxNumPictureInPictureActions(IBinder token) {
4169 // Currently, this is a static constant, but later, we may change this to be dependent on
4170 // the context of the activity
4171 return 3;
4172 }
4173
4174 private void logPictureInPictureArgs(PictureInPictureParams params) {
4175 if (params.hasSetActions()) {
4176 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4177 params.getActions().size());
4178 }
4179 if (params.hasSetAspectRatio()) {
4180 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4181 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4182 MetricsLogger.action(lm);
4183 }
4184 }
4185
4186 /**
4187 * Checks the state of the system and the activity associated with the given {@param token} to
4188 * verify that picture-in-picture is supported for that activity.
4189 *
4190 * @return the activity record for the given {@param token} if all the checks pass.
4191 */
4192 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4193 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004194 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004195 throw new IllegalStateException(caller
4196 + ": Device doesn't support picture-in-picture mode.");
4197 }
4198
4199 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4200 if (r == null) {
4201 throw new IllegalStateException(caller
4202 + ": Can't find activity for token=" + token);
4203 }
4204
4205 if (!r.supportsPictureInPicture()) {
4206 throw new IllegalStateException(caller
4207 + ": Current activity does not support picture-in-picture.");
4208 }
4209
4210 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004211 && !mWindowManager.isValidPictureInPictureAspectRatio(
4212 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004213 final float minAspectRatio = mContext.getResources().getFloat(
4214 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4215 final float maxAspectRatio = mContext.getResources().getFloat(
4216 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4217 throw new IllegalArgumentException(String.format(caller
4218 + ": Aspect ratio is too extreme (must be between %f and %f).",
4219 minAspectRatio, maxAspectRatio));
4220 }
4221
4222 // Truncate the number of actions if necessary
4223 params.truncateActions(getMaxNumPictureInPictureActions(token));
4224
4225 return r;
4226 }
4227
4228 @Override
4229 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004230 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004231 synchronized (mGlobalLock) {
4232 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4233 if (r == null) {
4234 throw new IllegalArgumentException("Activity does not exist; token="
4235 + activityToken);
4236 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004237 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004238 }
4239 }
4240
4241 @Override
4242 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4243 Rect tempDockedTaskInsetBounds,
4244 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004245 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 long ident = Binder.clearCallingIdentity();
4247 try {
4248 synchronized (mGlobalLock) {
4249 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4250 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4251 PRESERVE_WINDOWS);
4252 }
4253 } finally {
4254 Binder.restoreCallingIdentity(ident);
4255 }
4256 }
4257
4258 @Override
4259 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004260 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004261 final long ident = Binder.clearCallingIdentity();
4262 try {
4263 synchronized (mGlobalLock) {
4264 mStackSupervisor.setSplitScreenResizing(resizing);
4265 }
4266 } finally {
4267 Binder.restoreCallingIdentity(ident);
4268 }
4269 }
4270
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004271 /**
4272 * Check that we have the features required for VR-related API calls, and throw an exception if
4273 * not.
4274 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004275 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004276 if (!mContext.getPackageManager().hasSystemFeature(
4277 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4278 throw new UnsupportedOperationException("VR mode not supported on this device!");
4279 }
4280 }
4281
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004282 @Override
4283 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004284 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004285
4286 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4287
4288 ActivityRecord r;
4289 synchronized (mGlobalLock) {
4290 r = ActivityRecord.isInStackLocked(token);
4291 }
4292
4293 if (r == null) {
4294 throw new IllegalArgumentException();
4295 }
4296
4297 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004298 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 VrManagerInternal.NO_ERROR) {
4300 return err;
4301 }
4302
4303 // Clear the binder calling uid since this path may call moveToTask().
4304 final long callingId = Binder.clearCallingIdentity();
4305 try {
4306 synchronized (mGlobalLock) {
4307 r.requestedVrComponent = (enabled) ? packageName : null;
4308
4309 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004310 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004311 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 }
4313 return 0;
4314 }
4315 } finally {
4316 Binder.restoreCallingIdentity(callingId);
4317 }
4318 }
4319
4320 @Override
4321 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4322 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4323 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004324 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004325 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4326 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4327 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004328 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004329 || activity.voiceSession != null) {
4330 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4331 return;
4332 }
4333 if (activity.pendingVoiceInteractionStart) {
4334 Slog.w(TAG, "Pending start of voice interaction already.");
4335 return;
4336 }
4337 activity.pendingVoiceInteractionStart = true;
4338 }
4339 LocalServices.getService(VoiceInteractionManagerInternal.class)
4340 .startLocalVoiceInteraction(callingActivity, options);
4341 }
4342
4343 @Override
4344 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4345 LocalServices.getService(VoiceInteractionManagerInternal.class)
4346 .stopLocalVoiceInteraction(callingActivity);
4347 }
4348
4349 @Override
4350 public boolean supportsLocalVoiceInteraction() {
4351 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4352 .supportsLocalVoiceInteraction();
4353 }
4354
4355 /** Notifies all listeners when the pinned stack animation starts. */
4356 @Override
4357 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004358 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 }
4360
4361 /** Notifies all listeners when the pinned stack animation ends. */
4362 @Override
4363 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004364 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004365 }
4366
4367 @Override
4368 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004369 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 final long ident = Binder.clearCallingIdentity();
4371 try {
4372 synchronized (mGlobalLock) {
4373 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4374 }
4375 } finally {
4376 Binder.restoreCallingIdentity(ident);
4377 }
4378 }
4379
4380 @Override
4381 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004382 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004383
4384 synchronized (mGlobalLock) {
4385 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004386 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004387 // Call might come when display is not yet added or has already been removed.
4388 if (DEBUG_CONFIGURATION) {
4389 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4390 + displayId);
4391 }
4392 return false;
4393 }
4394
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004395 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004396 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004397 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004398 }
4399
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004401 final Message msg = PooledLambda.obtainMessage(
4402 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4403 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004404 }
4405
4406 final long origId = Binder.clearCallingIdentity();
4407 try {
4408 if (values != null) {
4409 Settings.System.clearConfiguration(values);
4410 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004411 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004412 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4413 return mTmpUpdateConfigurationResult.changes != 0;
4414 } finally {
4415 Binder.restoreCallingIdentity(origId);
4416 }
4417 }
4418 }
4419
4420 @Override
4421 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004422 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423
4424 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004425 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004427 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004428 }
4429
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004430 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004431 final Message msg = PooledLambda.obtainMessage(
4432 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4433 DEFAULT_DISPLAY);
4434 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 }
4436
4437 final long origId = Binder.clearCallingIdentity();
4438 try {
4439 if (values != null) {
4440 Settings.System.clearConfiguration(values);
4441 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004442 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004443 UserHandle.USER_NULL, false /* deferResume */,
4444 mTmpUpdateConfigurationResult);
4445 return mTmpUpdateConfigurationResult.changes != 0;
4446 } finally {
4447 Binder.restoreCallingIdentity(origId);
4448 }
4449 }
4450 }
4451
4452 @Override
4453 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4454 CharSequence message) {
4455 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004456 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004457 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4458 }
4459 final long callingId = Binder.clearCallingIdentity();
4460 try {
4461 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004462 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463 }
4464 } finally {
4465 Binder.restoreCallingIdentity(callingId);
4466 }
4467 }
4468
4469 @Override
4470 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004471 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004472 "cancelTaskWindowTransition()");
4473 final long ident = Binder.clearCallingIdentity();
4474 try {
4475 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004476 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004477 MATCH_TASK_IN_STACKS_ONLY);
4478 if (task == null) {
4479 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4480 return;
4481 }
4482 task.cancelWindowTransition();
4483 }
4484 } finally {
4485 Binder.restoreCallingIdentity(ident);
4486 }
4487 }
4488
4489 @Override
4490 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004491 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004492 final long ident = Binder.clearCallingIdentity();
4493 try {
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004494 return getTaskSnapshot(taskId, reducedResolution, true /* restoreFromDisk */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004495 } finally {
4496 Binder.restoreCallingIdentity(ident);
4497 }
4498 }
4499
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02004500 private ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution,
4501 boolean restoreFromDisk) {
4502 final TaskRecord task;
4503 synchronized (mGlobalLock) {
4504 task = mRootActivityContainer.anyTaskForId(taskId,
4505 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4506 if (task == null) {
4507 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4508 return null;
4509 }
4510 }
4511 // Don't call this while holding the lock as this operation might hit the disk.
4512 return task.getSnapshot(reducedResolution, restoreFromDisk);
4513 }
4514
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004515 @Override
4516 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4517 synchronized (mGlobalLock) {
4518 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4519 if (r == null) {
4520 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4521 + token);
4522 return;
4523 }
4524 final long origId = Binder.clearCallingIdentity();
4525 try {
4526 r.setDisablePreviewScreenshots(disable);
4527 } finally {
4528 Binder.restoreCallingIdentity(origId);
4529 }
4530 }
4531 }
4532
4533 /** Return the user id of the last resumed activity. */
4534 @Override
4535 public @UserIdInt
4536 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004537 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004538 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4539 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004540 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004541 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004542 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004543 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004544 }
4545 }
4546
4547 @Override
4548 public void updateLockTaskFeatures(int userId, int flags) {
4549 final int callingUid = Binder.getCallingUid();
4550 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004551 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004552 "updateLockTaskFeatures()");
4553 }
4554 synchronized (mGlobalLock) {
4555 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4556 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004557 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004558 }
4559 }
4560
4561 @Override
4562 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4563 synchronized (mGlobalLock) {
4564 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4565 if (r == null) {
4566 return;
4567 }
4568 final long origId = Binder.clearCallingIdentity();
4569 try {
4570 r.setShowWhenLocked(showWhenLocked);
4571 } finally {
4572 Binder.restoreCallingIdentity(origId);
4573 }
4574 }
4575 }
4576
4577 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004578 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4579 synchronized (mGlobalLock) {
4580 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4581 if (r == null) {
4582 return;
4583 }
4584 final long origId = Binder.clearCallingIdentity();
4585 try {
4586 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4587 } finally {
4588 Binder.restoreCallingIdentity(origId);
4589 }
4590 }
4591 }
4592
4593 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004594 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4595 synchronized (mGlobalLock) {
4596 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4597 if (r == null) {
4598 return;
4599 }
4600 final long origId = Binder.clearCallingIdentity();
4601 try {
4602 r.setTurnScreenOn(turnScreenOn);
4603 } finally {
4604 Binder.restoreCallingIdentity(origId);
4605 }
4606 }
4607 }
4608
4609 @Override
4610 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004611 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004612 "registerRemoteAnimations");
4613 definition.setCallingPid(Binder.getCallingPid());
4614 synchronized (mGlobalLock) {
4615 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4616 if (r == null) {
4617 return;
4618 }
4619 final long origId = Binder.clearCallingIdentity();
4620 try {
4621 r.registerRemoteAnimations(definition);
4622 } finally {
4623 Binder.restoreCallingIdentity(origId);
4624 }
4625 }
4626 }
4627
4628 @Override
4629 public void registerRemoteAnimationForNextActivityStart(String packageName,
4630 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004631 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004632 "registerRemoteAnimationForNextActivityStart");
4633 adapter.setCallingPid(Binder.getCallingPid());
4634 synchronized (mGlobalLock) {
4635 final long origId = Binder.clearCallingIdentity();
4636 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004637 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004638 packageName, adapter);
4639 } finally {
4640 Binder.restoreCallingIdentity(origId);
4641 }
4642 }
4643 }
4644
Evan Rosky966759f2019-01-15 10:33:58 -08004645 @Override
4646 public void registerRemoteAnimationsForDisplay(int displayId,
4647 RemoteAnimationDefinition definition) {
4648 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4649 "registerRemoteAnimations");
4650 definition.setCallingPid(Binder.getCallingPid());
4651 synchronized (mGlobalLock) {
4652 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4653 if (display == null) {
4654 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4655 return;
4656 }
4657 final long origId = Binder.clearCallingIdentity();
4658 try {
4659 display.mDisplayContent.registerRemoteAnimations(definition);
4660 } finally {
4661 Binder.restoreCallingIdentity(origId);
4662 }
4663 }
4664 }
4665
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004666 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4667 @Override
4668 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4669 synchronized (mGlobalLock) {
4670 final long origId = Binder.clearCallingIdentity();
4671 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004672 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004673 } finally {
4674 Binder.restoreCallingIdentity(origId);
4675 }
4676 }
4677 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004678
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004679 @Override
4680 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004681 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004682 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004683 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004684 final WindowProcessController wpc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004685 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004686 }
4687 }
4688
4689 @Override
4690 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004691 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004692 != PERMISSION_GRANTED) {
4693 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4694 + Binder.getCallingPid()
4695 + ", uid=" + Binder.getCallingUid()
4696 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4697 Slog.w(TAG, msg);
4698 throw new SecurityException(msg);
4699 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004700 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004701 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004702 final int pid = Binder.getCallingPid();
Michal Karpinski2e0aad22019-04-12 16:22:55 +01004703 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004704 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004705 }
4706 }
4707
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004708 @Override
4709 public void stopAppSwitches() {
4710 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4711 synchronized (mGlobalLock) {
4712 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
Ricky Wai906af482019-06-03 17:25:28 +01004713 mLastStopAppSwitchesTime = SystemClock.uptimeMillis();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004714 mDidAppSwitch = false;
4715 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4716 }
4717 }
4718
4719 @Override
4720 public void resumeAppSwitches() {
4721 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4722 synchronized (mGlobalLock) {
4723 // Note that we don't execute any pending app switches... we will
4724 // let those wait until either the timeout, or the next start
4725 // activity request.
4726 mAppSwitchesAllowedTime = 0;
4727 }
4728 }
4729
Ricky Wai906af482019-06-03 17:25:28 +01004730 long getLastStopAppSwitchesTime() {
4731 return mLastStopAppSwitchesTime;
4732 }
4733
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004734 void onStartActivitySetDidAppSwitch() {
4735 if (mDidAppSwitch) {
4736 // This is the second allowed switch since we stopped switches, so now just generally
4737 // allow switches. Use case:
4738 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4739 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4740 // anyone to switch again).
4741 mAppSwitchesAllowedTime = 0;
4742 } else {
4743 mDidAppSwitch = true;
4744 }
4745 }
4746
4747 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004748 boolean shouldDisableNonVrUiLocked() {
4749 return mVrController.shouldDisableNonVrUiLocked();
4750 }
4751
Wale Ogunwale53783742018-09-16 10:21:51 -07004752 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004753 // VR apps are expected to run in a main display. If an app is turning on VR for
4754 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4755 // fullscreen stack before enabling VR Mode.
4756 // TODO: The goal of this code is to keep the VR app on the main display. When the
4757 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4758 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4759 // option would be a better choice here.
4760 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4761 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4762 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004763 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004764 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004765 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004766 }
4767 mH.post(() -> {
4768 if (!mVrController.onVrModeChanged(r)) {
4769 return;
4770 }
4771 synchronized (mGlobalLock) {
4772 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4773 mWindowManager.disableNonVrUi(disableNonVrUi);
4774 if (disableNonVrUi) {
4775 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4776 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004777 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004778 }
4779 }
4780 });
4781 }
4782
Wale Ogunwale53783742018-09-16 10:21:51 -07004783 @Override
4784 public int getPackageScreenCompatMode(String packageName) {
4785 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4786 synchronized (mGlobalLock) {
4787 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4788 }
4789 }
4790
4791 @Override
4792 public void setPackageScreenCompatMode(String packageName, int mode) {
4793 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4794 "setPackageScreenCompatMode");
4795 synchronized (mGlobalLock) {
4796 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4797 }
4798 }
4799
4800 @Override
4801 public boolean getPackageAskScreenCompat(String packageName) {
4802 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4803 synchronized (mGlobalLock) {
4804 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4805 }
4806 }
4807
4808 @Override
4809 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4810 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4811 "setPackageAskScreenCompat");
4812 synchronized (mGlobalLock) {
4813 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4814 }
4815 }
4816
Wale Ogunwale64258362018-10-16 15:13:37 -07004817 public static String relaunchReasonToString(int relaunchReason) {
4818 switch (relaunchReason) {
4819 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4820 return "window_resize";
4821 case RELAUNCH_REASON_FREE_RESIZE:
4822 return "free_resize";
4823 default:
4824 return null;
4825 }
4826 }
4827
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004828 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004829 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004830 }
4831
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004832 /** Pokes the task persister. */
4833 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4834 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4835 }
4836
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004837 boolean isKeyguardLocked() {
4838 return mKeyguardController.isKeyguardLocked();
4839 }
4840
Garfield Tan01548632018-11-27 10:15:48 -08004841 /**
4842 * Clears launch params for the given package.
4843 * @param packageNames the names of the packages of which the launch params are to be cleared
4844 */
4845 @Override
4846 public void clearLaunchParamsForPackages(List<String> packageNames) {
4847 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4848 "clearLaunchParamsForPackages");
4849 synchronized (mGlobalLock) {
4850 for (int i = 0; i < packageNames.size(); ++i) {
4851 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4852 }
4853 }
4854 }
4855
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004856 /**
4857 * Makes the display with the given id a single task instance display. I.e the display can only
4858 * contain one task.
4859 */
4860 @Override
4861 public void setDisplayToSingleTaskInstance(int displayId) {
4862 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4863 "setDisplayToSingleTaskInstance");
4864 final long origId = Binder.clearCallingIdentity();
4865 try {
4866 final ActivityDisplay display =
4867 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4868 if (display != null) {
4869 display.setDisplayToSingleTaskInstance();
4870 }
4871 } finally {
4872 Binder.restoreCallingIdentity(origId);
4873 }
4874 }
4875
Wale Ogunwale31913b52018-10-13 08:29:31 -07004876 void dumpLastANRLocked(PrintWriter pw) {
4877 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4878 if (mLastANRState == null) {
4879 pw.println(" <no ANR has occurred since boot>");
4880 } else {
4881 pw.println(mLastANRState);
4882 }
4883 }
4884
4885 void dumpLastANRTracesLocked(PrintWriter pw) {
4886 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4887
4888 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4889 if (ArrayUtils.isEmpty(files)) {
4890 pw.println(" <no ANR has occurred since boot>");
4891 return;
4892 }
4893 // Find the latest file.
4894 File latest = null;
4895 for (File f : files) {
4896 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4897 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004898 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004899 }
4900 pw.print("File: ");
4901 pw.print(latest.getName());
4902 pw.println();
4903 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4904 String line;
4905 while ((line = in.readLine()) != null) {
4906 pw.println(line);
4907 }
4908 } catch (IOException e) {
4909 pw.print("Unable to read: ");
4910 pw.print(e);
4911 pw.println();
4912 }
4913 }
4914
4915 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4916 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4917 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4918 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4919 }
4920
4921 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4922 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4923 pw.println(header);
4924
Wale Ogunwaled32da472018-11-16 07:19:28 -08004925 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004926 dumpPackage);
4927 boolean needSep = printedAnything;
4928
4929 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004930 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004931 " ResumedActivity: ");
4932 if (printed) {
4933 printedAnything = true;
4934 needSep = false;
4935 }
4936
4937 if (dumpPackage == null) {
4938 if (needSep) {
4939 pw.println();
4940 }
4941 printedAnything = true;
4942 mStackSupervisor.dump(pw, " ");
4943 }
4944
4945 if (!printedAnything) {
4946 pw.println(" (nothing)");
4947 }
4948 }
4949
4950 void dumpActivityContainersLocked(PrintWriter pw) {
4951 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004952 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004953 pw.println(" ");
4954 }
4955
4956 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4957 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4958 getActivityStartController().dump(pw, "", dumpPackage);
4959 }
4960
4961 /**
4962 * There are three things that cmd can be:
4963 * - a flattened component name that matches an existing activity
4964 * - the cmd arg isn't the flattened component name of an existing activity:
4965 * dump all activity whose component contains the cmd as a substring
4966 * - A hex number of the ActivityRecord object instance.
4967 *
4968 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4969 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4970 */
4971 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4972 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4973 ArrayList<ActivityRecord> activities;
4974
4975 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004976 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004977 dumpFocusedStackOnly);
4978 }
4979
4980 if (activities.size() <= 0) {
4981 return false;
4982 }
4983
4984 String[] newArgs = new String[args.length - opti];
4985 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4986
4987 TaskRecord lastTask = null;
4988 boolean needSep = false;
4989 for (int i = activities.size() - 1; i >= 0; i--) {
4990 ActivityRecord r = activities.get(i);
4991 if (needSep) {
4992 pw.println();
4993 }
4994 needSep = true;
4995 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004996 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004997 if (lastTask != task) {
4998 lastTask = task;
4999 pw.print("TASK "); pw.print(lastTask.affinity);
5000 pw.print(" id="); pw.print(lastTask.taskId);
5001 pw.print(" userId="); pw.println(lastTask.userId);
5002 if (dumpAll) {
5003 lastTask.dump(pw, " ");
5004 }
5005 }
5006 }
5007 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
5008 }
5009 return true;
5010 }
5011
5012 /**
5013 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
5014 * there is a thread associated with the activity.
5015 */
5016 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
5017 final ActivityRecord r, String[] args, boolean dumpAll) {
5018 String innerPrefix = prefix + " ";
5019 synchronized (mGlobalLock) {
5020 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
5021 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
5022 pw.print(" pid=");
5023 if (r.hasProcess()) pw.println(r.app.getPid());
5024 else pw.println("(not running)");
5025 if (dumpAll) {
5026 r.dump(pw, innerPrefix);
5027 }
5028 }
5029 if (r.attachedToProcess()) {
5030 // flush anything that is already in the PrintWriter since the thread is going
5031 // to write to the file descriptor directly
5032 pw.flush();
5033 try {
5034 TransferPipe tp = new TransferPipe();
5035 try {
5036 r.app.getThread().dumpActivity(tp.getWriteFd(),
5037 r.appToken, innerPrefix, args);
5038 tp.go(fd);
5039 } finally {
5040 tp.kill();
5041 }
5042 } catch (IOException e) {
5043 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
5044 } catch (RemoteException e) {
5045 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
5046 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005047 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005048 }
5049
sanryhuang498e77e2018-12-06 14:57:01 +08005050 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
5051 boolean testPssMode) {
5052 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
5053 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
5054 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08005055 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005056 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
5057 st.toString());
5058 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005059 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
5060 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
5061 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08005062 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
5063 testPssMode);
5064 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005065 }
5066
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005067 int getCurrentUserId() {
5068 return mAmInternal.getCurrentUserId();
5069 }
5070
5071 private void enforceNotIsolatedCaller(String caller) {
5072 if (UserHandle.isIsolated(Binder.getCallingUid())) {
5073 throw new SecurityException("Isolated process not allowed to call " + caller);
5074 }
5075 }
5076
Wale Ogunwalef6733932018-06-27 05:14:34 -07005077 public Configuration getConfiguration() {
5078 Configuration ci;
5079 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005080 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07005081 ci.userSetLocale = false;
5082 }
5083 return ci;
5084 }
5085
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005086 /**
5087 * Current global configuration information. Contains general settings for the entire system,
5088 * also corresponds to the merged configuration of the default display.
5089 */
5090 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005091 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005092 }
5093
5094 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5095 boolean initLocale) {
5096 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5097 }
5098
5099 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5100 boolean initLocale, boolean deferResume) {
5101 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5102 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5103 UserHandle.USER_NULL, deferResume);
5104 }
5105
Wale Ogunwale59507092018-10-29 09:00:30 -07005106 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005107 final long origId = Binder.clearCallingIdentity();
5108 try {
5109 synchronized (mGlobalLock) {
5110 updateConfigurationLocked(values, null, false, true, userId,
5111 false /* deferResume */);
5112 }
5113 } finally {
5114 Binder.restoreCallingIdentity(origId);
5115 }
5116 }
5117
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005118 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5119 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5120 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5121 deferResume, null /* result */);
5122 }
5123
5124 /**
5125 * Do either or both things: (1) change the current configuration, and (2)
5126 * make sure the given activity is running with the (now) current
5127 * configuration. Returns true if the activity has been left running, or
5128 * false if <var>starting</var> is being destroyed to match the new
5129 * configuration.
5130 *
5131 * @param userId is only used when persistent parameter is set to true to persist configuration
5132 * for that particular user
5133 */
5134 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5135 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5136 ActivityTaskManagerService.UpdateConfigurationResult result) {
5137 int changes = 0;
5138 boolean kept = true;
5139
5140 if (mWindowManager != null) {
5141 mWindowManager.deferSurfaceLayout();
5142 }
5143 try {
5144 if (values != null) {
5145 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5146 deferResume);
5147 }
5148
5149 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5150 } finally {
5151 if (mWindowManager != null) {
5152 mWindowManager.continueSurfaceLayout();
5153 }
5154 }
5155
5156 if (result != null) {
5157 result.changes = changes;
5158 result.activityRelaunched = !kept;
5159 }
5160 return kept;
5161 }
5162
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005163 /** Update default (global) configuration and notify listeners about changes. */
5164 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5165 boolean persistent, int userId, boolean deferResume) {
5166 mTempConfig.setTo(getGlobalConfiguration());
5167 final int changes = mTempConfig.updateFrom(values);
5168 if (changes == 0) {
5169 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5170 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5171 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5172 // (even if there are no actual changes) to unfreeze the window.
5173 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5174 return 0;
5175 }
5176
5177 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5178 "Updating global configuration to: " + values);
5179
5180 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5181 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5182 values.colorMode,
5183 values.densityDpi,
5184 values.fontScale,
5185 values.hardKeyboardHidden,
5186 values.keyboard,
5187 values.keyboardHidden,
5188 values.mcc,
5189 values.mnc,
5190 values.navigation,
5191 values.navigationHidden,
5192 values.orientation,
5193 values.screenHeightDp,
5194 values.screenLayout,
5195 values.screenWidthDp,
5196 values.smallestScreenWidthDp,
5197 values.touchscreen,
5198 values.uiMode);
5199
5200
5201 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5202 final LocaleList locales = values.getLocales();
5203 int bestLocaleIndex = 0;
5204 if (locales.size() > 1) {
5205 if (mSupportedSystemLocales == null) {
5206 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5207 }
5208 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5209 }
5210 SystemProperties.set("persist.sys.locale",
5211 locales.get(bestLocaleIndex).toLanguageTag());
5212 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005213
5214 final Message m = PooledLambda.obtainMessage(
5215 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5216 locales.get(bestLocaleIndex));
5217 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005218 }
5219
Yunfan Chen75157d72018-07-27 14:47:21 +09005220 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005221
5222 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005223 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005224
5225 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5226 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005227 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005228
5229 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005230 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231
5232 AttributeCache ac = AttributeCache.instance();
5233 if (ac != null) {
5234 ac.updateConfiguration(mTempConfig);
5235 }
5236
5237 // Make sure all resources in our process are updated right now, so that anyone who is going
5238 // to retrieve resource values after we return will be sure to get the new ones. This is
5239 // especially important during boot, where the first config change needs to guarantee all
5240 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005241 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005242
5243 // We need another copy of global config because we're scheduling some calls instead of
5244 // running them in place. We need to be sure that object we send will be handled unchanged.
5245 final Configuration configCopy = new Configuration(mTempConfig);
5246 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005247 final Message msg = PooledLambda.obtainMessage(
5248 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5249 this, userId, configCopy);
5250 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005251 }
5252
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005253 SparseArray<WindowProcessController> pidMap = mProcessMap.getPidMap();
5254 for (int i = pidMap.size() - 1; i >= 0; i--) {
5255 final int pid = pidMap.keyAt(i);
5256 final WindowProcessController app = pidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005257 if (DEBUG_CONFIGURATION) {
5258 Slog.v(TAG_CONFIGURATION, "Update process config of "
5259 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005260 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005261 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005262 }
5263
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005264 final Message msg = PooledLambda.obtainMessage(
5265 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5266 mAmInternal, changes, initLocale);
5267 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005268
5269 // Override configuration of the default display duplicates global config, so we need to
5270 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005271 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005272 DEFAULT_DISPLAY);
5273
5274 return changes;
5275 }
5276
5277 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5278 boolean deferResume, int displayId) {
5279 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5280 displayId, null /* result */);
5281 }
5282
5283 /**
5284 * Updates override configuration specific for the selected display. If no config is provided,
5285 * new one will be computed in WM based on current display info.
5286 */
5287 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5288 ActivityRecord starting, boolean deferResume, int displayId,
5289 ActivityTaskManagerService.UpdateConfigurationResult result) {
5290 int changes = 0;
5291 boolean kept = true;
5292
5293 if (mWindowManager != null) {
5294 mWindowManager.deferSurfaceLayout();
5295 }
5296 try {
5297 if (values != null) {
5298 if (displayId == DEFAULT_DISPLAY) {
5299 // Override configuration of the default display duplicates global config, so
5300 // we're calling global config update instead for default display. It will also
5301 // apply the correct override config.
5302 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5303 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5304 } else {
5305 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5306 }
5307 }
5308
5309 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5310 } finally {
5311 if (mWindowManager != null) {
5312 mWindowManager.continueSurfaceLayout();
5313 }
5314 }
5315
5316 if (result != null) {
5317 result.changes = changes;
5318 result.activityRelaunched = !kept;
5319 }
5320 return kept;
5321 }
5322
5323 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5324 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005325 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005326 final int changes = mTempConfig.updateFrom(values);
5327 if (changes != 0) {
5328 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5329 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005330 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005331
5332 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5333 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005334 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005335
Wale Ogunwale5c918702018-10-18 11:06:33 -07005336 // Post message to start process to avoid possible deadlock of calling into AMS with
5337 // the ATMS lock held.
5338 final Message msg = PooledLambda.obtainMessage(
5339 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
Riddle Hsuaec55442019-03-12 17:25:35 +08005340 N, ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND);
Wale Ogunwale5c918702018-10-18 11:06:33 -07005341 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005342 }
5343 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005344 return changes;
5345 }
5346
Wale Ogunwalef6733932018-06-27 05:14:34 -07005347 private void updateEventDispatchingLocked(boolean booted) {
5348 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5349 }
5350
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005351 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5352 final ContentResolver resolver = mContext.getContentResolver();
5353 Settings.System.putConfigurationForUser(resolver, config, userId);
5354 }
5355
5356 private void sendLocaleToMountDaemonMsg(Locale l) {
5357 try {
5358 IBinder service = ServiceManager.getService("mount");
5359 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5360 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5361 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5362 } catch (RemoteException e) {
5363 Log.e(TAG, "Error storing locale for decryption UI", e);
5364 }
5365 }
5366
Alison Cichowlas3e340502018-08-07 17:15:01 -04005367 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5368 mStartActivitySources.remove(permissionToken);
5369 mExpiredStartAsCallerTokens.add(permissionToken);
5370 }
5371
5372 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5373 mExpiredStartAsCallerTokens.remove(permissionToken);
5374 }
5375
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005376 boolean isActivityStartsLoggingEnabled() {
5377 return mAmInternal.isActivityStartsLoggingEnabled();
5378 }
5379
Michal Karpinski8596ded2018-11-14 14:43:48 +00005380 boolean isBackgroundActivityStartsEnabled() {
5381 return mAmInternal.isBackgroundActivityStartsEnabled();
5382 }
5383
Wale Ogunwalef6733932018-06-27 05:14:34 -07005384 void enableScreenAfterBoot(boolean booted) {
5385 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5386 SystemClock.uptimeMillis());
5387 mWindowManager.enableScreenAfterBoot();
5388
5389 synchronized (mGlobalLock) {
5390 updateEventDispatchingLocked(booted);
5391 }
5392 }
5393
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005394 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5395 if (r == null || !r.hasProcess()) {
5396 return KEY_DISPATCHING_TIMEOUT_MS;
5397 }
5398 return getInputDispatchingTimeoutLocked(r.app);
5399 }
5400
5401 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005402 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005403 }
5404
Wale Ogunwalef6733932018-06-27 05:14:34 -07005405 /**
5406 * Decide based on the configuration whether we should show the ANR,
5407 * crash, etc dialogs. The idea is that if there is no affordance to
5408 * press the on-screen buttons, or the user experience would be more
5409 * greatly impacted than the crash itself, we shouldn't show the dialog.
5410 *
5411 * A thought: SystemUI might also want to get told about this, the Power
5412 * dialog / global actions also might want different behaviors.
5413 */
5414 private void updateShouldShowDialogsLocked(Configuration config) {
5415 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5416 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5417 && config.navigation == Configuration.NAVIGATION_NONAV);
5418 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5419 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5420 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5421 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5422 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5423 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5424 HIDE_ERROR_DIALOGS, 0) != 0;
5425 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5426 }
5427
5428 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5429 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5430 FONT_SCALE, 1.0f, userId);
5431
5432 synchronized (this) {
5433 if (getGlobalConfiguration().fontScale == scaleFactor) {
5434 return;
5435 }
5436
5437 final Configuration configuration
5438 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5439 configuration.fontScale = scaleFactor;
5440 updatePersistentConfiguration(configuration, userId);
5441 }
5442 }
5443
5444 // Actually is sleeping or shutting down or whatever else in the future
5445 // is an inactive state.
5446 boolean isSleepingOrShuttingDownLocked() {
5447 return isSleepingLocked() || mShuttingDown;
5448 }
5449
5450 boolean isSleepingLocked() {
5451 return mSleeping;
5452 }
5453
Riddle Hsu16567132018-08-16 21:37:47 +08005454 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005455 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005456 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005457 if (task.isActivityTypeStandard()) {
5458 if (mCurAppTimeTracker != r.appTimeTracker) {
5459 // We are switching app tracking. Complete the current one.
5460 if (mCurAppTimeTracker != null) {
5461 mCurAppTimeTracker.stop();
5462 mH.obtainMessage(
5463 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005464 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005465 mCurAppTimeTracker = null;
5466 }
5467 if (r.appTimeTracker != null) {
5468 mCurAppTimeTracker = r.appTimeTracker;
5469 startTimeTrackingFocusedActivityLocked();
5470 }
5471 } else {
5472 startTimeTrackingFocusedActivityLocked();
5473 }
5474 } else {
5475 r.appTimeTracker = null;
5476 }
5477 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5478 // TODO: Probably not, because we don't want to resume voice on switching
5479 // back to this activity
5480 if (task.voiceInteractor != null) {
5481 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5482 } else {
5483 finishRunningVoiceLocked();
5484
5485 if (mLastResumedActivity != null) {
5486 final IVoiceInteractionSession session;
5487
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005488 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005489 if (lastResumedActivityTask != null
5490 && lastResumedActivityTask.voiceSession != null) {
5491 session = lastResumedActivityTask.voiceSession;
5492 } else {
5493 session = mLastResumedActivity.voiceSession;
5494 }
5495
5496 if (session != null) {
5497 // We had been in a voice interaction session, but now focused has
5498 // move to something different. Just finish the session, we can't
5499 // return to it and retain the proper state and synchronization with
5500 // the voice interaction service.
5501 finishVoiceTask(session);
5502 }
5503 }
5504 }
5505
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005506 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5507 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005508 }
5509 updateResumedAppTrace(r);
5510 mLastResumedActivity = r;
5511
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005512 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005513
5514 applyUpdateLockStateLocked(r);
5515 applyUpdateVrModeLocked(r);
5516
5517 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005518 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005519 r == null ? "NULL" : r.shortComponentName,
5520 reason);
5521 }
5522
5523 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5524 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005525 final ActivityTaskManagerInternal.SleepToken token =
5526 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005527 updateSleepIfNeededLocked();
5528 return token;
5529 }
5530 }
5531
5532 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005533 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005534 final boolean wasSleeping = mSleeping;
5535 boolean updateOomAdj = false;
5536
5537 if (!shouldSleep) {
5538 // If wasSleeping is true, we need to wake up activity manager state from when
5539 // we started sleeping. In either case, we need to apply the sleep tokens, which
5540 // will wake up stacks or put them to sleep as appropriate.
5541 if (wasSleeping) {
5542 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005543 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5544 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005545 startTimeTrackingFocusedActivityLocked();
5546 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
Varun Shah98694fb2019-04-11 09:28:27 -07005547 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005548 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5549 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005550 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551 if (wasSleeping) {
5552 updateOomAdj = true;
5553 }
5554 } else if (!mSleeping && shouldSleep) {
5555 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005556 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5557 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005558 if (mCurAppTimeTracker != null) {
5559 mCurAppTimeTracker.stop();
5560 }
5561 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
Varun Shah98694fb2019-04-11 09:28:27 -07005562 Slog.d(TAG, "Top Process State changed to PROCESS_STATE_TOP_SLEEPING");
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 mStackSupervisor.goingToSleepLocked();
5564 updateResumedAppTrace(null /* resumed */);
5565 updateOomAdj = true;
5566 }
5567 if (updateOomAdj) {
5568 mH.post(mAmInternal::updateOomAdj);
5569 }
5570 }
5571
5572 void updateOomAdj() {
5573 mH.post(mAmInternal::updateOomAdj);
5574 }
5575
Wale Ogunwale53783742018-09-16 10:21:51 -07005576 void updateCpuStats() {
5577 mH.post(mAmInternal::updateCpuStats);
5578 }
5579
Hui Yu03d12402018-12-06 18:00:37 -08005580 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5581 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005582 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5583 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005584 mH.sendMessage(m);
5585 }
5586
Hui Yu03d12402018-12-06 18:00:37 -08005587 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005588 ComponentName taskRoot = null;
5589 final TaskRecord task = activity.getTaskRecord();
5590 if (task != null) {
5591 final ActivityRecord rootActivity = task.getRootActivity();
5592 if (rootActivity != null) {
5593 taskRoot = rootActivity.mActivityComponent;
5594 }
5595 }
5596
Hui Yu03d12402018-12-06 18:00:37 -08005597 final Message m = PooledLambda.obtainMessage(
5598 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005599 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005600 mH.sendMessage(m);
5601 }
5602
Riddle Hsu32dbdca2019-05-17 23:10:16 -06005603 void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
5604 String hostingType) {
5605 try {
5606 if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
5607 Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
5608 + activity.processName);
5609 }
5610 // Post message to start process to avoid possible deadlock of calling into AMS with the
5611 // ATMS lock held.
5612 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
5613 mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
5614 isTop, hostingType, activity.intent.getComponent());
5615 mH.sendMessage(m);
5616 } finally {
5617 Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
5618 }
5619 }
5620
Wale Ogunwale53783742018-09-16 10:21:51 -07005621 void setBooting(boolean booting) {
5622 mAmInternal.setBooting(booting);
5623 }
5624
5625 boolean isBooting() {
5626 return mAmInternal.isBooting();
5627 }
5628
5629 void setBooted(boolean booted) {
5630 mAmInternal.setBooted(booted);
5631 }
5632
5633 boolean isBooted() {
5634 return mAmInternal.isBooted();
5635 }
5636
5637 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5638 mH.post(() -> {
5639 if (finishBooting) {
5640 mAmInternal.finishBooting();
5641 }
5642 if (enableScreen) {
5643 mInternal.enableScreenAfterBoot(isBooted());
5644 }
5645 });
5646 }
5647
5648 void setHeavyWeightProcess(ActivityRecord root) {
5649 mHeavyWeightProcess = root.app;
5650 final Message m = PooledLambda.obtainMessage(
5651 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005652 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005653 mH.sendMessage(m);
5654 }
5655
5656 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5657 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5658 return;
5659 }
5660
5661 mHeavyWeightProcess = null;
5662 final Message m = PooledLambda.obtainMessage(
5663 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5664 proc.mUserId);
5665 mH.sendMessage(m);
5666 }
5667
5668 private void cancelHeavyWeightProcessNotification(int userId) {
5669 final INotificationManager inm = NotificationManager.getService();
5670 if (inm == null) {
5671 return;
5672 }
5673 try {
Julia Reynoldse4a47dd2019-06-07 13:40:59 -04005674 inm.cancelNotificationWithTag("android", "android", null,
Wale Ogunwale53783742018-09-16 10:21:51 -07005675 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5676 } catch (RuntimeException e) {
5677 Slog.w(TAG, "Error canceling notification for service", e);
5678 } catch (RemoteException e) {
5679 }
5680
5681 }
5682
5683 private void postHeavyWeightProcessNotification(
5684 WindowProcessController proc, Intent intent, int userId) {
5685 if (proc == null) {
5686 return;
5687 }
5688
5689 final INotificationManager inm = NotificationManager.getService();
5690 if (inm == null) {
5691 return;
5692 }
5693
5694 try {
5695 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5696 String text = mContext.getString(R.string.heavy_weight_notification,
5697 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5698 Notification notification =
5699 new Notification.Builder(context,
5700 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5701 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5702 .setWhen(0)
5703 .setOngoing(true)
5704 .setTicker(text)
5705 .setColor(mContext.getColor(
5706 com.android.internal.R.color.system_notification_accent_color))
5707 .setContentTitle(text)
5708 .setContentText(
5709 mContext.getText(R.string.heavy_weight_notification_detail))
5710 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5711 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5712 new UserHandle(userId)))
5713 .build();
5714 try {
5715 inm.enqueueNotificationWithTag("android", "android", null,
5716 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5717 } catch (RuntimeException e) {
5718 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5719 } catch (RemoteException e) {
5720 }
5721 } catch (PackageManager.NameNotFoundException e) {
5722 Slog.w(TAG, "Unable to create context for heavy notification", e);
5723 }
5724
5725 }
5726
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005727 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5728 IBinder token, String resultWho, int requestCode, Intent[] intents,
5729 String[] resolvedTypes, int flags, Bundle bOptions) {
5730
5731 ActivityRecord activity = null;
5732 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5733 activity = ActivityRecord.isInStackLocked(token);
5734 if (activity == null) {
5735 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5736 return null;
5737 }
5738 if (activity.finishing) {
5739 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5740 return null;
5741 }
5742 }
5743
5744 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5745 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5746 bOptions);
5747 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5748 if (noCreate) {
5749 return rec;
5750 }
5751 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5752 if (activity.pendingResults == null) {
5753 activity.pendingResults = new HashSet<>();
5754 }
5755 activity.pendingResults.add(rec.ref);
5756 }
5757 return rec;
5758 }
5759
Andrii Kulian52d255c2018-07-13 11:32:19 -07005760 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005761 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005762 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005763 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5764 mCurAppTimeTracker.start(resumedActivity.packageName);
5765 }
5766 }
5767
5768 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5769 if (mTracedResumedActivity != null) {
5770 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5771 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5772 }
5773 if (resumed != null) {
5774 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5775 constructResumedTraceName(resumed.packageName), 0);
5776 }
5777 mTracedResumedActivity = resumed;
5778 }
5779
5780 private String constructResumedTraceName(String packageName) {
5781 return "focused app: " + packageName;
5782 }
5783
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005784 /** Applies latest configuration and/or visibility updates if needed. */
5785 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5786 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005787 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005788 // mainStack is null during startup.
5789 if (mainStack != null) {
5790 if (changes != 0 && starting == null) {
5791 // If the configuration changed, and the caller is not already
5792 // in the process of starting an activity, then find the top
5793 // activity to check if its configuration needs to change.
5794 starting = mainStack.topRunningActivityLocked();
5795 }
5796
5797 if (starting != null) {
5798 kept = starting.ensureActivityConfiguration(changes,
5799 false /* preserveWindow */);
5800 // And we need to make sure at this point that all other activities
5801 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005802 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005803 !PRESERVE_WINDOWS);
5804 }
5805 }
5806
5807 return kept;
5808 }
5809
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005810 void scheduleAppGcsLocked() {
5811 mH.post(() -> mAmInternal.scheduleAppGcs());
5812 }
5813
Wale Ogunwale53783742018-09-16 10:21:51 -07005814 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5815 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5816 }
5817
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005818 /**
5819 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5820 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5821 * on demand.
5822 */
5823 IPackageManager getPackageManager() {
5824 return AppGlobals.getPackageManager();
5825 }
5826
5827 PackageManagerInternal getPackageManagerInternalLocked() {
5828 if (mPmInternal == null) {
5829 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5830 }
5831 return mPmInternal;
5832 }
5833
Hai Zhangf4da9be2019-05-01 13:46:06 +08005834 PermissionPolicyInternal getPermissionPolicyInternal() {
5835 if (mPermissionPolicyInternal == null) {
5836 mPermissionPolicyInternal = LocalServices.getService(PermissionPolicyInternal.class);
5837 }
5838 return mPermissionPolicyInternal;
5839 }
5840
Wale Ogunwale008163e2018-07-23 23:11:08 -07005841 AppWarnings getAppWarningsLocked() {
5842 return mAppWarnings;
5843 }
5844
Wale Ogunwale214f3482018-10-04 11:00:47 -07005845 Intent getHomeIntent() {
5846 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5847 intent.setComponent(mTopComponent);
5848 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5849 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5850 intent.addCategory(Intent.CATEGORY_HOME);
5851 }
5852 return intent;
5853 }
5854
Chilun2ef71f72018-11-16 17:57:15 +08005855 /**
5856 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5857 * activities.
5858 *
5859 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5860 * component defined in config_secondaryHomeComponent.
5861 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5862 */
5863 Intent getSecondaryHomeIntent(String preferredPackage) {
5864 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
Keun young Park340546a2019-05-06 16:27:44 -07005865 final boolean useSystemProvidedLauncher = mContext.getResources().getBoolean(
5866 com.android.internal.R.bool.config_useSystemProvidedLauncherForSecondary);
5867 if (preferredPackage == null || useSystemProvidedLauncher) {
5868 // Using the component stored in config if no package name or forced.
Chilun2ef71f72018-11-16 17:57:15 +08005869 final String secondaryHomeComponent = mContext.getResources().getString(
5870 com.android.internal.R.string.config_secondaryHomeComponent);
5871 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5872 } else {
5873 intent.setPackage(preferredPackage);
5874 }
5875 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5876 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5877 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5878 }
5879 return intent;
5880 }
5881
Wale Ogunwale214f3482018-10-04 11:00:47 -07005882 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5883 if (info == null) return null;
5884 ApplicationInfo newInfo = new ApplicationInfo(info);
5885 newInfo.initForUser(userId);
5886 return newInfo;
5887 }
5888
Wale Ogunwale9c103022018-10-18 07:44:54 -07005889 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005890 if (uid == SYSTEM_UID) {
5891 // The system gets to run in any process. If there are multiple processes with the same
5892 // uid, just pick the first (this should never happen).
5893 final SparseArray<WindowProcessController> procs =
5894 mProcessNames.getMap().get(processName);
5895 if (procs == null) return null;
5896 final int procCount = procs.size();
5897 for (int i = 0; i < procCount; i++) {
5898 final int procUid = procs.keyAt(i);
5899 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5900 // Don't use an app process or different user process for system component.
5901 continue;
5902 }
5903 return procs.valueAt(i);
5904 }
5905 }
5906
5907 return mProcessNames.get(processName, uid);
5908 }
5909
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005910 WindowProcessController getProcessController(IApplicationThread thread) {
5911 if (thread == null) {
5912 return null;
5913 }
5914
5915 final IBinder threadBinder = thread.asBinder();
5916 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5917 for (int i = pmap.size()-1; i >= 0; i--) {
5918 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5919 for (int j = procs.size() - 1; j >= 0; j--) {
5920 final WindowProcessController proc = procs.valueAt(j);
5921 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5922 return proc;
5923 }
5924 }
5925 }
5926
5927 return null;
5928 }
5929
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005930 WindowProcessController getProcessController(int pid, int uid) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01005931 final WindowProcessController proc = mProcessMap.getProcess(pid);
Yunfan Chen8546b212019-04-01 15:34:44 +09005932 if (proc == null) return null;
5933 if (UserHandle.isApp(uid) && proc.mUid == uid) {
5934 return proc;
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005935 }
5936 return null;
5937 }
5938
Riddle Hsua0536432019-02-16 00:38:59 +08005939 int getUidState(int uid) {
5940 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005941 }
5942
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005943 boolean isUidForeground(int uid) {
Alan Stokeseea8d3e2019-04-10 17:37:25 +01005944 // A uid is considered to be foreground if it has a visible non-toast window.
5945 return mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005946 }
5947
Ricky Wai96f5c352019-04-10 18:40:17 +01005948 boolean isDeviceOwner(int uid) {
5949 return uid >= 0 && mDeviceOwnerUid == uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005950 }
5951
Ricky Wai96f5c352019-04-10 18:40:17 +01005952 void setDeviceOwnerUid(int uid) {
5953 mDeviceOwnerUid = uid;
Michal Karpinski4026cae2019-02-12 11:51:47 +00005954 }
5955
Wale Ogunwale9de19442018-10-18 19:05:03 -07005956 /**
5957 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5958 * the whitelist
5959 */
5960 String getPendingTempWhitelistTagForUidLocked(int uid) {
5961 return mPendingTempWhitelist.get(uid);
5962 }
5963
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005964 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5965 if (true || Build.IS_USER) {
5966 return;
5967 }
5968
5969 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5970 StrictMode.allowThreadDiskWrites();
5971 try {
5972 File tracesDir = new File("/data/anr");
5973 File tracesFile = null;
5974 try {
5975 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5976
5977 StringBuilder sb = new StringBuilder();
5978 Time tobj = new Time();
5979 tobj.set(System.currentTimeMillis());
5980 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5981 sb.append(": ");
5982 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5983 sb.append(" since ");
5984 sb.append(msg);
5985 FileOutputStream fos = new FileOutputStream(tracesFile);
5986 fos.write(sb.toString().getBytes());
5987 if (app == null) {
5988 fos.write("\n*** No application process!".getBytes());
5989 }
5990 fos.close();
5991 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5992 } catch (IOException e) {
5993 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5994 return;
5995 }
5996
5997 if (app != null && app.getPid() > 0) {
5998 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5999 firstPids.add(app.getPid());
6000 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
6001 }
6002
6003 File lastTracesFile = null;
6004 File curTracesFile = null;
6005 for (int i=9; i>=0; i--) {
6006 String name = String.format(Locale.US, "slow%02d.txt", i);
6007 curTracesFile = new File(tracesDir, name);
6008 if (curTracesFile.exists()) {
6009 if (lastTracesFile != null) {
6010 curTracesFile.renameTo(lastTracesFile);
6011 } else {
6012 curTracesFile.delete();
6013 }
6014 }
6015 lastTracesFile = curTracesFile;
6016 }
6017 tracesFile.renameTo(curTracesFile);
6018 } finally {
6019 StrictMode.setThreadPolicy(oldPolicy);
6020 }
6021 }
6022
Michal Karpinskida34cd42019-04-02 19:46:52 +01006023 boolean isAssociatedCompanionApp(int userId, int uid) {
6024 final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
6025 if (allUids == null) {
Ricky Wai2452e2d2019-03-18 19:19:08 +00006026 return false;
6027 }
Michal Karpinskida34cd42019-04-02 19:46:52 +01006028 return allUids.contains(uid);
Ricky Wai2452e2d2019-03-18 19:19:08 +00006029 }
6030
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006031 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006032 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04006033
6034
Wale Ogunwale98875612018-10-12 07:53:02 -07006035 static final int FIRST_ACTIVITY_STACK_MSG = 100;
6036 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07006037
Riddle Hsud93a6c42018-11-29 21:50:06 +08006038 H(Looper looper) {
6039 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006040 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006041
6042 @Override
6043 public void handleMessage(Message msg) {
6044 switch (msg.what) {
6045 case REPORT_TIME_TRACKER_MSG: {
6046 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
6047 tracker.deliverResult(mContext);
6048 } break;
6049 }
6050 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006051 }
6052
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006053 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006054 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006055
6056 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006057 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006058 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006059
6060 @Override
6061 public void handleMessage(Message msg) {
6062 switch (msg.what) {
6063 case DISMISS_DIALOG_UI_MSG: {
6064 final Dialog d = (Dialog) msg.obj;
6065 d.dismiss();
6066 break;
6067 }
6068 }
6069 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006070 }
6071
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006072 final class LocalService extends ActivityTaskManagerInternal {
6073 @Override
6074 public SleepToken acquireSleepToken(String tag, int displayId) {
6075 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006076 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 }
6078
6079 @Override
6080 public ComponentName getHomeActivityForUser(int userId) {
6081 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006082 final ActivityRecord homeActivity =
6083 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006084 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006085 }
6086 }
6087
6088 @Override
6089 public void onLocalVoiceInteractionStarted(IBinder activity,
6090 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
6091 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006092 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006093 }
6094 }
6095
6096 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006097 public void notifyAppTransitionStarting(SparseIntArray reasons,
6098 long timestamp) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006099 synchronized (mGlobalLock) {
6100 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
6101 reasons, timestamp);
6102 }
6103 }
6104
6105 @Override
Issei Suzukicac2a502019-04-16 16:52:50 +02006106 public void notifySingleTaskDisplayDrawn(int displayId) {
6107 mTaskChangeNotificationController.notifySingleTaskDisplayDrawn(displayId);
6108 }
6109
6110 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006111 public void notifyAppTransitionFinished() {
6112 synchronized (mGlobalLock) {
6113 mStackSupervisor.notifyAppTransitionDone();
6114 }
6115 }
6116
6117 @Override
6118 public void notifyAppTransitionCancelled() {
6119 synchronized (mGlobalLock) {
6120 mStackSupervisor.notifyAppTransitionDone();
6121 }
6122 }
6123
6124 @Override
6125 public List<IBinder> getTopVisibleActivities() {
6126 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006127 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006128 }
6129 }
6130
6131 @Override
6132 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6133 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006134 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006135 }
6136 }
6137
6138 @Override
6139 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6140 Bundle bOptions) {
6141 Preconditions.checkNotNull(intents, "intents");
6142 final String[] resolvedTypes = new String[intents.length];
6143
6144 // UID of the package on user userId.
6145 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6146 // packageUid may not be initialized.
6147 int packageUid = 0;
6148 final long ident = Binder.clearCallingIdentity();
6149
6150 try {
6151 for (int i = 0; i < intents.length; i++) {
6152 resolvedTypes[i] =
6153 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6154 }
6155
6156 packageUid = AppGlobals.getPackageManager().getPackageUid(
6157 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6158 } catch (RemoteException e) {
6159 // Shouldn't happen.
6160 } finally {
6161 Binder.restoreCallingIdentity(ident);
6162 }
6163
Riddle Hsu591bf612019-02-14 17:55:31 +08006164 return getActivityStartController().startActivitiesInPackage(
6165 packageUid, packageName,
6166 intents, resolvedTypes, null /* resultTo */,
6167 SafeActivityOptions.fromBundle(bOptions), userId,
6168 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6169 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006170 }
6171
6172 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006173 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6174 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6175 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6176 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006177 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006178 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006179 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6180 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6181 userId, validateIncomingUser, originatingPendingIntent,
6182 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006183 }
6184 }
6185
6186 @Override
6187 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6188 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6189 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6190 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006191 PendingIntentRecord originatingPendingIntent,
6192 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006193 synchronized (mGlobalLock) {
6194 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6195 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6196 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006197 validateIncomingUser, originatingPendingIntent,
6198 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006199 }
6200 }
6201
6202 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006203 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6204 Intent intent, Bundle options, int userId) {
6205 return ActivityTaskManagerService.this.startActivityAsUser(
6206 caller, callerPacakge, intent,
6207 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6208 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6209 false /*validateIncomingUser*/);
6210 }
6211
6212 @Override
lumark588a3e82018-07-20 18:53:54 +08006213 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006214 synchronized (mGlobalLock) {
6215
6216 // We might change the visibilities here, so prepare an empty app transition which
6217 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006218 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006219 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006220 if (activityDisplay == null) {
6221 return;
6222 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006223 final DisplayContent dc = activityDisplay.mDisplayContent;
6224 final boolean wasTransitionSet =
6225 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006226 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006227 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006228 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006229 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006230
6231 // If there was a transition set already we don't want to interfere with it as we
6232 // might be starting it too early.
6233 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006234 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006235 }
6236 }
6237 if (callback != null) {
6238 callback.run();
6239 }
6240 }
6241
6242 @Override
6243 public void notifyKeyguardTrustedChanged() {
6244 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006245 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006246 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006247 }
6248 }
6249 }
6250
6251 /**
6252 * Called after virtual display Id is updated by
6253 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6254 * {@param vrVr2dDisplayId}.
6255 */
6256 @Override
6257 public void setVr2dDisplayId(int vr2dDisplayId) {
6258 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6259 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006260 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006261 }
6262 }
6263
6264 @Override
6265 public void setFocusedActivity(IBinder token) {
6266 synchronized (mGlobalLock) {
6267 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6268 if (r == null) {
6269 throw new IllegalArgumentException(
6270 "setFocusedActivity: No activity record matching token=" + token);
6271 }
Louis Chang19443452018-10-09 12:10:21 +08006272 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006273 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006274 }
6275 }
6276 }
6277
6278 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006279 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006280 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006281 }
6282
6283 @Override
6284 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006285 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006286 }
6287
6288 @Override
6289 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006290 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006291 }
6292
6293 @Override
6294 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6295 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6296 }
6297
6298 @Override
6299 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006300 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006301 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006302
6303 @Override
6304 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6305 synchronized (mGlobalLock) {
6306 mActiveVoiceInteractionServiceComponent = component;
6307 }
6308 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006309
6310 @Override
6311 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6312 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6313 return;
6314 }
6315 synchronized (mGlobalLock) {
6316 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6317 if (types == null) {
6318 if (uid < 0) {
6319 return;
6320 }
6321 types = new ArrayMap<>();
6322 mAllowAppSwitchUids.put(userId, types);
6323 }
6324 if (uid < 0) {
6325 types.remove(type);
6326 } else {
6327 types.put(type, uid);
6328 }
6329 }
6330 }
6331
6332 @Override
6333 public void onUserStopped(int userId) {
6334 synchronized (mGlobalLock) {
6335 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6336 mAllowAppSwitchUids.remove(userId);
6337 }
6338 }
6339
6340 @Override
6341 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6342 synchronized (mGlobalLock) {
6343 return ActivityTaskManagerService.this.isGetTasksAllowed(
6344 caller, callingPid, callingUid);
6345 }
6346 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006347
Riddle Hsua0536432019-02-16 00:38:59 +08006348 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006349 @Override
6350 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006351 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006352 mProcessNames.put(proc.mName, proc.mUid, proc);
6353 }
6354 }
6355
Riddle Hsua0536432019-02-16 00:38:59 +08006356 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006357 @Override
6358 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006359 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006360 mProcessNames.remove(name, uid);
6361 }
6362 }
6363
Riddle Hsua0536432019-02-16 00:38:59 +08006364 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006365 @Override
6366 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006367 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006368 if (proc == mHomeProcess) {
6369 mHomeProcess = null;
6370 }
6371 if (proc == mPreviousProcess) {
6372 mPreviousProcess = null;
6373 }
6374 }
6375 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006376
Riddle Hsua0536432019-02-16 00:38:59 +08006377 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006378 @Override
6379 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006380 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006381 return mTopProcessState;
6382 }
6383 }
6384
Riddle Hsua0536432019-02-16 00:38:59 +08006385 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006386 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006387 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006388 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006389 return proc == mHeavyWeightProcess;
6390 }
6391 }
6392
Riddle Hsua0536432019-02-16 00:38:59 +08006393 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006394 @Override
6395 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006396 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006397 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6398 }
6399 }
6400
6401 @Override
6402 public void finishHeavyWeightApp() {
6403 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006404 if (mHeavyWeightProcess != null) {
6405 mHeavyWeightProcess.finishActivities();
6406 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006407 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6408 mHeavyWeightProcess);
6409 }
6410 }
6411
Riddle Hsua0536432019-02-16 00:38:59 +08006412 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006413 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006414 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006415 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006416 return isSleepingLocked();
6417 }
6418 }
6419
6420 @Override
6421 public boolean isShuttingDown() {
6422 synchronized (mGlobalLock) {
6423 return mShuttingDown;
6424 }
6425 }
6426
6427 @Override
6428 public boolean shuttingDown(boolean booted, int timeout) {
6429 synchronized (mGlobalLock) {
6430 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006431 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006432 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006433 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006434 return mStackSupervisor.shutdownLocked(timeout);
6435 }
6436 }
6437
6438 @Override
6439 public void enableScreenAfterBoot(boolean booted) {
6440 synchronized (mGlobalLock) {
6441 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6442 SystemClock.uptimeMillis());
6443 mWindowManager.enableScreenAfterBoot();
6444 updateEventDispatchingLocked(booted);
6445 }
6446 }
6447
6448 @Override
6449 public boolean showStrictModeViolationDialog() {
6450 synchronized (mGlobalLock) {
6451 return mShowDialogs && !mSleeping && !mShuttingDown;
6452 }
6453 }
6454
6455 @Override
6456 public void showSystemReadyErrorDialogsIfNeeded() {
6457 synchronized (mGlobalLock) {
6458 try {
6459 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6460 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6461 + " data partition or your device will be unstable.");
6462 mUiHandler.post(() -> {
6463 if (mShowDialogs) {
6464 AlertDialog d = new BaseErrorDialog(mUiContext);
6465 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6466 d.setCancelable(false);
6467 d.setTitle(mUiContext.getText(R.string.android_system_label));
6468 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6469 d.setButton(DialogInterface.BUTTON_POSITIVE,
6470 mUiContext.getText(R.string.ok),
6471 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6472 d.show();
6473 }
6474 });
6475 }
6476 } catch (RemoteException e) {
6477 }
6478
6479 if (!Build.isBuildConsistent()) {
6480 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6481 mUiHandler.post(() -> {
6482 if (mShowDialogs) {
6483 AlertDialog d = new BaseErrorDialog(mUiContext);
6484 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6485 d.setCancelable(false);
6486 d.setTitle(mUiContext.getText(R.string.android_system_label));
6487 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6488 d.setButton(DialogInterface.BUTTON_POSITIVE,
6489 mUiContext.getText(R.string.ok),
6490 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6491 d.show();
6492 }
6493 });
6494 }
6495 }
6496 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006497
6498 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006499 public void onProcessMapped(int pid, WindowProcessController proc) {
6500 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006501 mProcessMap.put(pid, proc);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006502 }
6503 }
6504
6505 @Override
6506 public void onProcessUnMapped(int pid) {
6507 synchronized (mGlobalLock) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006508 mProcessMap.remove(pid);
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006509 }
6510 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006511
6512 @Override
6513 public void onPackageDataCleared(String name) {
6514 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006515 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006516 mAppWarnings.onPackageDataCleared(name);
6517 }
6518 }
6519
6520 @Override
6521 public void onPackageUninstalled(String name) {
6522 synchronized (mGlobalLock) {
6523 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006524 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006525 }
6526 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006527
6528 @Override
6529 public void onPackageAdded(String name, boolean replacing) {
6530 synchronized (mGlobalLock) {
6531 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6532 }
6533 }
6534
6535 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006536 public void onPackageReplaced(ApplicationInfo aInfo) {
6537 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006538 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006539 }
6540 }
6541
6542 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006543 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6544 synchronized (mGlobalLock) {
6545 return compatibilityInfoForPackageLocked(ai);
6546 }
6547 }
6548
Yunfan Chen75157d72018-07-27 14:47:21 +09006549 /**
6550 * Set the corresponding display information for the process global configuration. To be
6551 * called when we need to show IME on a different display.
6552 *
6553 * @param pid The process id associated with the IME window.
6554 * @param displayId The ID of the display showing the IME.
6555 */
6556 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006557 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
lumark48973532019-04-12 20:18:15 +08006558 // Don't update process-level configuration for Multi-Client IME process since other
6559 // IMEs on other displays will also receive this configuration change due to IME
6560 // services use the same application config/context.
6561 if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) return;
lumark5df49512019-04-02 14:56:46 +08006562
Yunfan Chen75157d72018-07-27 14:47:21 +09006563 if (pid == MY_PID || pid < 0) {
6564 if (DEBUG_CONFIGURATION) {
6565 Slog.w(TAG,
6566 "Trying to update display configuration for system/invalid process.");
6567 }
6568 return;
6569 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006570 synchronized (mGlobalLock) {
6571 final ActivityDisplay activityDisplay =
6572 mRootActivityContainer.getActivityDisplay(displayId);
6573 if (activityDisplay == null) {
6574 // Call might come when display is not yet added or has been removed.
6575 if (DEBUG_CONFIGURATION) {
6576 Slog.w(TAG, "Trying to update display configuration for non-existing "
6577 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006578 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006579 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006580 }
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006581 final WindowProcessController process = mProcessMap.getProcess(pid);
Yunfan Chencafc7062019-01-22 17:21:32 +09006582 if (process == null) {
6583 if (DEBUG_CONFIGURATION) {
6584 Slog.w(TAG, "Trying to update display configuration for invalid "
6585 + "process, pid=" + pid);
6586 }
6587 return;
6588 }
6589 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6590 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006591 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006592
6593 @Override
6594 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006595 int requestCode, int resultCode, Intent data) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006596 synchronized (mGlobalLock) {
Wale Ogunwale586a8ee2019-06-04 13:44:14 +00006597 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6598 if (r != null && r.getActivityStack() != null) {
6599 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6600 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006601 }
6602 }
6603 }
6604
6605 @Override
6606 public void clearPendingResultForActivity(IBinder activityToken,
6607 WeakReference<PendingIntentRecord> pir) {
6608 synchronized (mGlobalLock) {
6609 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6610 if (r != null && r.pendingResults != null) {
6611 r.pendingResults.remove(pir);
6612 }
6613 }
6614 }
6615
6616 @Override
Sunny Goyald40c3452019-03-20 12:46:55 -07006617 public ActivityTokens getTopActivityForTask(int taskId) {
6618 synchronized (mGlobalLock) {
6619 final TaskRecord taskRecord = mRootActivityContainer.anyTaskForId(taskId);
6620 if (taskRecord == null) {
6621 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6622 + " Requested task not found");
6623 return null;
6624 }
6625 final ActivityRecord activity = taskRecord.getTopActivity();
6626 if (activity == null) {
6627 Slog.w(TAG, "getApplicationThreadForTopActivity failed:"
6628 + " Requested activity not found");
6629 return null;
6630 }
6631 if (!activity.attachedToProcess()) {
6632 Slog.w(TAG, "getApplicationThreadForTopActivity failed: No process for "
6633 + activity);
6634 return null;
6635 }
6636 return new ActivityTokens(activity.appToken, activity.assistToken,
6637 activity.app.getThread());
6638 }
6639 }
6640
6641 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006642 public IIntentSender getIntentSender(int type, String packageName,
6643 int callingUid, int userId, IBinder token, String resultWho,
6644 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6645 Bundle bOptions) {
6646 synchronized (mGlobalLock) {
6647 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6648 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6649 }
6650 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006651
6652 @Override
6653 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6654 synchronized (mGlobalLock) {
6655 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6656 if (r == null) {
6657 return null;
6658 }
6659 if (r.mServiceConnectionsHolder == null) {
6660 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6661 ActivityTaskManagerService.this, r);
6662 }
6663
6664 return r.mServiceConnectionsHolder;
6665 }
6666 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006667
6668 @Override
6669 public Intent getHomeIntent() {
6670 synchronized (mGlobalLock) {
6671 return ActivityTaskManagerService.this.getHomeIntent();
6672 }
6673 }
6674
6675 @Override
6676 public boolean startHomeActivity(int userId, String reason) {
6677 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006678 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006679 }
6680 }
6681
6682 @Override
Chilun8b1f1be2019-03-13 17:14:36 +08006683 public boolean startHomeOnDisplay(int userId, String reason, int displayId,
Chilun39232092019-03-22 14:41:30 +08006684 boolean allowInstrumenting, boolean fromHomeKey) {
Chilun5fd56542019-03-21 19:51:37 +08006685 synchronized (mGlobalLock) {
6686 return mRootActivityContainer.startHomeOnDisplay(userId, reason, displayId,
Chilun39232092019-03-22 14:41:30 +08006687 allowInstrumenting, fromHomeKey);
Chilun5fd56542019-03-21 19:51:37 +08006688 }
Chilun8b1f1be2019-03-13 17:14:36 +08006689 }
6690
6691 @Override
Louis Chang89f43fc2018-10-05 10:59:14 +08006692 public boolean startHomeOnAllDisplays(int userId, String reason) {
6693 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006694 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006695 }
6696 }
6697
Riddle Hsua0536432019-02-16 00:38:59 +08006698 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006699 @Override
6700 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006701 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006702 if (mFactoryTest == FACTORY_TEST_OFF) {
6703 return false;
6704 }
6705 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6706 && wpc.mName.equals(mTopComponent.getPackageName())) {
6707 return true;
6708 }
6709 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6710 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6711 }
6712 }
6713
6714 @Override
6715 public void updateTopComponentForFactoryTest() {
6716 synchronized (mGlobalLock) {
6717 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6718 return;
6719 }
6720 final ResolveInfo ri = mContext.getPackageManager()
6721 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6722 final CharSequence errorMsg;
6723 if (ri != null) {
6724 final ActivityInfo ai = ri.activityInfo;
6725 final ApplicationInfo app = ai.applicationInfo;
6726 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6727 mTopAction = Intent.ACTION_FACTORY_TEST;
6728 mTopData = null;
6729 mTopComponent = new ComponentName(app.packageName, ai.name);
6730 errorMsg = null;
6731 } else {
6732 errorMsg = mContext.getResources().getText(
6733 com.android.internal.R.string.factorytest_not_system);
6734 }
6735 } else {
6736 errorMsg = mContext.getResources().getText(
6737 com.android.internal.R.string.factorytest_no_action);
6738 }
6739 if (errorMsg == null) {
6740 return;
6741 }
6742
6743 mTopAction = null;
6744 mTopData = null;
6745 mTopComponent = null;
6746 mUiHandler.post(() -> {
6747 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6748 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006749 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006750 });
6751 }
6752 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006753
Riddle Hsua0536432019-02-16 00:38:59 +08006754 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006755 @Override
6756 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6757 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006758 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006759 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006760 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006761
6762 wpc.clearRecentTasks();
6763 wpc.clearActivities();
6764
6765 if (wpc.isInstrumenting()) {
6766 finishInstrumentationCallback.run();
6767 }
6768
Jorim Jaggid0752812018-10-16 16:07:20 +02006769 if (!restarting && hasVisibleActivities) {
6770 mWindowManager.deferSurfaceLayout();
6771 try {
6772 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6773 // If there was nothing to resume, and we are not already restarting
6774 // this process, but there is a visible activity that is hosted by the
6775 // process...then make sure all visible activities are running, taking
6776 // care of restarting this process.
6777 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6778 !PRESERVE_WINDOWS);
6779 }
6780 } finally {
6781 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006782 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006783 }
6784 }
6785 }
6786
6787 @Override
6788 public void closeSystemDialogs(String reason) {
6789 enforceNotIsolatedCaller("closeSystemDialogs");
6790
6791 final int pid = Binder.getCallingPid();
6792 final int uid = Binder.getCallingUid();
6793 final long origId = Binder.clearCallingIdentity();
6794 try {
6795 synchronized (mGlobalLock) {
6796 // Only allow this from foreground processes, so that background
6797 // applications can't abuse it to prevent system UI from being shown.
6798 if (uid >= FIRST_APPLICATION_UID) {
Michal Karpinski2e0aad22019-04-12 16:22:55 +01006799 final WindowProcessController proc = mProcessMap.getProcess(pid);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006800 if (!proc.isPerceptible()) {
6801 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6802 + " from background process " + proc);
6803 return;
6804 }
6805 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006806 mWindowManager.closeSystemDialogs(reason);
6807
Wale Ogunwaled32da472018-11-16 07:19:28 -08006808 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006809 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006810 // Call into AM outside the synchronized block.
6811 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006812 } finally {
6813 Binder.restoreCallingIdentity(origId);
6814 }
6815 }
6816
6817 @Override
6818 public void cleanupDisabledPackageComponents(
6819 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6820 synchronized (mGlobalLock) {
6821 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006822 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006823 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006824 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006825 mStackSupervisor.scheduleIdleLocked();
6826 }
6827
6828 // Clean-up disabled tasks
6829 getRecentTasks().cleanupDisabledPackageTasksLocked(
6830 packageName, disabledClasses, userId);
6831 }
6832 }
6833
6834 @Override
6835 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6836 int userId) {
6837 synchronized (mGlobalLock) {
6838
6839 boolean didSomething =
6840 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006841 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006842 null, doit, evenPersistent, userId);
6843 return didSomething;
6844 }
6845 }
6846
6847 @Override
6848 public void resumeTopActivities(boolean scheduleIdle) {
6849 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006850 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006851 if (scheduleIdle) {
6852 mStackSupervisor.scheduleIdleLocked();
6853 }
6854 }
6855 }
6856
Riddle Hsua0536432019-02-16 00:38:59 +08006857 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006858 @Override
6859 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006860 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6862 }
6863 }
6864
Riddle Hsua0536432019-02-16 00:38:59 +08006865 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 @Override
6867 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006868 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006869 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 }
6871 }
6872
6873 @Override
6874 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6875 try {
6876 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6877 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6878 }
6879 } catch (RemoteException ex) {
6880 throw new SecurityException("Fail to check is caller a privileged app", ex);
6881 }
6882
6883 synchronized (mGlobalLock) {
6884 final long ident = Binder.clearCallingIdentity();
6885 try {
6886 if (mAmInternal.shouldConfirmCredentials(userId)) {
6887 if (mKeyguardController.isKeyguardLocked()) {
6888 // Showing launcher to avoid user entering credential twice.
6889 startHomeActivity(currentUserId, "notifyLockedProfile");
6890 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006891 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006892 }
6893 } finally {
6894 Binder.restoreCallingIdentity(ident);
6895 }
6896 }
6897 }
6898
6899 @Override
6900 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6901 mAmInternal.enforceCallingPermission(
6902 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6903
6904 synchronized (mGlobalLock) {
6905 final long ident = Binder.clearCallingIdentity();
6906 try {
Pavel Grafovc0fe0a02019-05-13 18:19:33 +01006907 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
6908 final ActivityOptions activityOptions = options != null
Wale Ogunwale31913b52018-10-13 08:29:31 -07006909 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006910 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6911 UserHandle.CURRENT);
6912 } finally {
6913 Binder.restoreCallingIdentity(ident);
6914 }
6915 }
6916 }
6917
6918 @Override
6919 public void writeActivitiesToProto(ProtoOutputStream proto) {
6920 synchronized (mGlobalLock) {
6921 // The output proto of "activity --proto activities"
6922 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006923 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006924 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6925 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006926 }
6927 }
6928
6929 @Override
6930 public void saveANRState(String reason) {
6931 synchronized (mGlobalLock) {
6932 final StringWriter sw = new StringWriter();
6933 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6934 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6935 if (reason != null) {
6936 pw.println(" Reason: " + reason);
6937 }
6938 pw.println();
6939 getActivityStartController().dump(pw, " ", null);
6940 pw.println();
6941 pw.println("-------------------------------------------------------------------------------");
6942 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6943 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6944 "" /* header */);
6945 pw.println();
6946 pw.close();
6947
6948 mLastANRState = sw.toString();
6949 }
6950 }
6951
6952 @Override
6953 public void clearSavedANRState() {
6954 synchronized (mGlobalLock) {
6955 mLastANRState = null;
6956 }
6957 }
6958
6959 @Override
6960 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6961 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6962 synchronized (mGlobalLock) {
6963 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6964 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6965 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6966 dumpLastANRLocked(pw);
6967 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6968 dumpLastANRTracesLocked(pw);
6969 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6970 dumpActivityStarterLocked(pw, dumpPackage);
6971 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6972 dumpActivityContainersLocked(pw);
6973 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6974 if (getRecentTasks() != null) {
6975 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6976 }
6977 }
6978 }
6979 }
6980
6981 @Override
6982 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6983 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6984 int wakefulness) {
6985 synchronized (mGlobalLock) {
6986 if (mHomeProcess != null && (dumpPackage == null
6987 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6988 if (needSep) {
6989 pw.println();
6990 needSep = false;
6991 }
6992 pw.println(" mHomeProcess: " + mHomeProcess);
6993 }
6994 if (mPreviousProcess != null && (dumpPackage == null
6995 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6996 if (needSep) {
6997 pw.println();
6998 needSep = false;
6999 }
7000 pw.println(" mPreviousProcess: " + mPreviousProcess);
7001 }
7002 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
7003 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
7004 StringBuilder sb = new StringBuilder(128);
7005 sb.append(" mPreviousProcessVisibleTime: ");
7006 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
7007 pw.println(sb);
7008 }
7009 if (mHeavyWeightProcess != null && (dumpPackage == null
7010 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
7011 if (needSep) {
7012 pw.println();
7013 needSep = false;
7014 }
7015 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7016 }
7017 if (dumpPackage == null) {
7018 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08007019 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07007020 }
7021 if (dumpAll) {
7022 if (dumpPackage == null) {
7023 pw.println(" mConfigWillChange: "
7024 + getTopDisplayFocusedStack().mConfigWillChange);
7025 }
7026 if (mCompatModePackages.getPackages().size() > 0) {
7027 boolean printed = false;
7028 for (Map.Entry<String, Integer> entry
7029 : mCompatModePackages.getPackages().entrySet()) {
7030 String pkg = entry.getKey();
7031 int mode = entry.getValue();
7032 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
7033 continue;
7034 }
7035 if (!printed) {
7036 pw.println(" mScreenCompatPackages:");
7037 printed = true;
7038 }
7039 pw.println(" " + pkg + ": " + mode);
7040 }
7041 }
7042 }
7043
7044 if (dumpPackage == null) {
7045 pw.println(" mWakefulness="
7046 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08007047 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007048 if (mRunningVoice != null) {
7049 pw.println(" mRunningVoice=" + mRunningVoice);
7050 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
7051 }
7052 pw.println(" mSleeping=" + mSleeping);
7053 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
7054 pw.println(" mVrController=" + mVrController);
7055 }
7056 if (mCurAppTimeTracker != null) {
7057 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
7058 }
7059 if (mAllowAppSwitchUids.size() > 0) {
7060 boolean printed = false;
7061 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
7062 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
7063 for (int j = 0; j < types.size(); j++) {
7064 if (dumpPackage == null ||
7065 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
7066 if (needSep) {
7067 pw.println();
7068 needSep = false;
7069 }
7070 if (!printed) {
7071 pw.println(" mAllowAppSwitchUids:");
7072 printed = true;
7073 }
7074 pw.print(" User ");
7075 pw.print(mAllowAppSwitchUids.keyAt(i));
7076 pw.print(": Type ");
7077 pw.print(types.keyAt(j));
7078 pw.print(" = ");
7079 UserHandle.formatUid(pw, types.valueAt(j).intValue());
7080 pw.println();
7081 }
7082 }
7083 }
7084 }
7085 if (dumpPackage == null) {
7086 if (mController != null) {
7087 pw.println(" mController=" + mController
7088 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
7089 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007090 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
7091 pw.println(" mLaunchingActivityWakeLock="
7092 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007093 }
7094
7095 return needSep;
7096 }
7097 }
7098
7099 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08007100 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
7101 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07007102 synchronized (mGlobalLock) {
7103 if (dumpPackage == null) {
7104 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
7105 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08007106 writeSleepStateToProto(proto, wakeFullness, testPssMode);
7107 if (mRunningVoice != null) {
7108 final long vrToken = proto.start(
7109 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
7110 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
7111 mRunningVoice.toString());
7112 mVoiceWakeLock.writeToProto(
7113 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
7114 proto.end(vrToken);
7115 }
7116 mVrController.writeToProto(proto,
7117 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007118 if (mController != null) {
7119 final long token = proto.start(CONTROLLER);
7120 proto.write(CONTROLLER, mController.toString());
7121 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
7122 proto.end(token);
7123 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08007124 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
7125 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
7126 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007127 }
7128
7129 if (mHomeProcess != null && (dumpPackage == null
7130 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007131 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007132 }
7133
7134 if (mPreviousProcess != null && (dumpPackage == null
7135 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007136 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007137 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
7138 }
7139
7140 if (mHeavyWeightProcess != null && (dumpPackage == null
7141 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07007142 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007143 }
7144
7145 for (Map.Entry<String, Integer> entry
7146 : mCompatModePackages.getPackages().entrySet()) {
7147 String pkg = entry.getKey();
7148 int mode = entry.getValue();
7149 if (dumpPackage == null || dumpPackage.equals(pkg)) {
7150 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
7151 proto.write(PACKAGE, pkg);
7152 proto.write(MODE, mode);
7153 proto.end(compatToken);
7154 }
7155 }
7156
7157 if (mCurAppTimeTracker != null) {
7158 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7159 }
7160
7161 }
7162 }
7163
7164 @Override
7165 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7166 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7167 boolean dumpFocusedStackOnly) {
7168 synchronized (mGlobalLock) {
7169 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7170 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7171 }
7172 }
7173
7174 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007175 public void dumpForOom(PrintWriter pw) {
7176 synchronized (mGlobalLock) {
7177 pw.println(" mHomeProcess: " + mHomeProcess);
7178 pw.println(" mPreviousProcess: " + mPreviousProcess);
7179 if (mHeavyWeightProcess != null) {
7180 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7181 }
7182 }
7183 }
7184
7185 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007186 public boolean canGcNow() {
7187 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007188 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007189 }
7190 }
7191
Riddle Hsua0536432019-02-16 00:38:59 +08007192 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007193 @Override
7194 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007195 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007196 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007197 return top != null ? top.app : null;
7198 }
7199 }
7200
Riddle Hsua0536432019-02-16 00:38:59 +08007201 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007202 @Override
7203 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007204 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007205 if (mRootActivityContainer != null) {
7206 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007207 }
7208 }
7209 }
7210
7211 @Override
7212 public void scheduleDestroyAllActivities(String reason) {
7213 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007214 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007215 }
7216 }
7217
7218 @Override
7219 public void removeUser(int userId) {
7220 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007221 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007222 }
7223 }
7224
7225 @Override
7226 public boolean switchUser(int userId, UserState userState) {
7227 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007228 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007229 }
7230 }
7231
7232 @Override
7233 public void onHandleAppCrash(WindowProcessController wpc) {
7234 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007235 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007236 }
7237 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007238
7239 @Override
7240 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7241 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007242 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007243 }
7244 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007245
Riddle Hsua0536432019-02-16 00:38:59 +08007246 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007247 @Override
7248 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007249 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007250 }
7251
Riddle Hsua0536432019-02-16 00:38:59 +08007252 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007253 @Override
7254 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007255 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007256 }
7257
Riddle Hsua0536432019-02-16 00:38:59 +08007258 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007259 @Override
7260 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007261 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007262 }
7263
Riddle Hsua0536432019-02-16 00:38:59 +08007264 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007265 @Override
7266 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007267 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007268 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007269
7270 @Override
7271 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007272 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007273 mPendingTempWhitelist.put(uid, tag);
7274 }
7275 }
7276
7277 @Override
7278 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007279 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007280 mPendingTempWhitelist.remove(uid);
7281 }
7282 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007283
7284 @Override
7285 public boolean handleAppCrashInActivityController(String processName, int pid,
7286 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7287 Runnable killCrashingAppCallback) {
7288 synchronized (mGlobalLock) {
7289 if (mController == null) {
7290 return false;
7291 }
7292
7293 try {
7294 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7295 stackTrace)) {
7296 killCrashingAppCallback.run();
7297 return true;
7298 }
7299 } catch (RemoteException e) {
7300 mController = null;
7301 Watchdog.getInstance().setActivityController(null);
7302 }
7303 return false;
7304 }
7305 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007306
7307 @Override
7308 public void removeRecentTasksByPackageName(String packageName, int userId) {
7309 synchronized (mGlobalLock) {
7310 mRecentTasks.removeTasksByPackageName(packageName, userId);
7311 }
7312 }
7313
7314 @Override
7315 public void cleanupRecentTasksForUser(int userId) {
7316 synchronized (mGlobalLock) {
7317 mRecentTasks.cleanupLocked(userId);
7318 }
7319 }
7320
7321 @Override
7322 public void loadRecentTasksForUser(int userId) {
7323 synchronized (mGlobalLock) {
7324 mRecentTasks.loadUserRecentsLocked(userId);
7325 }
7326 }
7327
7328 @Override
7329 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7330 synchronized (mGlobalLock) {
7331 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7332 }
7333 }
7334
7335 @Override
7336 public void flushRecentTasks() {
7337 mRecentTasks.flush();
7338 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007339
7340 @Override
7341 public WindowProcessController getHomeProcess() {
7342 synchronized (mGlobalLock) {
7343 return mHomeProcess;
7344 }
7345 }
7346
7347 @Override
7348 public WindowProcessController getPreviousProcess() {
7349 synchronized (mGlobalLock) {
7350 return mPreviousProcess;
7351 }
7352 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007353
7354 @Override
7355 public void clearLockedTasks(String reason) {
7356 synchronized (mGlobalLock) {
7357 getLockTaskController().clearLockedTasks(reason);
7358 }
7359 }
7360
7361 @Override
7362 public void updateUserConfiguration() {
7363 synchronized (mGlobalLock) {
7364 final Configuration configuration = new Configuration(getGlobalConfiguration());
7365 final int currentUserId = mAmInternal.getCurrentUserId();
7366 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7367 configuration, currentUserId, Settings.System.canWrite(mContext));
7368 updateConfigurationLocked(configuration, null /* starting */,
7369 false /* initLocale */, false /* persistent */, currentUserId,
7370 false /* deferResume */);
7371 }
7372 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007373
7374 @Override
7375 public boolean canShowErrorDialogs() {
7376 synchronized (mGlobalLock) {
7377 return mShowDialogs && !mSleeping && !mShuttingDown
7378 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7379 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7380 mAmInternal.getCurrentUserId())
7381 && !(UserManager.isDeviceInDemoMode(mContext)
7382 && mAmInternal.getCurrentUser().isDemo());
7383 }
7384 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007385
7386 @Override
7387 public void setProfileApp(String profileApp) {
7388 synchronized (mGlobalLock) {
7389 mProfileApp = profileApp;
7390 }
7391 }
7392
7393 @Override
7394 public void setProfileProc(WindowProcessController wpc) {
7395 synchronized (mGlobalLock) {
7396 mProfileProc = wpc;
7397 }
7398 }
7399
7400 @Override
7401 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7402 synchronized (mGlobalLock) {
7403 mProfilerInfo = profilerInfo;
7404 }
7405 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007406
7407 @Override
7408 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7409 synchronized (mGlobalLock) {
7410 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7411 }
7412 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007413
7414 @Override
Jorim Jaggi925bb3c2019-06-04 19:51:45 +02007415 public ActivityManager.TaskSnapshot getTaskSnapshotNoRestore(int taskId,
7416 boolean reducedResolution) {
7417 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution,
7418 false /* restoreFromDisk */);
Winson Chung3fb0f252019-01-08 17:41:55 -08007419 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007420
7421 @Override
7422 public boolean isUidForeground(int uid) {
7423 synchronized (mGlobalLock) {
7424 return ActivityTaskManagerService.this.isUidForeground(uid);
7425 }
7426 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007427
7428 @Override
Ricky Wai96f5c352019-04-10 18:40:17 +01007429 public void setDeviceOwnerUid(int uid) {
Michal Karpinski4026cae2019-02-12 11:51:47 +00007430 synchronized (mGlobalLock) {
Ricky Wai96f5c352019-04-10 18:40:17 +01007431 ActivityTaskManagerService.this.setDeviceOwnerUid(uid);
Michal Karpinski4026cae2019-02-12 11:51:47 +00007432 }
7433 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007434
7435 @Override
7436 public void setCompanionAppPackages(int userId, Set<String> companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007437 // Translate package names into UIDs
7438 final Set<Integer> result = new HashSet<>();
Ricky Wai2452e2d2019-03-18 19:19:08 +00007439 for (String pkg : companionAppPackages) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007440 final int uid = getPackageManagerInternalLocked().getPackageUid(pkg, 0, userId);
7441 if (uid >= 0) {
7442 result.add(uid);
7443 }
Ricky Wai2452e2d2019-03-18 19:19:08 +00007444 }
7445 synchronized (mGlobalLock) {
Michal Karpinskida34cd42019-04-02 19:46:52 +01007446 mCompanionAppUidsMap.put(userId, result);
Ricky Wai2452e2d2019-03-18 19:19:08 +00007447 }
7448 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007449 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007450}