blob: 502a95524b3f99823467526b0403328f8f5828cc [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Evan Rosky4505b352018-09-06 11:20:40 -070029import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070030import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070031import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070032import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
33import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070034import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
35import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070036import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
37import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070038import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070040import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070041import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070042import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070043import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070044import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070045import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
46import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070047import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070048import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070049import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070050import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
51import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070052import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
53import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070055import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070056import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070057import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070058import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
59import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070061import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
62import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070063import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040064import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.view.Display.DEFAULT_DISPLAY;
66import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070067import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070068import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070069
Yunfan Chen79b96062018-10-17 12:45:23 -070070import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
71import static com.android.server.am.ActivityManagerService.MY_PID;
72import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
73import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070074import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
75import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080084import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
89import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070090import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
91import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
92import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
93import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700111import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800115import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
116import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700117import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
118import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800119import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
122import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
123import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700124
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700125import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700126import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700127import android.annotation.Nullable;
128import android.annotation.UserIdInt;
129import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700130import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700131import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.app.ActivityOptions;
133import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700134import android.app.ActivityThread;
135import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700137import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700139import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.IApplicationThread;
141import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700142import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700144import android.app.Notification;
145import android.app.NotificationManager;
146import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.PictureInPictureParams;
148import android.app.ProfilerInfo;
149import android.app.RemoteAction;
150import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700151import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700152import android.app.admin.DevicePolicyCache;
153import android.app.assist.AssistContent;
154import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700155import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.content.ActivityNotFoundException;
157import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700158import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700159import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700160import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700161import android.content.IIntentSender;
162import android.content.Intent;
163import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700164import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900165import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700166import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700167import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700168import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700169import android.content.pm.ParceledListSlice;
170import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700171import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700172import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700173import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700174import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700175import android.graphics.Bitmap;
176import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700177import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700178import android.metrics.LogMaker;
179import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700180import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700181import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700183import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700184import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700185import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700187import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700188import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800189import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700190import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700191import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700192import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700193import android.os.PowerManagerInternal;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100194import android.os.Process;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Marvin Ramin830d4e32019-03-12 13:16:58 +0100247import com.android.server.DeviceIdleController;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700248import com.android.server.LocalServices;
249import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700250import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800251import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700252import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700253import com.android.server.am.ActivityManagerService;
254import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
255import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
256import com.android.server.am.AppTimeTracker;
257import com.android.server.am.BaseErrorDialog;
258import com.android.server.am.EventLogTags;
259import com.android.server.am.PendingIntentController;
260import com.android.server.am.PendingIntentRecord;
261import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900262import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700263import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700264import com.android.server.pm.UserManagerService;
265import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267
Wale Ogunwale31913b52018-10-13 08:29:31 -0700268import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700269import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700270import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700271import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700272import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700273import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700274import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700275import java.io.StringWriter;
Riddle Hsua0536432019-02-16 00:38:59 +0800276import java.lang.annotation.ElementType;
277import java.lang.annotation.Retention;
278import java.lang.annotation.RetentionPolicy;
279import java.lang.annotation.Target;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700280import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700283import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400285import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700286import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700288import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700289import java.util.Map;
290import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291
292/**
293 * System service for managing activities and their containers (task, stacks, displays,... ).
294 *
295 * {@hide}
296 */
297public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700298 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700299 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700300 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
301 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
302 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
303 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
304 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700305 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700306
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700308 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700309 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700310 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700311
Wale Ogunwale98875612018-10-12 07:53:02 -0700312 /** Used to indicate that an app transition should be animated. */
313 static final boolean ANIMATE = true;
314
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700315 /** Hardware-reported OpenGLES version. */
316 final int GL_ES_VERSION;
317
Wale Ogunwale31913b52018-10-13 08:29:31 -0700318 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
319 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
320 public static final String DUMP_LASTANR_CMD = "lastanr" ;
321 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
322 public static final String DUMP_STARTER_CMD = "starter" ;
323 public static final String DUMP_CONTAINERS_CMD = "containers" ;
324 public static final String DUMP_RECENTS_CMD = "recents" ;
325 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
326
Wale Ogunwale64258362018-10-16 15:13:37 -0700327 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
328 public static final int RELAUNCH_REASON_NONE = 0;
329 /** This activity is being relaunched due to windowing mode change. */
330 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
331 /** This activity is being relaunched due to a free-resize operation. */
332 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
333
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700334 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700335
Wale Ogunwalef6733932018-06-27 05:14:34 -0700336 /**
337 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
338 * change at runtime. Use mContext for non-UI purposes.
339 */
340 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700341 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700342 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700343 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700344 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700345 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700346 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800347 @VisibleForTesting
348 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 PowerManagerInternal mPowerManagerInternal;
350 private UsageStatsManagerInternal mUsageStatsInternal;
351
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700352 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700353 IntentFirewall mIntentFirewall;
354
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700355 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800356 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800357 /**
358 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
359 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
360 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
361 *
362 * @see WindowManagerThreadPriorityBooster
363 */
364 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700365 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800366 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700367 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700368 private UserManagerService mUserManager;
369 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700370 /** All active uids in the system. */
Riddle Hsua0536432019-02-16 00:38:59 +0800371 private final MirrorActiveUids mActiveUids = new MirrorActiveUids();
Wale Ogunwale9de19442018-10-18 19:05:03 -0700372 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700373 /** All processes currently running that might have a window organized by name. */
374 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700375 /** All processes we currently have running mapped by pid */
376 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /** This is the process holding what we currently consider to be the "home" activity. */
378 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700379 /** The currently running heavy-weight process, if any. */
380 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700381 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700382 /**
383 * This is the process holding the activity the user last visited that is in a different process
384 * from the one they are currently in.
385 */
386 WindowProcessController mPreviousProcess;
387 /** The time at which the previous process was last visible. */
388 long mPreviousProcessVisibleTime;
389
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700390 /** List of intents that were used to start the most recent tasks. */
391 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700392 /** State of external calls telling us if the device is awake or asleep. */
393 private boolean mKeyguardShown = false;
394
395 // Wrapper around VoiceInteractionServiceManager
396 private AssistUtils mAssistUtils;
397
398 // VoiceInteraction session ID that changes for each new request except when
399 // being called for multi-window assist in a single session.
400 private int mViSessionId = 1000;
401
402 // How long to wait in getAssistContextExtras for the activity and foreground services
403 // to respond with the result.
404 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
405
406 // How long top wait when going through the modern assist (which doesn't need to block
407 // on getting this result before starting to launch its UI).
408 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
409
410 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
411 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
412
Alison Cichowlas3e340502018-08-07 17:15:01 -0400413 // Permission tokens are used to temporarily granted a trusted app the ability to call
414 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
415 // showing any appropriate error messages to the user.
416 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
417 10 * MINUTE_IN_MILLIS;
418
419 // How long before the service actually expires a token. This is slightly longer than
420 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
421 // expiration exception.
422 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
423 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
424
425 // How long the service will remember expired tokens, for the purpose of providing error
426 // messaging when a client uses an expired token.
427 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
428 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
429
Marvin Ramin830d4e32019-03-12 13:16:58 +0100430 // How long to whitelist the Services for when requested.
431 private static final int SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS = 5 * 1000;
432
Alison Cichowlas3e340502018-08-07 17:15:01 -0400433 // Activity tokens of system activities that are delegating their call to
434 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
435 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
436
437 // Permission tokens that have expired, but we remember for error reporting.
438 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
439
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700440 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
441
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700442 // Keeps track of the active voice interaction service component, notified from
443 // VoiceInteractionManagerService
444 ComponentName mActiveVoiceInteractionServiceComponent;
445
Wale Ogunwalee2172292018-10-25 10:11:10 -0700446 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700447 KeyguardController mKeyguardController;
448 private final ClientLifecycleManager mLifecycleManager;
449 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700450 /** The controller for all operations related to locktask. */
451 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700452 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700453
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700454 boolean mSuppressResizeConfigChanges;
455
456 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
457 new UpdateConfigurationResult();
458
459 static final class UpdateConfigurationResult {
460 // Configuration changes that were updated.
461 int changes;
462 // If the activity was relaunched to match the new configuration.
463 boolean activityRelaunched;
464
465 void reset() {
466 changes = 0;
467 activityRelaunched = false;
468 }
469 }
470
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700471 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700472 private int mConfigurationSeq;
473 // To cache the list of supported system locales
474 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700475
476 /**
477 * Temp object used when global and/or display override configuration is updated. It is also
478 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
479 * anyone...
480 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700481 private Configuration mTempConfig = new Configuration();
482
Wale Ogunwalef6733932018-06-27 05:14:34 -0700483 /** Temporary to avoid allocations. */
484 final StringBuilder mStringBuilder = new StringBuilder(256);
485
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486 // Amount of time after a call to stopAppSwitches() during which we will
487 // prevent further untrusted switches from happening.
488 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
489
490 /**
491 * The time at which we will allow normal application switches again,
492 * after a call to {@link #stopAppSwitches()}.
493 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700495 /**
496 * This is set to true after the first switch after mAppSwitchesAllowedTime
497 * is set; any switches after that will clear the time.
498 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700499 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500
501 IActivityController mController = null;
502 boolean mControllerIsAMonkey = false;
503
Wale Ogunwale214f3482018-10-04 11:00:47 -0700504 final int mFactoryTest;
505
506 /** Used to control how we initialize the service. */
507 ComponentName mTopComponent;
508 String mTopAction = Intent.ACTION_MAIN;
509 String mTopData;
510
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800511 /** Profiling app information. */
512 String mProfileApp = null;
513 WindowProcessController mProfileProc = null;
514 ProfilerInfo mProfilerInfo = null;
515
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700516 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700517 * Dump of the activity state at the time of the last ANR. Cleared after
518 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
519 */
520 String mLastANRState;
521
522 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523 * Used to retain an update lock when the foreground activity is in
524 * immersive mode.
525 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700526 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700527
528 /**
529 * Packages that are being allowed to perform unrestricted app switches. Mapping is
530 * User -> Type -> uid.
531 */
532 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
533
534 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700535 private int mThumbnailWidth;
536 private int mThumbnailHeight;
537 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700538
539 /**
540 * Flag that indicates if multi-window is enabled.
541 *
542 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
543 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
544 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
545 * At least one of the forms of multi-window must be enabled in order for this flag to be
546 * initialized to 'true'.
547 *
548 * @see #mSupportsSplitScreenMultiWindow
549 * @see #mSupportsFreeformWindowManagement
550 * @see #mSupportsPictureInPicture
551 * @see #mSupportsMultiDisplay
552 */
553 boolean mSupportsMultiWindow;
554 boolean mSupportsSplitScreenMultiWindow;
555 boolean mSupportsFreeformWindowManagement;
556 boolean mSupportsPictureInPicture;
557 boolean mSupportsMultiDisplay;
558 boolean mForceResizableActivities;
559
560 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
561
562 // VR Vr2d Display Id.
563 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700564
Wale Ogunwalef6733932018-06-27 05:14:34 -0700565 /**
566 * Set while we are wanting to sleep, to prevent any
567 * activities from being started/resumed.
568 *
569 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
570 *
571 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
572 * while in the sleep state until there is a pending transition out of sleep, in which case
573 * mSleeping is set to false, and remains false while awake.
574 *
575 * Whether mSleeping can quickly toggled between true/false without the device actually
576 * display changing states is undefined.
577 */
578 private boolean mSleeping = false;
579
580 /**
581 * The process state used for processes that are running the top activities.
582 * This changes between TOP and TOP_SLEEPING to following mSleeping.
583 */
584 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
585
586 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
587 // automatically. Important for devices without direct input devices.
588 private boolean mShowDialogs = true;
589
590 /** Set if we are shutting down the system, similar to sleeping. */
591 boolean mShuttingDown = false;
592
593 /**
594 * We want to hold a wake lock while running a voice interaction session, since
595 * this may happen with the screen off and we need to keep the CPU running to
596 * be able to continue to interact with the user.
597 */
598 PowerManager.WakeLock mVoiceWakeLock;
599
600 /**
601 * Set while we are running a voice interaction. This overrides sleeping while it is active.
602 */
603 IVoiceInteractionSession mRunningVoice;
604
605 /**
606 * The last resumed activity. This is identical to the current resumed activity most
607 * of the time but could be different when we're pausing one activity before we resume
608 * another activity.
609 */
610 ActivityRecord mLastResumedActivity;
611
612 /**
613 * The activity that is currently being traced as the active resumed activity.
614 *
615 * @see #updateResumedAppTrace
616 */
617 private @Nullable ActivityRecord mTracedResumedActivity;
618
619 /** If non-null, we are tracking the time the user spends in the currently focused app. */
620 AppTimeTracker mCurAppTimeTracker;
621
Wale Ogunwale008163e2018-07-23 23:11:08 -0700622 private AppWarnings mAppWarnings;
623
Wale Ogunwale53783742018-09-16 10:21:51 -0700624 /**
625 * Packages that the user has asked to have run in screen size
626 * compatibility mode instead of filling the screen.
627 */
628 CompatModePackages mCompatModePackages;
629
Wale Ogunwalef6733932018-06-27 05:14:34 -0700630 private FontScaleSettingObserver mFontScaleSettingObserver;
631
Michal Karpinski4026cae2019-02-12 11:51:47 +0000632 private String mDeviceOwnerPackageName;
633
Wale Ogunwalef6733932018-06-27 05:14:34 -0700634 private final class FontScaleSettingObserver extends ContentObserver {
635 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
636 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
637
638 public FontScaleSettingObserver() {
639 super(mH);
640 final ContentResolver resolver = mContext.getContentResolver();
641 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
642 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
643 UserHandle.USER_ALL);
644 }
645
646 @Override
647 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
648 if (mFontScaleUri.equals(uri)) {
649 updateFontScaleIfNeeded(userId);
650 } else if (mHideErrorDialogsUri.equals(uri)) {
651 synchronized (mGlobalLock) {
652 updateShouldShowDialogsLocked(getGlobalConfiguration());
653 }
654 }
655 }
656 }
657
Riddle Hsua0536432019-02-16 00:38:59 +0800658 /** Indicates that the method may be invoked frequently or is sensitive to performance. */
659 @Target(ElementType.METHOD)
660 @Retention(RetentionPolicy.SOURCE)
661 @interface HotPath {
662 int NONE = 0;
663 int OOM_ADJUSTMENT = 1;
664 int LRU_UPDATE = 2;
665 int PROCESS_CHANGE = 3;
666 int caller() default NONE;
667 }
668
Charles Chen8d98dd22018-12-26 17:36:54 +0800669 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
670 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700671 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700672 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700673 mSystemThread = ActivityThread.currentActivityThread();
674 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700675 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800676 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700677 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700678 }
679
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700680 public void onSystemReady() {
681 synchronized (mGlobalLock) {
682 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
683 PackageManager.FEATURE_CANT_SAVE_STATE);
684 mAssistUtils = new AssistUtils(mContext);
685 mVrController.onSystemReady();
686 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700687 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700688 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700689 }
690
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700691 public void onInitPowerManagement() {
692 synchronized (mGlobalLock) {
693 mStackSupervisor.initPowerManagement();
694 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
695 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
696 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
697 mVoiceWakeLock.setReferenceCounted(false);
698 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700699 }
700
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700701 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700702 mFontScaleSettingObserver = new FontScaleSettingObserver();
703 }
704
Wale Ogunwale59507092018-10-29 09:00:30 -0700705 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700706 final boolean freeformWindowManagement =
707 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
708 || Settings.Global.getInt(
709 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
710
711 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
712 final boolean supportsPictureInPicture = supportsMultiWindow &&
713 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
714 final boolean supportsSplitScreenMultiWindow =
715 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
716 final boolean supportsMultiDisplay = mContext.getPackageManager()
717 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700718 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
719 final boolean forceResizable = Settings.Global.getInt(
720 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700721 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700722
723 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900724 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725
726 final Configuration configuration = new Configuration();
727 Settings.System.getConfiguration(resolver, configuration);
728 if (forceRtl) {
729 // This will take care of setting the correct layout direction flags
730 configuration.setLayoutDirection(configuration.locale);
731 }
732
733 synchronized (mGlobalLock) {
734 mForceResizableActivities = forceResizable;
735 final boolean multiWindowFormEnabled = freeformWindowManagement
736 || supportsSplitScreenMultiWindow
737 || supportsPictureInPicture
738 || supportsMultiDisplay;
739 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
740 mSupportsMultiWindow = true;
741 mSupportsFreeformWindowManagement = freeformWindowManagement;
742 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
743 mSupportsPictureInPicture = supportsPictureInPicture;
744 mSupportsMultiDisplay = supportsMultiDisplay;
745 } else {
746 mSupportsMultiWindow = false;
747 mSupportsFreeformWindowManagement = false;
748 mSupportsSplitScreenMultiWindow = false;
749 mSupportsPictureInPicture = false;
750 mSupportsMultiDisplay = false;
751 }
752 mWindowManager.setForceResizableTasks(mForceResizableActivities);
753 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700754 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
755 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 // This happens before any activities are started, so we can change global configuration
757 // in-place.
758 updateConfigurationLocked(configuration, null, true);
759 final Configuration globalConfig = getGlobalConfiguration();
760 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
761
762 // Load resources only after the current configuration has been set.
763 final Resources res = mContext.getResources();
764 mThumbnailWidth = res.getDimensionPixelSize(
765 com.android.internal.R.dimen.thumbnail_width);
766 mThumbnailHeight = res.getDimensionPixelSize(
767 com.android.internal.R.dimen.thumbnail_height);
768
769 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
770 mFullscreenThumbnailScale = (float) res
771 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
772 (float) globalConfig.screenWidthDp;
773 } else {
774 mFullscreenThumbnailScale = res.getFraction(
775 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
776 }
777 }
778 }
779
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800780 public WindowManagerGlobalLock getGlobalLock() {
781 return mGlobalLock;
782 }
783
Yunfan Chen585f2932019-01-29 16:04:45 +0900784 /** For test purpose only. */
785 @VisibleForTesting
786 public ActivityTaskManagerInternal getAtmInternal() {
787 return mInternal;
788 }
789
Riddle Hsud93a6c42018-11-29 21:50:06 +0800790 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
791 Looper looper) {
792 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700793 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700794 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700795 final File systemDir = SystemServiceManager.ensureSystemDir();
796 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
797 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700798 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700799
800 mTempConfig.setToDefaults();
801 mTempConfig.setLocales(LocaleList.getDefault());
802 mConfigurationSeq = mTempConfig.seq = 1;
803 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800804 mRootActivityContainer = new RootActivityContainer(this);
805 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700806
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700807 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700808 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700809 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700810 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700811 mRecentTasks = createRecentTasks();
812 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700813 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700814 mKeyguardController = mStackSupervisor.getKeyguardController();
815 }
816
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700817 public void onActivityManagerInternalAdded() {
818 synchronized (mGlobalLock) {
819 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
820 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
821 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700822 }
823
Yunfan Chen75157d72018-07-27 14:47:21 +0900824 int increaseConfigurationSeqLocked() {
825 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
826 return mConfigurationSeq;
827 }
828
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700829 protected ActivityStackSupervisor createStackSupervisor() {
830 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
831 supervisor.initialize();
832 return supervisor;
833 }
834
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700835 public void setWindowManager(WindowManagerService wm) {
836 synchronized (mGlobalLock) {
837 mWindowManager = wm;
838 mLockTaskController.setWindowManager(wm);
839 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800840 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700841 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700842 }
843
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700844 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
845 synchronized (mGlobalLock) {
846 mUsageStatsInternal = usageStatsManager;
847 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700848 }
849
Wale Ogunwalef6733932018-06-27 05:14:34 -0700850 UserManagerService getUserManager() {
851 if (mUserManager == null) {
852 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
853 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
854 }
855 return mUserManager;
856 }
857
858 AppOpsService getAppOpsService() {
859 if (mAppOpsService == null) {
860 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
861 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
862 }
863 return mAppOpsService;
864 }
865
866 boolean hasUserRestriction(String restriction, int userId) {
867 return getUserManager().hasUserRestriction(restriction, userId);
868 }
869
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700870 protected RecentTasks createRecentTasks() {
871 return new RecentTasks(this, mStackSupervisor);
872 }
873
874 RecentTasks getRecentTasks() {
875 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700876 }
877
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700878 ClientLifecycleManager getLifecycleManager() {
879 return mLifecycleManager;
880 }
881
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700882 ActivityStartController getActivityStartController() {
883 return mActivityStartController;
884 }
885
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700886 TaskChangeNotificationController getTaskChangeNotificationController() {
887 return mTaskChangeNotificationController;
888 }
889
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700890 LockTaskController getLockTaskController() {
891 return mLockTaskController;
892 }
893
Yunfan Chen75157d72018-07-27 14:47:21 +0900894 /**
895 * Return the global configuration used by the process corresponding to the input pid. This is
896 * usually the global configuration with some overrides specific to that process.
897 */
898 Configuration getGlobalConfigurationForCallingPid() {
899 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800900 return getGlobalConfigurationForPid(pid);
901 }
902
903 /**
904 * Return the global configuration used by the process corresponding to the given pid.
905 */
906 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900907 if (pid == MY_PID || pid < 0) {
908 return getGlobalConfiguration();
909 }
910 synchronized (mGlobalLock) {
911 final WindowProcessController app = mPidMap.get(pid);
912 return app != null ? app.getConfiguration() : getGlobalConfiguration();
913 }
914 }
915
916 /**
917 * Return the device configuration info used by the process corresponding to the input pid.
918 * The value is consistent with the global configuration for the process.
919 */
920 @Override
921 public ConfigurationInfo getDeviceConfigurationInfo() {
922 ConfigurationInfo config = new ConfigurationInfo();
923 synchronized (mGlobalLock) {
924 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
925 config.reqTouchScreen = globalConfig.touchscreen;
926 config.reqKeyboardType = globalConfig.keyboard;
927 config.reqNavigation = globalConfig.navigation;
928 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
929 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
930 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
931 }
932 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
933 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
934 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
935 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700936 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900937 }
938 return config;
939 }
940
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700941 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700942 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700943 }
944
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700945 public static final class Lifecycle extends SystemService {
946 private final ActivityTaskManagerService mService;
947
948 public Lifecycle(Context context) {
949 super(context);
950 mService = new ActivityTaskManagerService(context);
951 }
952
953 @Override
954 public void onStart() {
955 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700956 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700957 }
958
Garfield Tan891146c2018-10-09 12:14:00 -0700959 @Override
960 public void onUnlockUser(int userId) {
961 synchronized (mService.getGlobalLock()) {
Garfield Tan0d407f42019-03-07 11:47:01 -0800962 mService.mStackSupervisor.onUserUnlocked(userId);
Garfield Tan891146c2018-10-09 12:14:00 -0700963 }
964 }
965
966 @Override
967 public void onCleanupUser(int userId) {
968 synchronized (mService.getGlobalLock()) {
969 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
970 }
971 }
972
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700973 public ActivityTaskManagerService getService() {
974 return mService;
975 }
976 }
977
978 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700979 public final int startActivity(IApplicationThread caller, String callingPackage,
980 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
981 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
982 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
983 resultWho, requestCode, startFlags, profilerInfo, bOptions,
984 UserHandle.getCallingUserId());
985 }
986
987 @Override
988 public final int startActivities(IApplicationThread caller, String callingPackage,
989 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
990 int userId) {
991 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700992 enforceNotIsolatedCaller(reason);
993 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700994 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000995 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
996 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
997 reason, null /* originatingPendingIntent */,
998 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700999 }
1000
1001 @Override
1002 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
1003 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1004 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1005 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
1006 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
1007 true /*validateIncomingUser*/);
1008 }
1009
1010 int startActivityAsUser(IApplicationThread caller, String callingPackage,
1011 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1012 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
1013 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001014 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001016 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
1018
1019 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001020 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001021 .setCaller(caller)
1022 .setCallingPackage(callingPackage)
1023 .setResolvedType(resolvedType)
1024 .setResultTo(resultTo)
1025 .setResultWho(resultWho)
1026 .setRequestCode(requestCode)
1027 .setStartFlags(startFlags)
1028 .setProfilerInfo(profilerInfo)
1029 .setActivityOptions(bOptions)
1030 .setMayWait(userId)
1031 .execute();
1032
1033 }
1034
1035 @Override
1036 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1037 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001038 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1039 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001040 // Refuse possible leaked file descriptors
1041 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1042 throw new IllegalArgumentException("File descriptors passed in Intent");
1043 }
1044
1045 if (!(target instanceof PendingIntentRecord)) {
1046 throw new IllegalArgumentException("Bad PendingIntent object");
1047 }
1048
1049 PendingIntentRecord pir = (PendingIntentRecord)target;
1050
1051 synchronized (mGlobalLock) {
1052 // If this is coming from the currently resumed activity, it is
1053 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001054 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 if (stack.mResumedActivity != null &&
1056 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001057 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001058 }
1059 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001060 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001061 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001062 }
1063
1064 @Override
1065 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1066 Bundle bOptions) {
1067 // Refuse possible leaked file descriptors
1068 if (intent != null && intent.hasFileDescriptors()) {
1069 throw new IllegalArgumentException("File descriptors passed in Intent");
1070 }
1071 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1072
1073 synchronized (mGlobalLock) {
1074 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1075 if (r == null) {
1076 SafeActivityOptions.abort(options);
1077 return false;
1078 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001079 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001080 // The caller is not running... d'oh!
1081 SafeActivityOptions.abort(options);
1082 return false;
1083 }
1084 intent = new Intent(intent);
1085 // The caller is not allowed to change the data.
1086 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1087 // And we are resetting to find the next component...
1088 intent.setComponent(null);
1089
1090 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1091
1092 ActivityInfo aInfo = null;
1093 try {
1094 List<ResolveInfo> resolves =
1095 AppGlobals.getPackageManager().queryIntentActivities(
1096 intent, r.resolvedType,
1097 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1098 UserHandle.getCallingUserId()).getList();
1099
1100 // Look for the original activity in the list...
1101 final int N = resolves != null ? resolves.size() : 0;
1102 for (int i=0; i<N; i++) {
1103 ResolveInfo rInfo = resolves.get(i);
1104 if (rInfo.activityInfo.packageName.equals(r.packageName)
1105 && rInfo.activityInfo.name.equals(r.info.name)) {
1106 // We found the current one... the next matching is
1107 // after it.
1108 i++;
1109 if (i<N) {
1110 aInfo = resolves.get(i).activityInfo;
1111 }
1112 if (debug) {
1113 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1114 + "/" + r.info.name);
1115 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1116 ? "null" : aInfo.packageName + "/" + aInfo.name));
1117 }
1118 break;
1119 }
1120 }
1121 } catch (RemoteException e) {
1122 }
1123
1124 if (aInfo == null) {
1125 // Nobody who is next!
1126 SafeActivityOptions.abort(options);
1127 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1128 return false;
1129 }
1130
1131 intent.setComponent(new ComponentName(
1132 aInfo.applicationInfo.packageName, aInfo.name));
1133 intent.setFlags(intent.getFlags()&~(
1134 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1135 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1136 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1137 FLAG_ACTIVITY_NEW_TASK));
1138
1139 // Okay now we need to start the new activity, replacing the currently running activity.
1140 // This is a little tricky because we want to start the new one as if the current one is
1141 // finished, but not finish the current one first so that there is no flicker.
1142 // And thus...
1143 final boolean wasFinishing = r.finishing;
1144 r.finishing = true;
1145
1146 // Propagate reply information over to the new activity.
1147 final ActivityRecord resultTo = r.resultTo;
1148 final String resultWho = r.resultWho;
1149 final int requestCode = r.requestCode;
1150 r.resultTo = null;
1151 if (resultTo != null) {
1152 resultTo.removeResultsLocked(r, resultWho, requestCode);
1153 }
1154
1155 final long origId = Binder.clearCallingIdentity();
1156 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001157 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001158 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001159 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001160 .setResolvedType(r.resolvedType)
1161 .setActivityInfo(aInfo)
1162 .setResultTo(resultTo != null ? resultTo.appToken : null)
1163 .setResultWho(resultWho)
1164 .setRequestCode(requestCode)
1165 .setCallingPid(-1)
1166 .setCallingUid(r.launchedFromUid)
1167 .setCallingPackage(r.launchedFromPackage)
1168 .setRealCallingPid(-1)
1169 .setRealCallingUid(r.launchedFromUid)
1170 .setActivityOptions(options)
1171 .execute();
1172 Binder.restoreCallingIdentity(origId);
1173
1174 r.finishing = wasFinishing;
1175 if (res != ActivityManager.START_SUCCESS) {
1176 return false;
1177 }
1178 return true;
1179 }
1180 }
1181
1182 @Override
1183 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1184 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1185 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1186 final WaitResult res = new WaitResult();
1187 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001188 enforceNotIsolatedCaller("startActivityAndWait");
1189 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1190 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001191 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001192 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001193 .setCaller(caller)
1194 .setCallingPackage(callingPackage)
1195 .setResolvedType(resolvedType)
1196 .setResultTo(resultTo)
1197 .setResultWho(resultWho)
1198 .setRequestCode(requestCode)
1199 .setStartFlags(startFlags)
1200 .setActivityOptions(bOptions)
1201 .setMayWait(userId)
1202 .setProfilerInfo(profilerInfo)
1203 .setWaitResult(res)
1204 .execute();
1205 }
1206 return res;
1207 }
1208
1209 @Override
1210 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1211 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1212 int startFlags, Configuration config, Bundle bOptions, int userId) {
1213 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001214 enforceNotIsolatedCaller("startActivityWithConfig");
1215 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1216 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001217 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001218 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001219 .setCaller(caller)
1220 .setCallingPackage(callingPackage)
1221 .setResolvedType(resolvedType)
1222 .setResultTo(resultTo)
1223 .setResultWho(resultWho)
1224 .setRequestCode(requestCode)
1225 .setStartFlags(startFlags)
1226 .setGlobalConfiguration(config)
1227 .setActivityOptions(bOptions)
1228 .setMayWait(userId)
1229 .execute();
1230 }
1231 }
1232
Alison Cichowlas3e340502018-08-07 17:15:01 -04001233
1234 @Override
1235 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1236 int callingUid = Binder.getCallingUid();
1237 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1238 throw new SecurityException("Only the system process can request a permission token, "
1239 + "received request from uid: " + callingUid);
1240 }
1241 IBinder permissionToken = new Binder();
1242 synchronized (mGlobalLock) {
1243 mStartActivitySources.put(permissionToken, delegatorToken);
1244 }
1245
1246 Message expireMsg = PooledLambda.obtainMessage(
1247 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1248 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1249
1250 Message forgetMsg = PooledLambda.obtainMessage(
1251 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1252 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1253
1254 return permissionToken;
1255 }
1256
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001257 @Override
1258 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1259 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001260 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1261 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001262 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001263 // permission grants) as any app that may launch one of your own activities. So we only
1264 // allow this in two cases:
1265 // 1) The caller is an activity that is part of the core framework, and then only when it
1266 // is running as the system.
1267 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1268 // can only be requested by a system activity, which may then delegate this call to
1269 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001270 final ActivityRecord sourceRecord;
1271 final int targetUid;
1272 final String targetPackage;
1273 final boolean isResolver;
1274 synchronized (mGlobalLock) {
1275 if (resultTo == null) {
1276 throw new SecurityException("Must be called from an activity");
1277 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001278 final IBinder sourceToken;
1279 if (permissionToken != null) {
1280 // To even attempt to use a permissionToken, an app must also have this signature
1281 // permission.
1282 mAmInternal.enforceCallingPermission(
1283 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1284 "startActivityAsCaller");
1285 // If called with a permissionToken, we want the sourceRecord from the delegator
1286 // activity that requested this token.
1287 sourceToken = mStartActivitySources.remove(permissionToken);
1288 if (sourceToken == null) {
1289 // Invalid permissionToken, check if it recently expired.
1290 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1291 throw new SecurityException("Called with expired permission token: "
1292 + permissionToken);
1293 } else {
1294 throw new SecurityException("Called with invalid permission token: "
1295 + permissionToken);
1296 }
1297 }
1298 } else {
1299 // This method was called directly by the source.
1300 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001301 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001302
Wale Ogunwaled32da472018-11-16 07:19:28 -08001303 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001304 if (sourceRecord == null) {
1305 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001306 }
1307 if (sourceRecord.app == null) {
1308 throw new SecurityException("Called without a process attached to activity");
1309 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001310
1311 // Whether called directly or from a delegate, the source activity must be from the
1312 // android package.
1313 if (!sourceRecord.info.packageName.equals("android")) {
1314 throw new SecurityException("Must be called from an activity that is "
1315 + "declared in the android package");
1316 }
1317
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001318 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001319 // This is still okay, as long as this activity is running under the
1320 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001321 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001322 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001323 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001324 + " must be system uid or original calling uid "
1325 + sourceRecord.launchedFromUid);
1326 }
1327 }
1328 if (ignoreTargetSecurity) {
1329 if (intent.getComponent() == null) {
1330 throw new SecurityException(
1331 "Component must be specified with ignoreTargetSecurity");
1332 }
1333 if (intent.getSelector() != null) {
1334 throw new SecurityException(
1335 "Selector not allowed with ignoreTargetSecurity");
1336 }
1337 }
1338 targetUid = sourceRecord.launchedFromUid;
1339 targetPackage = sourceRecord.launchedFromPackage;
1340 isResolver = sourceRecord.isResolverOrChildActivity();
1341 }
1342
1343 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001344 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001345 }
1346
1347 // TODO: Switch to user app stacks here.
1348 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001349 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 .setCallingUid(targetUid)
1351 .setCallingPackage(targetPackage)
1352 .setResolvedType(resolvedType)
1353 .setResultTo(resultTo)
1354 .setResultWho(resultWho)
1355 .setRequestCode(requestCode)
1356 .setStartFlags(startFlags)
1357 .setActivityOptions(bOptions)
1358 .setMayWait(userId)
1359 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1360 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1361 .execute();
1362 } catch (SecurityException e) {
1363 // XXX need to figure out how to propagate to original app.
1364 // A SecurityException here is generally actually a fault of the original
1365 // calling activity (such as a fairly granting permissions), so propagate it
1366 // back to them.
1367 /*
1368 StringBuilder msg = new StringBuilder();
1369 msg.append("While launching");
1370 msg.append(intent.toString());
1371 msg.append(": ");
1372 msg.append(e.getMessage());
1373 */
1374 throw e;
1375 }
1376 }
1377
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001378 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1379 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1380 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1381 }
1382
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001383 @Override
1384 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1385 Intent intent, String resolvedType, IVoiceInteractionSession session,
1386 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1387 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001388 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001389 if (session == null || interactor == null) {
1390 throw new NullPointerException("null session or interactor");
1391 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001392 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001393 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001394 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001395 .setCallingUid(callingUid)
1396 .setCallingPackage(callingPackage)
1397 .setResolvedType(resolvedType)
1398 .setVoiceSession(session)
1399 .setVoiceInteractor(interactor)
1400 .setStartFlags(startFlags)
1401 .setProfilerInfo(profilerInfo)
1402 .setActivityOptions(bOptions)
1403 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001404 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001405 .execute();
1406 }
1407
1408 @Override
1409 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1410 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1412 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001414 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 .setCallingUid(callingUid)
1416 .setCallingPackage(callingPackage)
1417 .setResolvedType(resolvedType)
1418 .setActivityOptions(bOptions)
1419 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001420 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001421 .execute();
1422 }
1423
1424 @Override
1425 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1426 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001427 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001428 final int callingPid = Binder.getCallingPid();
1429 final long origId = Binder.clearCallingIdentity();
1430 try {
1431 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001432 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1433 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001434
1435 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001436 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1437 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001438 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1439 recentsUid, assistDataReceiver);
1440 }
1441 } finally {
1442 Binder.restoreCallingIdentity(origId);
1443 }
1444 }
1445
1446 @Override
1447 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001448 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 "startActivityFromRecents()");
1450
1451 final int callingPid = Binder.getCallingPid();
1452 final int callingUid = Binder.getCallingUid();
1453 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1454 final long origId = Binder.clearCallingIdentity();
1455 try {
1456 synchronized (mGlobalLock) {
1457 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1458 safeOptions);
1459 }
1460 } finally {
1461 Binder.restoreCallingIdentity(origId);
1462 }
1463 }
1464
1465 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001466 * Public API to check if the client is allowed to start an activity on specified display.
1467 *
1468 * If the target display is private or virtual, some restrictions will apply.
1469 *
1470 * @param displayId Target display id.
1471 * @param intent Intent used to launch the activity.
1472 * @param resolvedType The MIME type of the intent.
1473 * @param userId The id of the user for whom the call is made.
1474 * @return {@code true} if a call to start an activity on the target display should succeed and
1475 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1476 */
1477 @Override
1478 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1479 String resolvedType, int userId) {
1480 final int callingUid = Binder.getCallingUid();
1481 final int callingPid = Binder.getCallingPid();
1482 final long origId = Binder.clearCallingIdentity();
1483
1484 try {
1485 // Collect information about the target of the Intent.
1486 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1487 0 /* startFlags */, null /* profilerInfo */, userId,
1488 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1489 UserHandle.USER_NULL));
1490 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1491
1492 synchronized (mGlobalLock) {
1493 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1494 aInfo);
1495 }
1496 } finally {
1497 Binder.restoreCallingIdentity(origId);
1498 }
1499 }
1500
1501 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 * This is the internal entry point for handling Activity.finish().
1503 *
1504 * @param token The Binder token referencing the Activity we want to finish.
1505 * @param resultCode Result code, if any, from this Activity.
1506 * @param resultData Result data (Intent), if any, from this Activity.
1507 * @param finishTask Whether to finish the task associated with this Activity.
1508 *
1509 * @return Returns true if the activity successfully finished, or false if it is still running.
1510 */
1511 @Override
1512 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1513 int finishTask) {
1514 // Refuse possible leaked file descriptors
1515 if (resultData != null && resultData.hasFileDescriptors()) {
1516 throw new IllegalArgumentException("File descriptors passed in Intent");
1517 }
1518
1519 synchronized (mGlobalLock) {
1520 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1521 if (r == null) {
1522 return true;
1523 }
1524 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001525 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001526 ActivityRecord rootR = tr.getRootActivity();
1527 if (rootR == null) {
1528 Slog.w(TAG, "Finishing task with all activities already finished");
1529 }
1530 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1531 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001532 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001533 return false;
1534 }
1535
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001536 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1537 // We should consolidate.
1538 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001540 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001541 if (next != null) {
1542 // ask watcher if this is allowed
1543 boolean resumeOK = true;
1544 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001545 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001547 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001548 Watchdog.getInstance().setActivityController(null);
1549 }
1550
1551 if (!resumeOK) {
1552 Slog.i(TAG, "Not finishing activity because controller resumed");
1553 return false;
1554 }
1555 }
1556 }
1557 final long origId = Binder.clearCallingIdentity();
1558 try {
1559 boolean res;
1560 final boolean finishWithRootActivity =
1561 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1562 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1563 || (finishWithRootActivity && r == rootR)) {
1564 // If requested, remove the task that is associated to this activity only if it
1565 // was the root activity in the task. The result code and data is ignored
1566 // because we don't support returning them across task boundaries. Also, to
1567 // keep backwards compatibility we remove the task from recents when finishing
1568 // task with root activity.
1569 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1570 finishWithRootActivity, "finish-activity");
1571 if (!res) {
1572 Slog.i(TAG, "Removing task failed to finish activity");
1573 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001574 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001575 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001576 } else {
1577 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1578 resultData, "app-request", true);
1579 if (!res) {
1580 Slog.i(TAG, "Failed to finish by app-request");
1581 }
1582 }
1583 return res;
1584 } finally {
1585 Binder.restoreCallingIdentity(origId);
1586 }
1587 }
1588 }
1589
1590 @Override
1591 public boolean finishActivityAffinity(IBinder token) {
1592 synchronized (mGlobalLock) {
1593 final long origId = Binder.clearCallingIdentity();
1594 try {
1595 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1596 if (r == null) {
1597 return false;
1598 }
1599
1600 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1601 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001602 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001603 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001604 return false;
1605 }
1606 return task.getStack().finishActivityAffinityLocked(r);
1607 } finally {
1608 Binder.restoreCallingIdentity(origId);
1609 }
1610 }
1611 }
1612
1613 @Override
1614 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1615 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001616 try {
1617 WindowProcessController proc = null;
1618 synchronized (mGlobalLock) {
1619 ActivityStack stack = ActivityRecord.getStackLocked(token);
1620 if (stack == null) {
1621 return;
1622 }
1623 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1624 false /* fromTimeout */, false /* processPausingActivities */, config);
1625 if (r != null) {
1626 proc = r.app;
1627 }
1628 if (stopProfiling && proc != null) {
1629 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001630 }
1631 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001632 } finally {
1633 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001635 }
1636
1637 @Override
1638 public final void activityResumed(IBinder token) {
1639 final long origId = Binder.clearCallingIdentity();
1640 synchronized (mGlobalLock) {
1641 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001642 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001643 }
1644 Binder.restoreCallingIdentity(origId);
1645 }
1646
1647 @Override
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001648 public final void activityTopResumedStateLost() {
1649 final long origId = Binder.clearCallingIdentity();
1650 synchronized (mGlobalLock) {
1651 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1652 }
1653 Binder.restoreCallingIdentity(origId);
1654 }
1655
1656 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001657 public final void activityPaused(IBinder token) {
1658 final long origId = Binder.clearCallingIdentity();
1659 synchronized (mGlobalLock) {
1660 ActivityStack stack = ActivityRecord.getStackLocked(token);
1661 if (stack != null) {
1662 stack.activityPausedLocked(token, false);
1663 }
1664 }
1665 Binder.restoreCallingIdentity(origId);
1666 }
1667
1668 @Override
1669 public final void activityStopped(IBinder token, Bundle icicle,
1670 PersistableBundle persistentState, CharSequence description) {
1671 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1672
1673 // Refuse possible leaked file descriptors
1674 if (icicle != null && icicle.hasFileDescriptors()) {
1675 throw new IllegalArgumentException("File descriptors passed in Bundle");
1676 }
1677
1678 final long origId = Binder.clearCallingIdentity();
1679
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001680 String restartingName = null;
1681 int restartingUid = 0;
1682 final ActivityRecord r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001683 synchronized (mGlobalLock) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001684 r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001685 if (r != null) {
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001686 if (r.attachedToProcess()
1687 && r.isState(ActivityStack.ActivityState.RESTARTING_PROCESS)) {
1688 // The activity was requested to restart from
1689 // {@link #restartActivityProcessIfVisible}.
1690 restartingName = r.app.mName;
1691 restartingUid = r.app.mUid;
1692 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001693 r.activityStoppedLocked(icicle, persistentState, description);
1694 }
1695 }
1696
Riddle Hsu7b766fd2019-01-28 21:14:59 +08001697 if (restartingName != null) {
1698 // In order to let the foreground activity can be restarted with its saved state from
1699 // {@link android.app.Activity#onSaveInstanceState}, the kill operation is postponed
1700 // until the activity reports stopped with the state. And the activity record will be
1701 // kept because the record state is restarting, then the activity will be restarted
1702 // immediately if it is still the top one.
1703 mStackSupervisor.removeRestartTimeouts(r);
1704 mAmInternal.killProcess(restartingName, restartingUid, "restartActivityProcess");
1705 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001706 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001707
1708 Binder.restoreCallingIdentity(origId);
1709 }
1710
1711 @Override
1712 public final void activityDestroyed(IBinder token) {
1713 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1714 synchronized (mGlobalLock) {
1715 ActivityStack stack = ActivityRecord.getStackLocked(token);
1716 if (stack != null) {
1717 stack.activityDestroyedLocked(token, "activityDestroyed");
1718 }
1719 }
1720 }
1721
1722 @Override
1723 public final void activityRelaunched(IBinder token) {
1724 final long origId = Binder.clearCallingIdentity();
1725 synchronized (mGlobalLock) {
1726 mStackSupervisor.activityRelaunchedLocked(token);
1727 }
1728 Binder.restoreCallingIdentity(origId);
1729 }
1730
1731 public final void activitySlept(IBinder token) {
1732 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1733
1734 final long origId = Binder.clearCallingIdentity();
1735
1736 synchronized (mGlobalLock) {
1737 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1738 if (r != null) {
1739 mStackSupervisor.activitySleptLocked(r);
1740 }
1741 }
1742
1743 Binder.restoreCallingIdentity(origId);
1744 }
1745
1746 @Override
1747 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1748 synchronized (mGlobalLock) {
1749 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1750 if (r == null) {
1751 return;
1752 }
1753 final long origId = Binder.clearCallingIdentity();
1754 try {
1755 r.setRequestedOrientation(requestedOrientation);
1756 } finally {
1757 Binder.restoreCallingIdentity(origId);
1758 }
1759 }
1760 }
1761
1762 @Override
1763 public int getRequestedOrientation(IBinder token) {
1764 synchronized (mGlobalLock) {
1765 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1766 if (r == null) {
1767 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1768 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001769 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 }
1771 }
1772
1773 @Override
1774 public void setImmersive(IBinder token, boolean immersive) {
1775 synchronized (mGlobalLock) {
1776 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1777 if (r == null) {
1778 throw new IllegalArgumentException();
1779 }
1780 r.immersive = immersive;
1781
1782 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001783 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001784 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001785 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001786 }
1787 }
1788 }
1789
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001790 void applyUpdateLockStateLocked(ActivityRecord r) {
1791 // Modifications to the UpdateLock state are done on our handler, outside
1792 // the activity manager's locks. The new state is determined based on the
1793 // state *now* of the relevant activity record. The object is passed to
1794 // the handler solely for logging detail, not to be consulted/modified.
1795 final boolean nextState = r != null && r.immersive;
1796 mH.post(() -> {
1797 if (mUpdateLock.isHeld() != nextState) {
1798 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1799 "Applying new update lock state '" + nextState + "' for " + r);
1800 if (nextState) {
1801 mUpdateLock.acquire();
1802 } else {
1803 mUpdateLock.release();
1804 }
1805 }
1806 });
1807 }
1808
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001809 @Override
1810 public boolean isImmersive(IBinder token) {
1811 synchronized (mGlobalLock) {
1812 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1813 if (r == null) {
1814 throw new IllegalArgumentException();
1815 }
1816 return r.immersive;
1817 }
1818 }
1819
1820 @Override
1821 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001822 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001823 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001824 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001825 return (r != null) ? r.immersive : false;
1826 }
1827 }
1828
1829 @Override
1830 public void overridePendingTransition(IBinder token, String packageName,
1831 int enterAnim, int exitAnim) {
1832 synchronized (mGlobalLock) {
1833 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1834 if (self == null) {
1835 return;
1836 }
1837
1838 final long origId = Binder.clearCallingIdentity();
1839
1840 if (self.isState(
1841 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001842 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001843 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001844 }
1845
1846 Binder.restoreCallingIdentity(origId);
1847 }
1848 }
1849
1850 @Override
1851 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001852 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001853 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001854 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001855 if (r == null) {
1856 return ActivityManager.COMPAT_MODE_UNKNOWN;
1857 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001858 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001859 }
1860 }
1861
1862 @Override
1863 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001864 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001865 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001866 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001867 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001868 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001869 if (r == null) {
1870 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1871 return;
1872 }
1873 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001874 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001875 }
1876 }
1877
1878 @Override
1879 public int getLaunchedFromUid(IBinder activityToken) {
1880 ActivityRecord srec;
1881 synchronized (mGlobalLock) {
1882 srec = ActivityRecord.forTokenLocked(activityToken);
1883 }
1884 if (srec == null) {
1885 return -1;
1886 }
1887 return srec.launchedFromUid;
1888 }
1889
1890 @Override
1891 public String getLaunchedFromPackage(IBinder activityToken) {
1892 ActivityRecord srec;
1893 synchronized (mGlobalLock) {
1894 srec = ActivityRecord.forTokenLocked(activityToken);
1895 }
1896 if (srec == null) {
1897 return null;
1898 }
1899 return srec.launchedFromPackage;
1900 }
1901
1902 @Override
1903 public boolean convertFromTranslucent(IBinder token) {
1904 final long origId = Binder.clearCallingIdentity();
1905 try {
1906 synchronized (mGlobalLock) {
1907 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1908 if (r == null) {
1909 return false;
1910 }
1911 final boolean translucentChanged = r.changeWindowTranslucency(true);
1912 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001913 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001914 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 return translucentChanged;
1917 }
1918 } finally {
1919 Binder.restoreCallingIdentity(origId);
1920 }
1921 }
1922
1923 @Override
1924 public boolean convertToTranslucent(IBinder token, Bundle options) {
1925 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1926 final long origId = Binder.clearCallingIdentity();
1927 try {
1928 synchronized (mGlobalLock) {
1929 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1930 if (r == null) {
1931 return false;
1932 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001933 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001934 int index = task.mActivities.lastIndexOf(r);
1935 if (index > 0) {
1936 ActivityRecord under = task.mActivities.get(index - 1);
1937 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1938 }
1939 final boolean translucentChanged = r.changeWindowTranslucency(false);
1940 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001941 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001942 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001943 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001944 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 return translucentChanged;
1946 }
1947 } finally {
1948 Binder.restoreCallingIdentity(origId);
1949 }
1950 }
1951
1952 @Override
1953 public void notifyActivityDrawn(IBinder token) {
1954 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1955 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001956 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001958 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001959 }
1960 }
1961 }
1962
1963 @Override
1964 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1965 synchronized (mGlobalLock) {
1966 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1967 if (r == null) {
1968 return;
1969 }
1970 r.reportFullyDrawnLocked(restoredFromBundle);
1971 }
1972 }
1973
1974 @Override
1975 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1976 synchronized (mGlobalLock) {
1977 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1978 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1979 return stack.mDisplayId;
1980 }
1981 return DEFAULT_DISPLAY;
1982 }
1983 }
1984
1985 @Override
1986 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001987 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001988 long ident = Binder.clearCallingIdentity();
1989 try {
1990 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001991 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001992 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001993 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001994 }
1995 return null;
1996 }
1997 } finally {
1998 Binder.restoreCallingIdentity(ident);
1999 }
2000 }
2001
2002 @Override
2003 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002004 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
2006 final long callingId = Binder.clearCallingIdentity();
2007 try {
2008 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002009 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002010 if (stack == null) {
2011 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
2012 return;
2013 }
2014 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002015 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002016 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002017 }
2018 }
2019 } finally {
2020 Binder.restoreCallingIdentity(callingId);
2021 }
2022 }
2023
2024 @Override
2025 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002026 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
2028 final long callingId = Binder.clearCallingIdentity();
2029 try {
2030 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002031 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002032 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002033 if (task == null) {
2034 return;
2035 }
2036 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08002037 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002038 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002039 }
2040 }
2041 } finally {
2042 Binder.restoreCallingIdentity(callingId);
2043 }
2044 }
2045
2046 @Override
Riddle Hsu7b766fd2019-01-28 21:14:59 +08002047 public void restartActivityProcessIfVisible(IBinder activityToken) {
2048 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "restartActivityProcess()");
2049 final long callingId = Binder.clearCallingIdentity();
2050 try {
2051 synchronized (mGlobalLock) {
2052 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2053 if (r == null) {
2054 return;
2055 }
2056 r.restartProcessIfVisible();
2057 }
2058 } finally {
2059 Binder.restoreCallingIdentity(callingId);
2060 }
2061 }
2062
2063 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002064 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002065 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002066 synchronized (mGlobalLock) {
2067 final long ident = Binder.clearCallingIdentity();
2068 try {
2069 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2070 "remove-task");
2071 } finally {
2072 Binder.restoreCallingIdentity(ident);
2073 }
2074 }
2075 }
2076
2077 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002078 public void removeAllVisibleRecentTasks() {
2079 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2080 synchronized (mGlobalLock) {
2081 final long ident = Binder.clearCallingIdentity();
2082 try {
2083 getRecentTasks().removeAllVisibleTasks();
2084 } finally {
2085 Binder.restoreCallingIdentity(ident);
2086 }
2087 }
2088 }
2089
2090 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002091 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2092 synchronized (mGlobalLock) {
2093 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2094 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002095 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002096 }
2097 }
2098 return false;
2099 }
2100
2101 @Override
2102 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2103 Intent resultData) {
2104
2105 synchronized (mGlobalLock) {
2106 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2107 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002108 return r.getActivityStack().navigateUpToLocked(
2109 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 }
2111 return false;
2112 }
2113 }
2114
2115 /**
2116 * Attempts to move a task backwards in z-order (the order of activities within the task is
2117 * unchanged).
2118 *
2119 * There are several possible results of this call:
2120 * - if the task is locked, then we will show the lock toast
2121 * - if there is a task behind the provided task, then that task is made visible and resumed as
2122 * this task is moved to the back
2123 * - otherwise, if there are no other tasks in the stack:
2124 * - if this task is in the pinned stack, then we remove the stack completely, which will
2125 * have the effect of moving the task to the top or bottom of the fullscreen stack
2126 * (depending on whether it is visible)
2127 * - otherwise, we simply return home and hide this task
2128 *
2129 * @param token A reference to the activity we wish to move
2130 * @param nonRoot If false then this only works if the activity is the root
2131 * of a task; if true it will work for any activity in a task.
2132 * @return Returns true if the move completed, false if not.
2133 */
2134 @Override
2135 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002136 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002137 synchronized (mGlobalLock) {
2138 final long origId = Binder.clearCallingIdentity();
2139 try {
2140 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002141 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002142 if (task != null) {
2143 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2144 }
2145 } finally {
2146 Binder.restoreCallingIdentity(origId);
2147 }
2148 }
2149 return false;
2150 }
2151
2152 @Override
2153 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002154 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 long ident = Binder.clearCallingIdentity();
2156 Rect rect = new Rect();
2157 try {
2158 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002159 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002160 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2161 if (task == null) {
2162 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2163 return rect;
2164 }
2165 if (task.getStack() != null) {
2166 // Return the bounds from window manager since it will be adjusted for various
2167 // things like the presense of a docked stack for tasks that aren't resizeable.
2168 task.getWindowContainerBounds(rect);
2169 } else {
2170 // Task isn't in window manager yet since it isn't associated with a stack.
2171 // Return the persist value from activity manager
2172 if (!task.matchParentBounds()) {
2173 rect.set(task.getBounds());
2174 } else if (task.mLastNonFullscreenBounds != null) {
2175 rect.set(task.mLastNonFullscreenBounds);
2176 }
2177 }
2178 }
2179 } finally {
2180 Binder.restoreCallingIdentity(ident);
2181 }
2182 return rect;
2183 }
2184
2185 @Override
2186 public ActivityManager.TaskDescription getTaskDescription(int id) {
2187 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002188 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002189 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002190 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002191 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2192 if (tr != null) {
2193 return tr.lastTaskDescription;
2194 }
2195 }
2196 return null;
2197 }
2198
2199 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002200 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2201 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2202 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2203 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2204 return;
2205 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002206 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002207 synchronized (mGlobalLock) {
2208 final long ident = Binder.clearCallingIdentity();
2209 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002210 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002211 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002212 if (task == null) {
2213 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2214 return;
2215 }
2216
2217 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2218 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2219
2220 if (!task.isActivityTypeStandardOrUndefined()) {
2221 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2222 + " non-standard task " + taskId + " to windowing mode="
2223 + windowingMode);
2224 }
2225
2226 final ActivityStack stack = task.getStack();
2227 if (toTop) {
2228 stack.moveToFront("setTaskWindowingMode", task);
2229 }
2230 stack.setWindowingMode(windowingMode);
2231 } finally {
2232 Binder.restoreCallingIdentity(ident);
2233 }
2234 }
2235 }
2236
2237 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002239 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002240 ActivityRecord r = getCallingRecordLocked(token);
2241 return r != null ? r.info.packageName : null;
2242 }
2243 }
2244
2245 @Override
2246 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002248 ActivityRecord r = getCallingRecordLocked(token);
2249 return r != null ? r.intent.getComponent() : null;
2250 }
2251 }
2252
2253 private ActivityRecord getCallingRecordLocked(IBinder token) {
2254 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2255 if (r == null) {
2256 return null;
2257 }
2258 return r.resultTo;
2259 }
2260
2261 @Override
2262 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002263 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002264
2265 synchronized (mGlobalLock) {
2266 final long origId = Binder.clearCallingIdentity();
2267 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002268 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002269 } finally {
2270 Binder.restoreCallingIdentity(origId);
2271 }
2272 }
2273 }
2274
2275 /**
2276 * TODO: Add mController hook
2277 */
2278 @Override
2279 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002280 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002281
2282 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2283 synchronized (mGlobalLock) {
2284 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2285 false /* fromRecents */);
2286 }
2287 }
2288
2289 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2290 boolean fromRecents) {
2291
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002292 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002293 Binder.getCallingUid(), -1, -1, "Task to front")) {
2294 SafeActivityOptions.abort(options);
2295 return;
2296 }
2297 final long origId = Binder.clearCallingIdentity();
2298 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002299 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002300 if (task == null) {
2301 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002302 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002303 return;
2304 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002305 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002306 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002307 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 return;
2309 }
2310 ActivityOptions realOptions = options != null
2311 ? options.getOptions(mStackSupervisor)
2312 : null;
2313 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2314 false /* forceNonResizable */);
2315
2316 final ActivityRecord topActivity = task.getTopActivity();
2317 if (topActivity != null) {
2318
2319 // We are reshowing a task, use a starting window to hide the initial draw delay
2320 // so the transition can start earlier.
2321 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2322 true /* taskSwitch */, fromRecents);
2323 }
2324 } finally {
2325 Binder.restoreCallingIdentity(origId);
2326 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002327 }
2328
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002329 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2330 int callingPid, int callingUid, String name) {
2331 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2332 return true;
2333 }
2334
2335 if (getRecentTasks().isCallerRecents(sourceUid)) {
2336 return true;
2337 }
2338
2339 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2340 if (perm == PackageManager.PERMISSION_GRANTED) {
2341 return true;
2342 }
2343 if (checkAllowAppSwitchUid(sourceUid)) {
2344 return true;
2345 }
2346
2347 // If the actual IPC caller is different from the logical source, then
2348 // also see if they are allowed to control app switches.
2349 if (callingUid != -1 && callingUid != sourceUid) {
2350 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2351 if (perm == PackageManager.PERMISSION_GRANTED) {
2352 return true;
2353 }
2354 if (checkAllowAppSwitchUid(callingUid)) {
2355 return true;
2356 }
2357 }
2358
2359 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2360 return false;
2361 }
2362
2363 private boolean checkAllowAppSwitchUid(int uid) {
2364 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2365 if (types != null) {
2366 for (int i = types.size() - 1; i >= 0; i--) {
2367 if (types.valueAt(i).intValue() == uid) {
2368 return true;
2369 }
2370 }
2371 }
2372 return false;
2373 }
2374
2375 @Override
2376 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2377 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2378 "setActivityController()");
2379 synchronized (mGlobalLock) {
2380 mController = controller;
2381 mControllerIsAMonkey = imAMonkey;
2382 Watchdog.getInstance().setActivityController(controller);
2383 }
2384 }
2385
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002386 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002387 synchronized (mGlobalLock) {
2388 return mController != null && mControllerIsAMonkey;
2389 }
2390 }
2391
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002392 @Override
2393 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2394 synchronized (mGlobalLock) {
2395 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2396 }
2397 }
2398
2399 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002400 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2401 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2402 }
2403
2404 @Override
2405 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2406 @WindowConfiguration.ActivityType int ignoreActivityType,
2407 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2408 final int callingUid = Binder.getCallingUid();
2409 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2410
2411 synchronized (mGlobalLock) {
2412 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2413
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002414 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002415 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002416 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002417 ignoreWindowingMode, callingUid, allowed);
2418 }
2419
2420 return list;
2421 }
2422
2423 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002424 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2425 synchronized (mGlobalLock) {
2426 final long origId = Binder.clearCallingIdentity();
2427 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2428 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002429 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 }
2431 Binder.restoreCallingIdentity(origId);
2432 }
2433 }
2434
2435 @Override
2436 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002437 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002438 ActivityStack stack = ActivityRecord.getStackLocked(token);
2439 if (stack != null) {
2440 return stack.willActivityBeVisibleLocked(token);
2441 }
2442 return false;
2443 }
2444 }
2445
2446 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002447 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002448 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002449 synchronized (mGlobalLock) {
2450 final long ident = Binder.clearCallingIdentity();
2451 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002452 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002453 if (task == null) {
2454 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2455 return;
2456 }
2457
2458 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2459 + " to stackId=" + stackId + " toTop=" + toTop);
2460
Wale Ogunwaled32da472018-11-16 07:19:28 -08002461 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002462 if (stack == null) {
2463 throw new IllegalStateException(
2464 "moveTaskToStack: No stack for stackId=" + stackId);
2465 }
2466 if (!stack.isActivityTypeStandardOrUndefined()) {
2467 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2468 + taskId + " to stack " + stackId);
2469 }
2470 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002471 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002472 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2473 }
2474 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2475 "moveTaskToStack");
2476 } finally {
2477 Binder.restoreCallingIdentity(ident);
2478 }
2479 }
2480 }
2481
2482 @Override
2483 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2484 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002485 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002486
2487 final long ident = Binder.clearCallingIdentity();
2488 try {
2489 synchronized (mGlobalLock) {
2490 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002491 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002492 if (stack == null) {
2493 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2494 return;
2495 }
2496 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2497 throw new IllegalArgumentException("Stack: " + stackId
2498 + " doesn't support animated resize.");
2499 }
2500 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2501 animationDuration, false /* fromFullscreen */);
2502 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002503 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002504 if (stack == null) {
2505 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2506 return;
2507 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002508 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002509 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2510 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2511 }
2512 }
2513 } finally {
2514 Binder.restoreCallingIdentity(ident);
2515 }
2516 }
2517
wilsonshih5c4cf522019-01-25 09:03:47 +08002518 @Override
2519 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2520 int animationDuration) {
2521 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2522
2523 final long ident = Binder.clearCallingIdentity();
2524 try {
2525 synchronized (mGlobalLock) {
2526 if (xOffset == 0 && yOffset == 0) {
2527 return;
2528 }
2529 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2530 if (stack == null) {
2531 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2532 return;
2533 }
2534 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2535 throw new IllegalArgumentException("Stack: " + stackId
2536 + " doesn't support animated resize.");
2537 }
2538 final Rect destBounds = new Rect();
2539 stack.getAnimationOrCurrentBounds(destBounds);
wilsonshiha6e408c2019-02-19 17:30:03 +08002540 if (destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
wilsonshih5c4cf522019-01-25 09:03:47 +08002541 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2542 return;
2543 }
2544 destBounds.offset(xOffset, yOffset);
2545 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2546 animationDuration, false /* fromFullscreen */);
2547 }
2548 } finally {
2549 Binder.restoreCallingIdentity(ident);
2550 }
2551 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 /**
2553 * Moves the specified task to the primary-split-screen stack.
2554 *
2555 * @param taskId Id of task to move.
2556 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2557 * exist already. See
2558 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2559 * and
2560 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2561 * @param toTop If the task and stack should be moved to the top.
2562 * @param animate Whether we should play an animation for the moving the task.
2563 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2564 * stack. Pass {@code null} to use default bounds.
2565 * @param showRecents If the recents activity should be shown on the other side of the task
2566 * going into split-screen mode.
2567 */
2568 @Override
2569 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2570 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002571 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002572 "setTaskWindowingModeSplitScreenPrimary()");
2573 synchronized (mGlobalLock) {
2574 final long ident = Binder.clearCallingIdentity();
2575 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002576 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002577 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002578 if (task == null) {
2579 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2580 return false;
2581 }
2582 if (DEBUG_STACK) Slog.d(TAG_STACK,
2583 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2584 + " to createMode=" + createMode + " toTop=" + toTop);
2585 if (!task.isActivityTypeStandardOrUndefined()) {
2586 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2587 + " non-standard task " + taskId + " to split-screen windowing mode");
2588 }
2589
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002590 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002591 final int windowingMode = task.getWindowingMode();
2592 final ActivityStack stack = task.getStack();
2593 if (toTop) {
2594 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2595 }
2596 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002597 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2598 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002599 return windowingMode != task.getWindowingMode();
2600 } finally {
2601 Binder.restoreCallingIdentity(ident);
2602 }
2603 }
2604 }
2605
2606 /**
2607 * Removes stacks in the input windowing modes from the system if they are of activity type
2608 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2609 */
2610 @Override
2611 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002612 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002613 "removeStacksInWindowingModes()");
2614
2615 synchronized (mGlobalLock) {
2616 final long ident = Binder.clearCallingIdentity();
2617 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002618 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002619 } finally {
2620 Binder.restoreCallingIdentity(ident);
2621 }
2622 }
2623 }
2624
2625 @Override
2626 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002627 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002628 "removeStacksWithActivityTypes()");
2629
2630 synchronized (mGlobalLock) {
2631 final long ident = Binder.clearCallingIdentity();
2632 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002633 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002634 } finally {
2635 Binder.restoreCallingIdentity(ident);
2636 }
2637 }
2638 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002639
2640 @Override
2641 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2642 int userId) {
2643 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002644 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2645 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002647 final boolean detailed = checkGetTasksPermission(
2648 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2649 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002650 == PackageManager.PERMISSION_GRANTED;
2651
2652 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002653 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 callingUid);
2655 }
2656 }
2657
2658 @Override
2659 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002660 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661 long ident = Binder.clearCallingIdentity();
2662 try {
2663 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002664 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002665 }
2666 } finally {
2667 Binder.restoreCallingIdentity(ident);
2668 }
2669 }
2670
2671 @Override
2672 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002673 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 long ident = Binder.clearCallingIdentity();
2675 try {
2676 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002677 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002678 }
2679 } finally {
2680 Binder.restoreCallingIdentity(ident);
2681 }
2682 }
2683
2684 @Override
2685 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002686 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002687 final long callingUid = Binder.getCallingUid();
2688 final long origId = Binder.clearCallingIdentity();
2689 try {
2690 synchronized (mGlobalLock) {
2691 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002692 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002693 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2694 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2695 }
2696 } finally {
2697 Binder.restoreCallingIdentity(origId);
2698 }
2699 }
2700
2701 @Override
2702 public void startLockTaskModeByToken(IBinder token) {
2703 synchronized (mGlobalLock) {
2704 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2705 if (r == null) {
2706 return;
2707 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002708 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 }
2710 }
2711
2712 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002713 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002714 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002715 // This makes inner call to look as if it was initiated by system.
2716 long ident = Binder.clearCallingIdentity();
2717 try {
2718 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002719 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002720 MATCH_TASK_IN_STACKS_ONLY);
2721 if (task == null) {
2722 return;
2723 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002724
2725 // When starting lock task mode the stack must be in front and focused
2726 task.getStack().moveToFront("startSystemLockTaskMode");
2727 startLockTaskModeLocked(task, true /* isSystemCaller */);
2728 }
2729 } finally {
2730 Binder.restoreCallingIdentity(ident);
2731 }
2732 }
2733
2734 @Override
2735 public void stopLockTaskModeByToken(IBinder token) {
2736 synchronized (mGlobalLock) {
2737 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2738 if (r == null) {
2739 return;
2740 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002741 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002742 }
2743 }
2744
2745 /**
2746 * This API should be called by SystemUI only when user perform certain action to dismiss
2747 * lock task mode. We should only dismiss pinned lock task mode in this case.
2748 */
2749 @Override
2750 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002751 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002752 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2753 }
2754
2755 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2756 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2757 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2758 return;
2759 }
2760
Wale Ogunwaled32da472018-11-16 07:19:28 -08002761 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 if (stack == null || task != stack.topTask()) {
2763 throw new IllegalArgumentException("Invalid task, not in foreground");
2764 }
2765
2766 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2767 // system or a specific app.
2768 // * System-initiated requests will only start the pinned mode (screen pinning)
2769 // * App-initiated requests
2770 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2771 // - will start the pinned mode, otherwise
2772 final int callingUid = Binder.getCallingUid();
2773 long ident = Binder.clearCallingIdentity();
2774 try {
2775 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002776 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002777
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002778 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002779 } finally {
2780 Binder.restoreCallingIdentity(ident);
2781 }
2782 }
2783
2784 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2785 final int callingUid = Binder.getCallingUid();
2786 long ident = Binder.clearCallingIdentity();
2787 try {
2788 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002789 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 }
2791 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2792 // task and jumping straight into a call in the case of emergency call back.
2793 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2794 if (tm != null) {
2795 tm.showInCallScreen(false);
2796 }
2797 } finally {
2798 Binder.restoreCallingIdentity(ident);
2799 }
2800 }
2801
2802 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002803 public void updateLockTaskPackages(int userId, String[] packages) {
2804 final int callingUid = Binder.getCallingUid();
2805 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2806 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2807 "updateLockTaskPackages()");
2808 }
2809 synchronized (this) {
2810 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2811 + Arrays.toString(packages));
2812 getLockTaskController().updateLockTaskPackages(userId, packages);
2813 }
2814 }
2815
2816 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817 public boolean isInLockTaskMode() {
2818 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2819 }
2820
2821 @Override
2822 public int getLockTaskModeState() {
2823 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002824 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002825 }
2826 }
2827
2828 @Override
2829 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2830 synchronized (mGlobalLock) {
2831 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2832 if (r != null) {
2833 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002834 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002835 task.updateTaskDescription();
Mark Renoufc808f062019-02-07 15:20:37 -05002836 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.getTaskInfo());
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 }
2838 }
2839 }
2840
2841 @Override
2842 public Bundle getActivityOptions(IBinder token) {
2843 final long origId = Binder.clearCallingIdentity();
2844 try {
2845 synchronized (mGlobalLock) {
2846 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2847 if (r != null) {
2848 final ActivityOptions activityOptions = r.takeOptionsLocked();
2849 return activityOptions == null ? null : activityOptions.toBundle();
2850 }
2851 return null;
2852 }
2853 } finally {
2854 Binder.restoreCallingIdentity(origId);
2855 }
2856 }
2857
2858 @Override
2859 public List<IBinder> getAppTasks(String callingPackage) {
2860 int callingUid = Binder.getCallingUid();
2861 long ident = Binder.clearCallingIdentity();
2862 try {
2863 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002864 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865 }
2866 } finally {
2867 Binder.restoreCallingIdentity(ident);
2868 }
2869 }
2870
2871 @Override
2872 public void finishVoiceTask(IVoiceInteractionSession session) {
2873 synchronized (mGlobalLock) {
2874 final long origId = Binder.clearCallingIdentity();
2875 try {
2876 // TODO: VI Consider treating local voice interactions and voice tasks
2877 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002878 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 } finally {
2880 Binder.restoreCallingIdentity(origId);
2881 }
2882 }
2883
2884 }
2885
2886 @Override
2887 public boolean isTopOfTask(IBinder token) {
2888 synchronized (mGlobalLock) {
2889 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002890 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002891 }
2892 }
2893
2894 @Override
2895 public void notifyLaunchTaskBehindComplete(IBinder token) {
2896 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2897 }
2898
2899 @Override
2900 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002901 mH.post(() -> {
2902 synchronized (mGlobalLock) {
2903 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002904 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002905 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002906 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002907 } catch (RemoteException e) {
2908 }
2909 }
2910 }
2911
2912 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002913 }
2914
2915 /** Called from an app when assist data is ready. */
2916 @Override
2917 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2918 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002919 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002920 synchronized (pae) {
2921 pae.result = extras;
2922 pae.structure = structure;
2923 pae.content = content;
2924 if (referrer != null) {
2925 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2926 }
2927 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002928 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002929 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2930 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002931 structure.setHomeActivity(pae.isHome);
2932 }
2933 pae.haveResult = true;
2934 pae.notifyAll();
2935 if (pae.intent == null && pae.receiver == null) {
2936 // Caller is just waiting for the result.
2937 return;
2938 }
2939 }
2940 // We are now ready to launch the assist activity.
2941 IAssistDataReceiver sendReceiver = null;
2942 Bundle sendBundle = null;
2943 synchronized (mGlobalLock) {
2944 buildAssistBundleLocked(pae, extras);
2945 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002946 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002947 if (!exists) {
2948 // Timed out.
2949 return;
2950 }
2951
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002952 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 // Caller wants result sent back to them.
2954 sendBundle = new Bundle();
2955 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2956 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2957 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2958 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2959 }
2960 }
2961 if (sendReceiver != null) {
2962 try {
2963 sendReceiver.onHandleAssistData(sendBundle);
2964 } catch (RemoteException e) {
2965 }
2966 return;
2967 }
2968
2969 final long ident = Binder.clearCallingIdentity();
2970 try {
2971 if (TextUtils.equals(pae.intent.getAction(),
2972 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2973 pae.intent.putExtras(pae.extras);
Marvin Ramin830d4e32019-03-12 13:16:58 +01002974
2975 startVoiceInteractionServiceAsUser(pae.intent, pae.userHandle, "AssistContext");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002976 } else {
2977 pae.intent.replaceExtras(pae.extras);
2978 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2979 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2980 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002981 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982
2983 try {
2984 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2985 } catch (ActivityNotFoundException e) {
2986 Slog.w(TAG, "No activity to handle assist action.", e);
2987 }
2988 }
2989 } finally {
2990 Binder.restoreCallingIdentity(ident);
2991 }
2992 }
2993
Marvin Ramin830d4e32019-03-12 13:16:58 +01002994 /**
2995 * Workaround for historical API which starts the Assist service with a non-foreground
2996 * {@code startService()} call.
2997 */
2998 private void startVoiceInteractionServiceAsUser(
2999 Intent intent, int userHandle, String reason) {
3000 // Resolve the intent to find out which package we need to whitelist.
3001 ResolveInfo resolveInfo =
3002 mContext.getPackageManager().resolveServiceAsUser(intent, 0, userHandle);
3003 if (resolveInfo == null || resolveInfo.serviceInfo == null) {
3004 Slog.e(TAG, "VoiceInteractionService intent does not resolve. Not starting.");
3005 return;
3006 }
3007 intent.setPackage(resolveInfo.serviceInfo.packageName);
3008
3009 // Whitelist background services temporarily.
3010 LocalServices.getService(DeviceIdleController.LocalService.class)
3011 .addPowerSaveTempWhitelistApp(Process.myUid(), intent.getPackage(),
3012 SERVICE_LAUNCH_IDLE_WHITELIST_DURATION_MS, userHandle, false, reason);
3013
3014 // Finally, try to start the service.
3015 try {
3016 mContext.startServiceAsUser(intent, UserHandle.of(userHandle));
3017 } catch (RuntimeException e) {
3018 Slog.e(TAG, "VoiceInteractionService failed to start.", e);
3019 }
3020 }
3021
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003022 @Override
3023 public int addAppTask(IBinder activityToken, Intent intent,
3024 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
3025 final int callingUid = Binder.getCallingUid();
3026 final long callingIdent = Binder.clearCallingIdentity();
3027
3028 try {
3029 synchronized (mGlobalLock) {
3030 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3031 if (r == null) {
3032 throw new IllegalArgumentException("Activity does not exist; token="
3033 + activityToken);
3034 }
3035 ComponentName comp = intent.getComponent();
3036 if (comp == null) {
3037 throw new IllegalArgumentException("Intent " + intent
3038 + " must specify explicit component");
3039 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003040 if (thumbnail.getWidth() != mThumbnailWidth
3041 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003042 throw new IllegalArgumentException("Bad thumbnail size: got "
3043 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003044 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003045 }
3046 if (intent.getSelector() != null) {
3047 intent.setSelector(null);
3048 }
3049 if (intent.getSourceBounds() != null) {
3050 intent.setSourceBounds(null);
3051 }
3052 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
3053 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
3054 // The caller has added this as an auto-remove task... that makes no
3055 // sense, so turn off auto-remove.
3056 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
3057 }
3058 }
3059 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
3060 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
3061 if (ainfo.applicationInfo.uid != callingUid) {
3062 throw new SecurityException(
3063 "Can't add task for another application: target uid="
3064 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
3065 }
3066
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003067 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003069 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003070 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003071 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 // The app has too many tasks already and we can't add any more
3073 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
3074 return INVALID_TASK_ID;
3075 }
3076 task.lastTaskDescription.copyFrom(description);
3077
3078 // TODO: Send the thumbnail to WM to store it.
3079
3080 return task.taskId;
3081 }
3082 } finally {
3083 Binder.restoreCallingIdentity(callingIdent);
3084 }
3085 }
3086
3087 @Override
3088 public Point getAppTaskThumbnailSize() {
3089 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003090 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 }
3092 }
3093
3094 @Override
3095 public void setTaskResizeable(int taskId, int resizeableMode) {
3096 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003097 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3099 if (task == null) {
3100 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3101 return;
3102 }
3103 task.setResizeMode(resizeableMode);
3104 }
3105 }
3106
3107 @Override
3108 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003109 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003110 long ident = Binder.clearCallingIdentity();
3111 try {
3112 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003113 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003114 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003115 if (task == null) {
3116 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3117 return;
3118 }
3119 // Place the task in the right stack if it isn't there already based on
3120 // the requested bounds.
3121 // The stack transition logic is:
3122 // - a null bounds on a freeform task moves that task to fullscreen
3123 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3124 // that task to freeform
3125 // - otherwise the task is not moved
3126 ActivityStack stack = task.getStack();
3127 if (!task.getWindowConfiguration().canResizeTask()) {
3128 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3129 }
3130 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3131 stack = stack.getDisplay().getOrCreateStack(
3132 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3133 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3134 stack = stack.getDisplay().getOrCreateStack(
3135 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3136 }
3137
3138 // Reparent the task to the right stack if necessary
3139 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3140 if (stack != task.getStack()) {
3141 // Defer resume until the task is resized below
3142 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3143 DEFER_RESUME, "resizeTask");
3144 preserveWindow = false;
3145 }
3146
3147 // After reparenting (which only resizes the task to the stack bounds), resize the
3148 // task to the actual bounds provided
3149 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3150 }
3151 } finally {
3152 Binder.restoreCallingIdentity(ident);
3153 }
3154 }
3155
3156 @Override
3157 public boolean releaseActivityInstance(IBinder token) {
3158 synchronized (mGlobalLock) {
3159 final long origId = Binder.clearCallingIdentity();
3160 try {
3161 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3162 if (r == null) {
3163 return false;
3164 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003165 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003166 } finally {
3167 Binder.restoreCallingIdentity(origId);
3168 }
3169 }
3170 }
3171
3172 @Override
3173 public void releaseSomeActivities(IApplicationThread appInt) {
3174 synchronized (mGlobalLock) {
3175 final long origId = Binder.clearCallingIdentity();
3176 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003177 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003178 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003179 } finally {
3180 Binder.restoreCallingIdentity(origId);
3181 }
3182 }
3183 }
3184
3185 @Override
wilsonshih177261f2019-02-22 12:02:18 +08003186 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003187 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 != PackageManager.PERMISSION_GRANTED) {
3189 throw new SecurityException("Requires permission "
3190 + android.Manifest.permission.DEVICE_POWER);
3191 }
3192
3193 synchronized (mGlobalLock) {
3194 long ident = Binder.clearCallingIdentity();
3195 if (mKeyguardShown != keyguardShowing) {
3196 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003197 final Message msg = PooledLambda.obtainMessage(
3198 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3199 keyguardShowing);
3200 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003201 }
3202 try {
wilsonshih177261f2019-02-22 12:02:18 +08003203 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003204 } finally {
3205 Binder.restoreCallingIdentity(ident);
3206 }
3207 }
3208
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003209 mH.post(() -> {
3210 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3211 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3212 }
3213 });
3214 }
3215
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003216 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003217 mH.post(() -> {
3218 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3219 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3220 }
3221 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003222 }
3223
3224 @Override
3225 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003226 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3227 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003228
3229 final File passedIconFile = new File(filePath);
3230 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3231 passedIconFile.getName());
3232 if (!legitIconFile.getPath().equals(filePath)
3233 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3234 throw new IllegalArgumentException("Bad file path: " + filePath
3235 + " passed for userId " + userId);
3236 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003237 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 }
3239
3240 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003241 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3243 final ActivityOptions activityOptions = safeOptions != null
3244 ? safeOptions.getOptions(mStackSupervisor)
3245 : null;
3246 if (activityOptions == null
3247 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3248 || activityOptions.getCustomInPlaceResId() == 0) {
3249 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3250 "with valid animation");
3251 }
lumark588a3e82018-07-20 18:53:54 +08003252 // Get top display of front most application.
3253 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3254 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003255 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3256 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3257 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003258 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003259 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003260 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003261 }
3262
3263 @Override
3264 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003265 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003266 synchronized (mGlobalLock) {
3267 final long ident = Binder.clearCallingIdentity();
3268 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003269 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003270 if (stack == null) {
3271 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3272 return;
3273 }
3274 if (!stack.isActivityTypeStandardOrUndefined()) {
3275 throw new IllegalArgumentException(
3276 "Removing non-standard stack is not allowed.");
3277 }
3278 mStackSupervisor.removeStack(stack);
3279 } finally {
3280 Binder.restoreCallingIdentity(ident);
3281 }
3282 }
3283 }
3284
3285 @Override
3286 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003287 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003288
3289 synchronized (mGlobalLock) {
3290 final long ident = Binder.clearCallingIdentity();
3291 try {
3292 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3293 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003294 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003295 } finally {
3296 Binder.restoreCallingIdentity(ident);
3297 }
3298 }
3299 }
3300
3301 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003302 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003303 synchronized (mGlobalLock) {
3304 long ident = Binder.clearCallingIdentity();
3305 try {
3306 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3307 if (r == null) {
3308 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003309 "toggleFreeformWindowingMode: No activity record matching token="
3310 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003311 }
3312
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003313 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003314 if (stack == null) {
3315 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3316 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 }
3318
Yunfan Chend967af82019-01-17 18:30:18 +09003319 if (!stack.inFreeformWindowingMode()
3320 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3321 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3322 + "toggle between fullscreen and freeform.");
3323 }
3324
3325 if (stack.inFreeformWindowingMode()) {
3326 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3327 } else {
3328 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3329 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003330 } finally {
3331 Binder.restoreCallingIdentity(ident);
3332 }
3333 }
3334 }
3335
3336 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3337 @Override
3338 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003339 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003340 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003341 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003342 }
3343
3344 /** Unregister a task stack listener so that it stops receiving callbacks. */
3345 @Override
3346 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003347 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003348 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003349 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003350 }
3351
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003352 @Override
3353 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3354 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3355 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3356 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3357 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3358 }
3359
3360 @Override
3361 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3362 IBinder activityToken, int flags) {
3363 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3364 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3365 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3366 }
3367
3368 @Override
3369 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3370 Bundle args) {
3371 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3372 true /* focused */, true /* newSessionId */, userHandle, args,
3373 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3374 }
3375
3376 @Override
3377 public Bundle getAssistContextExtras(int requestType) {
3378 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3379 null, null, true /* focused */, true /* newSessionId */,
3380 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3381 if (pae == null) {
3382 return null;
3383 }
3384 synchronized (pae) {
3385 while (!pae.haveResult) {
3386 try {
3387 pae.wait();
3388 } catch (InterruptedException e) {
3389 }
3390 }
3391 }
3392 synchronized (mGlobalLock) {
3393 buildAssistBundleLocked(pae, pae.result);
3394 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003395 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003396 }
3397 return pae.extras;
3398 }
3399
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003400 /**
3401 * Binder IPC calls go through the public entry point.
3402 * This can be called with or without the global lock held.
3403 */
3404 private static int checkCallingPermission(String permission) {
3405 return checkPermission(
3406 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3407 }
3408
3409 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003410 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003411 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3412 mAmInternal.enforceCallingPermission(permission, func);
3413 }
3414 }
3415
3416 @VisibleForTesting
3417 int checkGetTasksPermission(String permission, int pid, int uid) {
3418 return checkPermission(permission, pid, uid);
3419 }
3420
3421 static int checkPermission(String permission, int pid, int uid) {
3422 if (permission == null) {
3423 return PackageManager.PERMISSION_DENIED;
3424 }
3425 return checkComponentPermission(permission, pid, uid, -1, true);
3426 }
3427
Wale Ogunwale214f3482018-10-04 11:00:47 -07003428 public static int checkComponentPermission(String permission, int pid, int uid,
3429 int owningUid, boolean exported) {
3430 return ActivityManagerService.checkComponentPermission(
3431 permission, pid, uid, owningUid, exported);
3432 }
3433
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003434 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3435 if (getRecentTasks().isCallerRecents(callingUid)) {
3436 // Always allow the recents component to get tasks
3437 return true;
3438 }
3439
3440 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3441 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3442 if (!allowed) {
3443 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3444 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3445 // Temporary compatibility: some existing apps on the system image may
3446 // still be requesting the old permission and not switched to the new
3447 // one; if so, we'll still allow them full access. This means we need
3448 // to see if they are holding the old permission and are a system app.
3449 try {
3450 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3451 allowed = true;
3452 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3453 + " is using old GET_TASKS but privileged; allowing");
3454 }
3455 } catch (RemoteException e) {
3456 }
3457 }
3458 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3459 + " does not hold REAL_GET_TASKS; limiting output");
3460 }
3461 return allowed;
3462 }
3463
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3465 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3466 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3467 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003468 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003469 "enqueueAssistContext()");
3470
3471 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003472 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003473 if (activity == null) {
3474 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3475 return null;
3476 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003477 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3479 return null;
3480 }
3481 if (focused) {
3482 if (activityToken != null) {
3483 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3484 if (activity != caller) {
3485 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3486 + " is not current top " + activity);
3487 return null;
3488 }
3489 }
3490 } else {
3491 activity = ActivityRecord.forTokenLocked(activityToken);
3492 if (activity == null) {
3493 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3494 + " couldn't be found");
3495 return null;
3496 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003497 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003498 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3499 return null;
3500 }
3501 }
3502
3503 PendingAssistExtras pae;
3504 Bundle extras = new Bundle();
3505 if (args != null) {
3506 extras.putAll(args);
3507 }
3508 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003509 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003510
3511 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3512 userHandle);
3513 pae.isHome = activity.isActivityTypeHome();
3514
3515 // Increment the sessionId if necessary
3516 if (newSessionId) {
3517 mViSessionId++;
3518 }
3519 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003520 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3521 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003522 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003523 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003524 } catch (RemoteException e) {
3525 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3526 return null;
3527 }
3528 return pae;
3529 }
3530 }
3531
3532 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3533 if (result != null) {
3534 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3535 }
3536 if (pae.hint != null) {
3537 pae.extras.putBoolean(pae.hint, true);
3538 }
3539 }
3540
3541 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3542 IAssistDataReceiver receiver;
3543 synchronized (mGlobalLock) {
3544 mPendingAssistExtras.remove(pae);
3545 receiver = pae.receiver;
3546 }
3547 if (receiver != null) {
3548 // Caller wants result sent back to them.
3549 Bundle sendBundle = new Bundle();
3550 // At least return the receiver extras
3551 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3552 try {
3553 pae.receiver.onHandleAssistData(sendBundle);
3554 } catch (RemoteException e) {
3555 }
3556 }
3557 }
3558
3559 public class PendingAssistExtras extends Binder implements Runnable {
3560 public final ActivityRecord activity;
3561 public boolean isHome;
3562 public final Bundle extras;
3563 public final Intent intent;
3564 public final String hint;
3565 public final IAssistDataReceiver receiver;
3566 public final int userHandle;
3567 public boolean haveResult = false;
3568 public Bundle result = null;
3569 public AssistStructure structure = null;
3570 public AssistContent content = null;
3571 public Bundle receiverExtras;
3572
3573 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3574 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3575 int _userHandle) {
3576 activity = _activity;
3577 extras = _extras;
3578 intent = _intent;
3579 hint = _hint;
3580 receiver = _receiver;
3581 receiverExtras = _receiverExtras;
3582 userHandle = _userHandle;
3583 }
3584
3585 @Override
3586 public void run() {
3587 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3588 synchronized (this) {
3589 haveResult = true;
3590 notifyAll();
3591 }
3592 pendingAssistExtrasTimedOut(this);
3593 }
3594 }
3595
3596 @Override
3597 public boolean isAssistDataAllowedOnCurrentActivity() {
3598 int userId;
3599 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003600 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003601 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3602 return false;
3603 }
3604
3605 final ActivityRecord activity = focusedStack.getTopActivity();
3606 if (activity == null) {
3607 return false;
3608 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003609 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003610 }
3611 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3612 }
3613
3614 @Override
3615 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3616 long ident = Binder.clearCallingIdentity();
3617 try {
3618 synchronized (mGlobalLock) {
3619 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003620 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003621 if (top != caller) {
3622 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3623 + " is not current top " + top);
3624 return false;
3625 }
3626 if (!top.nowVisible) {
3627 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3628 + " is not visible");
3629 return false;
3630 }
3631 }
3632 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3633 token);
3634 } finally {
3635 Binder.restoreCallingIdentity(ident);
3636 }
3637 }
3638
3639 @Override
3640 public boolean isRootVoiceInteraction(IBinder token) {
3641 synchronized (mGlobalLock) {
3642 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3643 if (r == null) {
3644 return false;
3645 }
3646 return r.rootVoiceInteraction;
3647 }
3648 }
3649
Wale Ogunwalef6733932018-06-27 05:14:34 -07003650 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3651 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3652 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3653 if (activityToCallback == null) return;
3654 activityToCallback.setVoiceSessionLocked(voiceSession);
3655
3656 // Inform the activity
3657 try {
3658 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3659 voiceInteractor);
3660 long token = Binder.clearCallingIdentity();
3661 try {
3662 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3663 } finally {
3664 Binder.restoreCallingIdentity(token);
3665 }
3666 // TODO: VI Should we cache the activity so that it's easier to find later
3667 // rather than scan through all the stacks and activities?
3668 } catch (RemoteException re) {
3669 activityToCallback.clearVoiceSessionLocked();
3670 // TODO: VI Should this terminate the voice session?
3671 }
3672 }
3673
3674 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3675 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3676 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3677 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3678 boolean wasRunningVoice = mRunningVoice != null;
3679 mRunningVoice = session;
3680 if (!wasRunningVoice) {
3681 mVoiceWakeLock.acquire();
3682 updateSleepIfNeededLocked();
3683 }
3684 }
3685 }
3686
3687 void finishRunningVoiceLocked() {
3688 if (mRunningVoice != null) {
3689 mRunningVoice = null;
3690 mVoiceWakeLock.release();
3691 updateSleepIfNeededLocked();
3692 }
3693 }
3694
3695 @Override
3696 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3697 synchronized (mGlobalLock) {
3698 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3699 if (keepAwake) {
3700 mVoiceWakeLock.acquire();
3701 } else {
3702 mVoiceWakeLock.release();
3703 }
3704 }
3705 }
3706 }
3707
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 @Override
3709 public ComponentName getActivityClassForToken(IBinder token) {
3710 synchronized (mGlobalLock) {
3711 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3712 if (r == null) {
3713 return null;
3714 }
3715 return r.intent.getComponent();
3716 }
3717 }
3718
3719 @Override
3720 public String getPackageForToken(IBinder token) {
3721 synchronized (mGlobalLock) {
3722 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3723 if (r == null) {
3724 return null;
3725 }
3726 return r.packageName;
3727 }
3728 }
3729
3730 @Override
3731 public void showLockTaskEscapeMessage(IBinder token) {
3732 synchronized (mGlobalLock) {
3733 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3734 if (r == null) {
3735 return;
3736 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003737 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 }
3739 }
3740
3741 @Override
3742 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003743 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003744 final long token = Binder.clearCallingIdentity();
3745 try {
3746 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003747 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003748 }
3749 } finally {
3750 Binder.restoreCallingIdentity(token);
3751 }
3752 }
3753
3754 /**
3755 * Try to place task to provided position. The final position might be different depending on
3756 * current user and stacks state. The task will be moved to target stack if it's currently in
3757 * different stack.
3758 */
3759 @Override
3760 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003761 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003762 synchronized (mGlobalLock) {
3763 long ident = Binder.clearCallingIdentity();
3764 try {
3765 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3766 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003767 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 if (task == null) {
3769 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3770 + taskId);
3771 }
3772
Wale Ogunwaled32da472018-11-16 07:19:28 -08003773 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003774
3775 if (stack == null) {
3776 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3777 + stackId);
3778 }
3779 if (!stack.isActivityTypeStandardOrUndefined()) {
3780 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3781 + " the position of task " + taskId + " in/to non-standard stack");
3782 }
3783
3784 // TODO: Have the callers of this API call a separate reparent method if that is
3785 // what they intended to do vs. having this method also do reparenting.
3786 if (task.getStack() == stack) {
3787 // Change position in current stack.
3788 stack.positionChildAt(task, position);
3789 } else {
3790 // Reparent to new stack.
3791 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3792 !DEFER_RESUME, "positionTaskInStack");
3793 }
3794 } finally {
3795 Binder.restoreCallingIdentity(ident);
3796 }
3797 }
3798 }
3799
3800 @Override
3801 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3802 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3803 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3804 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3805 synchronized (mGlobalLock) {
3806 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3807 if (record == null) {
3808 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3809 + "found for: " + token);
3810 }
3811 record.setSizeConfigurations(horizontalSizeConfiguration,
3812 verticalSizeConfigurations, smallestSizeConfigurations);
3813 }
3814 }
3815
3816 /**
3817 * Dismisses split-screen multi-window mode.
3818 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3819 */
3820 @Override
3821 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003822 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003823 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3824 final long ident = Binder.clearCallingIdentity();
3825 try {
3826 synchronized (mGlobalLock) {
3827 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003828 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003829 if (stack == null) {
3830 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3831 return;
3832 }
3833
3834 if (toTop) {
3835 // Caller wants the current split-screen primary stack to be the top stack after
3836 // it goes fullscreen, so move it to the front.
3837 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003838 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 // In this case the current split-screen primary stack shouldn't be the top
3840 // stack after it goes fullscreen, but it current has focus, so we move the
3841 // focus to the top-most split-screen secondary stack next to it.
3842 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3843 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3844 if (otherStack != null) {
3845 otherStack.moveToFront("dismissSplitScreenMode_other");
3846 }
3847 }
3848
Evan Rosky10475742018-09-05 19:02:48 -07003849 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 }
3851 } finally {
3852 Binder.restoreCallingIdentity(ident);
3853 }
3854 }
3855
3856 /**
3857 * Dismisses Pip
3858 * @param animate True if the dismissal should be animated.
3859 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3860 * default animation duration should be used.
3861 */
3862 @Override
3863 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003864 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003865 final long ident = Binder.clearCallingIdentity();
3866 try {
3867 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003868 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003869 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003870 if (stack == null) {
3871 Slog.w(TAG, "dismissPip: pinned stack not found.");
3872 return;
3873 }
3874 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3875 throw new IllegalArgumentException("Stack: " + stack
3876 + " doesn't support animated resize.");
3877 }
3878 if (animate) {
3879 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3880 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3881 } else {
3882 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3883 }
3884 }
3885 } finally {
3886 Binder.restoreCallingIdentity(ident);
3887 }
3888 }
3889
3890 @Override
3891 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003892 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 synchronized (mGlobalLock) {
3894 mSuppressResizeConfigChanges = suppress;
3895 }
3896 }
3897
3898 /**
3899 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3900 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3901 * activity and clearing the task at the same time.
3902 */
3903 @Override
3904 // TODO: API should just be about changing windowing modes...
3905 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003906 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003907 "moveTasksToFullscreenStack()");
3908 synchronized (mGlobalLock) {
3909 final long origId = Binder.clearCallingIdentity();
3910 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003911 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 if (stack != null){
3913 if (!stack.isActivityTypeStandardOrUndefined()) {
3914 throw new IllegalArgumentException(
3915 "You can't move tasks from non-standard stacks.");
3916 }
3917 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3918 }
3919 } finally {
3920 Binder.restoreCallingIdentity(origId);
3921 }
3922 }
3923 }
3924
3925 /**
3926 * Moves the top activity in the input stackId to the pinned stack.
3927 *
3928 * @param stackId Id of stack to move the top activity to pinned stack.
3929 * @param bounds Bounds to use for pinned stack.
3930 *
3931 * @return True if the top activity of the input stack was successfully moved to the pinned
3932 * stack.
3933 */
3934 @Override
3935 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003936 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003937 "moveTopActivityToPinnedStack()");
3938 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003939 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003940 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3941 + "Device doesn't support picture-in-picture mode");
3942 }
3943
3944 long ident = Binder.clearCallingIdentity();
3945 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003946 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003947 } finally {
3948 Binder.restoreCallingIdentity(ident);
3949 }
3950 }
3951 }
3952
3953 @Override
3954 public boolean isInMultiWindowMode(IBinder token) {
3955 final long origId = Binder.clearCallingIdentity();
3956 try {
3957 synchronized (mGlobalLock) {
3958 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3959 if (r == null) {
3960 return false;
3961 }
3962 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3963 return r.inMultiWindowMode();
3964 }
3965 } finally {
3966 Binder.restoreCallingIdentity(origId);
3967 }
3968 }
3969
3970 @Override
3971 public boolean isInPictureInPictureMode(IBinder token) {
3972 final long origId = Binder.clearCallingIdentity();
3973 try {
3974 synchronized (mGlobalLock) {
3975 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3976 }
3977 } finally {
3978 Binder.restoreCallingIdentity(origId);
3979 }
3980 }
3981
3982 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003983 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3984 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003985 return false;
3986 }
3987
3988 // If we are animating to fullscreen then we have already dispatched the PIP mode
3989 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003990 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3991 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 }
3993
3994 @Override
3995 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3996 final long origId = Binder.clearCallingIdentity();
3997 try {
3998 synchronized (mGlobalLock) {
3999 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4000 "enterPictureInPictureMode", token, params);
4001
4002 // If the activity is already in picture in picture mode, then just return early
4003 if (isInPictureInPictureMode(r)) {
4004 return true;
4005 }
4006
4007 // Activity supports picture-in-picture, now check that we can enter PiP at this
4008 // point, if it is
4009 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
4010 false /* beforeStopping */)) {
4011 return false;
4012 }
4013
4014 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004015 synchronized (mGlobalLock) {
4016 // Only update the saved args from the args that are set
4017 r.pictureInPictureArgs.copyOnlySet(params);
4018 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
4019 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
4020 // Adjust the source bounds by the insets for the transition down
4021 final Rect sourceBounds = new Rect(
4022 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08004023 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004024 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08004025 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07004026 stack.setPictureInPictureAspectRatio(aspectRatio);
4027 stack.setPictureInPictureActions(actions);
4028 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
4029 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
4030 logPictureInPictureArgs(params);
4031 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 };
4033
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004034 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 // If the keyguard is showing or occluded, then try and dismiss it before
4036 // entering picture-in-picture (this will prompt the user to authenticate if the
4037 // device is currently locked).
4038 dismissKeyguard(token, new KeyguardDismissCallback() {
4039 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004040 public void onDismissSucceeded() {
4041 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 }
4043 }, null /* message */);
4044 } else {
4045 // Enter picture in picture immediately otherwise
4046 enterPipRunnable.run();
4047 }
4048 return true;
4049 }
4050 } finally {
4051 Binder.restoreCallingIdentity(origId);
4052 }
4053 }
4054
4055 @Override
4056 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
4057 final long origId = Binder.clearCallingIdentity();
4058 try {
4059 synchronized (mGlobalLock) {
4060 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
4061 "setPictureInPictureParams", token, params);
4062
4063 // Only update the saved args from the args that are set
4064 r.pictureInPictureArgs.copyOnlySet(params);
4065 if (r.inPinnedWindowingMode()) {
4066 // If the activity is already in picture-in-picture, update the pinned stack now
4067 // if it is not already expanding to fullscreen. Otherwise, the arguments will
4068 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08004069 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004070 if (!stack.isAnimatingBoundsToFullscreen()) {
4071 stack.setPictureInPictureAspectRatio(
4072 r.pictureInPictureArgs.getAspectRatio());
4073 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
4074 }
4075 }
4076 logPictureInPictureArgs(params);
4077 }
4078 } finally {
4079 Binder.restoreCallingIdentity(origId);
4080 }
4081 }
4082
4083 @Override
4084 public int getMaxNumPictureInPictureActions(IBinder token) {
4085 // Currently, this is a static constant, but later, we may change this to be dependent on
4086 // the context of the activity
4087 return 3;
4088 }
4089
4090 private void logPictureInPictureArgs(PictureInPictureParams params) {
4091 if (params.hasSetActions()) {
4092 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
4093 params.getActions().size());
4094 }
4095 if (params.hasSetAspectRatio()) {
4096 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4097 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4098 MetricsLogger.action(lm);
4099 }
4100 }
4101
4102 /**
4103 * Checks the state of the system and the activity associated with the given {@param token} to
4104 * verify that picture-in-picture is supported for that activity.
4105 *
4106 * @return the activity record for the given {@param token} if all the checks pass.
4107 */
4108 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4109 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004110 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004111 throw new IllegalStateException(caller
4112 + ": Device doesn't support picture-in-picture mode.");
4113 }
4114
4115 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4116 if (r == null) {
4117 throw new IllegalStateException(caller
4118 + ": Can't find activity for token=" + token);
4119 }
4120
4121 if (!r.supportsPictureInPicture()) {
4122 throw new IllegalStateException(caller
4123 + ": Current activity does not support picture-in-picture.");
4124 }
4125
4126 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004127 && !mWindowManager.isValidPictureInPictureAspectRatio(
4128 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 final float minAspectRatio = mContext.getResources().getFloat(
4130 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4131 final float maxAspectRatio = mContext.getResources().getFloat(
4132 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4133 throw new IllegalArgumentException(String.format(caller
4134 + ": Aspect ratio is too extreme (must be between %f and %f).",
4135 minAspectRatio, maxAspectRatio));
4136 }
4137
4138 // Truncate the number of actions if necessary
4139 params.truncateActions(getMaxNumPictureInPictureActions(token));
4140
4141 return r;
4142 }
4143
4144 @Override
4145 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004146 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004147 synchronized (mGlobalLock) {
4148 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4149 if (r == null) {
4150 throw new IllegalArgumentException("Activity does not exist; token="
4151 + activityToken);
4152 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004153 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 }
4155 }
4156
4157 @Override
4158 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4159 Rect tempDockedTaskInsetBounds,
4160 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004161 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004162 long ident = Binder.clearCallingIdentity();
4163 try {
4164 synchronized (mGlobalLock) {
4165 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4166 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4167 PRESERVE_WINDOWS);
4168 }
4169 } finally {
4170 Binder.restoreCallingIdentity(ident);
4171 }
4172 }
4173
4174 @Override
4175 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004176 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004177 final long ident = Binder.clearCallingIdentity();
4178 try {
4179 synchronized (mGlobalLock) {
4180 mStackSupervisor.setSplitScreenResizing(resizing);
4181 }
4182 } finally {
4183 Binder.restoreCallingIdentity(ident);
4184 }
4185 }
4186
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004187 /**
4188 * Check that we have the features required for VR-related API calls, and throw an exception if
4189 * not.
4190 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004191 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 if (!mContext.getPackageManager().hasSystemFeature(
4193 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4194 throw new UnsupportedOperationException("VR mode not supported on this device!");
4195 }
4196 }
4197
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004198 @Override
4199 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004200 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004201
4202 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4203
4204 ActivityRecord r;
4205 synchronized (mGlobalLock) {
4206 r = ActivityRecord.isInStackLocked(token);
4207 }
4208
4209 if (r == null) {
4210 throw new IllegalArgumentException();
4211 }
4212
4213 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004214 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 VrManagerInternal.NO_ERROR) {
4216 return err;
4217 }
4218
4219 // Clear the binder calling uid since this path may call moveToTask().
4220 final long callingId = Binder.clearCallingIdentity();
4221 try {
4222 synchronized (mGlobalLock) {
4223 r.requestedVrComponent = (enabled) ? packageName : null;
4224
4225 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004226 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004227 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004228 }
4229 return 0;
4230 }
4231 } finally {
4232 Binder.restoreCallingIdentity(callingId);
4233 }
4234 }
4235
4236 @Override
4237 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4238 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4239 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004240 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004241 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4242 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4243 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004244 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 || activity.voiceSession != null) {
4246 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4247 return;
4248 }
4249 if (activity.pendingVoiceInteractionStart) {
4250 Slog.w(TAG, "Pending start of voice interaction already.");
4251 return;
4252 }
4253 activity.pendingVoiceInteractionStart = true;
4254 }
4255 LocalServices.getService(VoiceInteractionManagerInternal.class)
4256 .startLocalVoiceInteraction(callingActivity, options);
4257 }
4258
4259 @Override
4260 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4261 LocalServices.getService(VoiceInteractionManagerInternal.class)
4262 .stopLocalVoiceInteraction(callingActivity);
4263 }
4264
4265 @Override
4266 public boolean supportsLocalVoiceInteraction() {
4267 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4268 .supportsLocalVoiceInteraction();
4269 }
4270
4271 /** Notifies all listeners when the pinned stack animation starts. */
4272 @Override
4273 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004274 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004275 }
4276
4277 /** Notifies all listeners when the pinned stack animation ends. */
4278 @Override
4279 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004280 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004281 }
4282
4283 @Override
4284 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004285 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004286 final long ident = Binder.clearCallingIdentity();
4287 try {
4288 synchronized (mGlobalLock) {
4289 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4290 }
4291 } finally {
4292 Binder.restoreCallingIdentity(ident);
4293 }
4294 }
4295
4296 @Override
4297 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004298 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299
4300 synchronized (mGlobalLock) {
4301 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004302 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004303 // Call might come when display is not yet added or has already been removed.
4304 if (DEBUG_CONFIGURATION) {
4305 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4306 + displayId);
4307 }
4308 return false;
4309 }
4310
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004311 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004312 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004313 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 }
4315
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004316 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004317 final Message msg = PooledLambda.obtainMessage(
4318 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4319 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004320 }
4321
4322 final long origId = Binder.clearCallingIdentity();
4323 try {
4324 if (values != null) {
4325 Settings.System.clearConfiguration(values);
4326 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004327 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4329 return mTmpUpdateConfigurationResult.changes != 0;
4330 } finally {
4331 Binder.restoreCallingIdentity(origId);
4332 }
4333 }
4334 }
4335
4336 @Override
4337 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004338 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004339
4340 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004341 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004342 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004343 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004344 }
4345
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004346 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004347 final Message msg = PooledLambda.obtainMessage(
4348 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4349 DEFAULT_DISPLAY);
4350 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 }
4352
4353 final long origId = Binder.clearCallingIdentity();
4354 try {
4355 if (values != null) {
4356 Settings.System.clearConfiguration(values);
4357 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004358 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004359 UserHandle.USER_NULL, false /* deferResume */,
4360 mTmpUpdateConfigurationResult);
4361 return mTmpUpdateConfigurationResult.changes != 0;
4362 } finally {
4363 Binder.restoreCallingIdentity(origId);
4364 }
4365 }
4366 }
4367
4368 @Override
4369 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4370 CharSequence message) {
4371 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004372 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004373 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4374 }
4375 final long callingId = Binder.clearCallingIdentity();
4376 try {
4377 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004378 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004379 }
4380 } finally {
4381 Binder.restoreCallingIdentity(callingId);
4382 }
4383 }
4384
4385 @Override
4386 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 "cancelTaskWindowTransition()");
4389 final long ident = Binder.clearCallingIdentity();
4390 try {
4391 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004392 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004393 MATCH_TASK_IN_STACKS_ONLY);
4394 if (task == null) {
4395 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4396 return;
4397 }
4398 task.cancelWindowTransition();
4399 }
4400 } finally {
4401 Binder.restoreCallingIdentity(ident);
4402 }
4403 }
4404
4405 @Override
4406 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004407 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 final long ident = Binder.clearCallingIdentity();
4409 try {
4410 final TaskRecord task;
4411 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004412 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004413 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4414 if (task == null) {
4415 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4416 return null;
4417 }
4418 }
4419 // Don't call this while holding the lock as this operation might hit the disk.
4420 return task.getSnapshot(reducedResolution);
4421 } finally {
4422 Binder.restoreCallingIdentity(ident);
4423 }
4424 }
4425
4426 @Override
4427 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4428 synchronized (mGlobalLock) {
4429 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4430 if (r == null) {
4431 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4432 + token);
4433 return;
4434 }
4435 final long origId = Binder.clearCallingIdentity();
4436 try {
4437 r.setDisablePreviewScreenshots(disable);
4438 } finally {
4439 Binder.restoreCallingIdentity(origId);
4440 }
4441 }
4442 }
4443
4444 /** Return the user id of the last resumed activity. */
4445 @Override
4446 public @UserIdInt
4447 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004449 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4450 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004451 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004452 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004453 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004454 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004455 }
4456 }
4457
4458 @Override
4459 public void updateLockTaskFeatures(int userId, int flags) {
4460 final int callingUid = Binder.getCallingUid();
4461 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004462 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004463 "updateLockTaskFeatures()");
4464 }
4465 synchronized (mGlobalLock) {
4466 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4467 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004468 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004469 }
4470 }
4471
4472 @Override
4473 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4474 synchronized (mGlobalLock) {
4475 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4476 if (r == null) {
4477 return;
4478 }
4479 final long origId = Binder.clearCallingIdentity();
4480 try {
4481 r.setShowWhenLocked(showWhenLocked);
4482 } finally {
4483 Binder.restoreCallingIdentity(origId);
4484 }
4485 }
4486 }
4487
4488 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004489 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4490 synchronized (mGlobalLock) {
4491 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4492 if (r == null) {
4493 return;
4494 }
4495 final long origId = Binder.clearCallingIdentity();
4496 try {
4497 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4498 } finally {
4499 Binder.restoreCallingIdentity(origId);
4500 }
4501 }
4502 }
4503
4504 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004505 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4506 synchronized (mGlobalLock) {
4507 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4508 if (r == null) {
4509 return;
4510 }
4511 final long origId = Binder.clearCallingIdentity();
4512 try {
4513 r.setTurnScreenOn(turnScreenOn);
4514 } finally {
4515 Binder.restoreCallingIdentity(origId);
4516 }
4517 }
4518 }
4519
4520 @Override
4521 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004523 "registerRemoteAnimations");
4524 definition.setCallingPid(Binder.getCallingPid());
4525 synchronized (mGlobalLock) {
4526 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4527 if (r == null) {
4528 return;
4529 }
4530 final long origId = Binder.clearCallingIdentity();
4531 try {
4532 r.registerRemoteAnimations(definition);
4533 } finally {
4534 Binder.restoreCallingIdentity(origId);
4535 }
4536 }
4537 }
4538
4539 @Override
4540 public void registerRemoteAnimationForNextActivityStart(String packageName,
4541 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004542 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004543 "registerRemoteAnimationForNextActivityStart");
4544 adapter.setCallingPid(Binder.getCallingPid());
4545 synchronized (mGlobalLock) {
4546 final long origId = Binder.clearCallingIdentity();
4547 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004548 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004549 packageName, adapter);
4550 } finally {
4551 Binder.restoreCallingIdentity(origId);
4552 }
4553 }
4554 }
4555
Evan Rosky966759f2019-01-15 10:33:58 -08004556 @Override
4557 public void registerRemoteAnimationsForDisplay(int displayId,
4558 RemoteAnimationDefinition definition) {
4559 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4560 "registerRemoteAnimations");
4561 definition.setCallingPid(Binder.getCallingPid());
4562 synchronized (mGlobalLock) {
4563 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4564 if (display == null) {
4565 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4566 return;
4567 }
4568 final long origId = Binder.clearCallingIdentity();
4569 try {
4570 display.mDisplayContent.registerRemoteAnimations(definition);
4571 } finally {
4572 Binder.restoreCallingIdentity(origId);
4573 }
4574 }
4575 }
4576
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004577 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4578 @Override
4579 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4580 synchronized (mGlobalLock) {
4581 final long origId = Binder.clearCallingIdentity();
4582 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004583 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004584 } finally {
4585 Binder.restoreCallingIdentity(origId);
4586 }
4587 }
4588 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004589
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004590 @Override
4591 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004592 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004593 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004594 final int pid = Binder.getCallingPid();
4595 final WindowProcessController wpc = mPidMap.get(pid);
4596 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004597 }
4598 }
4599
4600 @Override
4601 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004602 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004603 != PERMISSION_GRANTED) {
4604 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4605 + Binder.getCallingPid()
4606 + ", uid=" + Binder.getCallingUid()
4607 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4608 Slog.w(TAG, msg);
4609 throw new SecurityException(msg);
4610 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004611 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004612 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004613 final int pid = Binder.getCallingPid();
4614 final WindowProcessController proc = mPidMap.get(pid);
4615 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004616 }
4617 }
4618
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004619 @Override
4620 public void stopAppSwitches() {
4621 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4622 synchronized (mGlobalLock) {
4623 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4624 mDidAppSwitch = false;
4625 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4626 }
4627 }
4628
4629 @Override
4630 public void resumeAppSwitches() {
4631 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4632 synchronized (mGlobalLock) {
4633 // Note that we don't execute any pending app switches... we will
4634 // let those wait until either the timeout, or the next start
4635 // activity request.
4636 mAppSwitchesAllowedTime = 0;
4637 }
4638 }
4639
4640 void onStartActivitySetDidAppSwitch() {
4641 if (mDidAppSwitch) {
4642 // This is the second allowed switch since we stopped switches, so now just generally
4643 // allow switches. Use case:
4644 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4645 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4646 // anyone to switch again).
4647 mAppSwitchesAllowedTime = 0;
4648 } else {
4649 mDidAppSwitch = true;
4650 }
4651 }
4652
4653 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004654 boolean shouldDisableNonVrUiLocked() {
4655 return mVrController.shouldDisableNonVrUiLocked();
4656 }
4657
Wale Ogunwale53783742018-09-16 10:21:51 -07004658 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004659 // VR apps are expected to run in a main display. If an app is turning on VR for
4660 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4661 // fullscreen stack before enabling VR Mode.
4662 // TODO: The goal of this code is to keep the VR app on the main display. When the
4663 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4664 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4665 // option would be a better choice here.
4666 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4667 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4668 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004669 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004670 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004671 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004672 }
4673 mH.post(() -> {
4674 if (!mVrController.onVrModeChanged(r)) {
4675 return;
4676 }
4677 synchronized (mGlobalLock) {
4678 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4679 mWindowManager.disableNonVrUi(disableNonVrUi);
4680 if (disableNonVrUi) {
4681 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4682 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004683 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004684 }
4685 }
4686 });
4687 }
4688
Wale Ogunwale53783742018-09-16 10:21:51 -07004689 @Override
4690 public int getPackageScreenCompatMode(String packageName) {
4691 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4692 synchronized (mGlobalLock) {
4693 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4694 }
4695 }
4696
4697 @Override
4698 public void setPackageScreenCompatMode(String packageName, int mode) {
4699 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4700 "setPackageScreenCompatMode");
4701 synchronized (mGlobalLock) {
4702 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4703 }
4704 }
4705
4706 @Override
4707 public boolean getPackageAskScreenCompat(String packageName) {
4708 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4709 synchronized (mGlobalLock) {
4710 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4711 }
4712 }
4713
4714 @Override
4715 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4716 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4717 "setPackageAskScreenCompat");
4718 synchronized (mGlobalLock) {
4719 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4720 }
4721 }
4722
Wale Ogunwale64258362018-10-16 15:13:37 -07004723 public static String relaunchReasonToString(int relaunchReason) {
4724 switch (relaunchReason) {
4725 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4726 return "window_resize";
4727 case RELAUNCH_REASON_FREE_RESIZE:
4728 return "free_resize";
4729 default:
4730 return null;
4731 }
4732 }
4733
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004734 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004735 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004736 }
4737
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004738 /** Pokes the task persister. */
4739 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4740 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4741 }
4742
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004743 boolean isKeyguardLocked() {
4744 return mKeyguardController.isKeyguardLocked();
4745 }
4746
Garfield Tan01548632018-11-27 10:15:48 -08004747 /**
4748 * Clears launch params for the given package.
4749 * @param packageNames the names of the packages of which the launch params are to be cleared
4750 */
4751 @Override
4752 public void clearLaunchParamsForPackages(List<String> packageNames) {
4753 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4754 "clearLaunchParamsForPackages");
4755 synchronized (mGlobalLock) {
4756 for (int i = 0; i < packageNames.size(); ++i) {
4757 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4758 }
4759 }
4760 }
4761
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004762 /**
4763 * Makes the display with the given id a single task instance display. I.e the display can only
4764 * contain one task.
4765 */
4766 @Override
4767 public void setDisplayToSingleTaskInstance(int displayId) {
4768 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4769 "setDisplayToSingleTaskInstance");
4770 final long origId = Binder.clearCallingIdentity();
4771 try {
4772 final ActivityDisplay display =
4773 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4774 if (display != null) {
4775 display.setDisplayToSingleTaskInstance();
4776 }
4777 } finally {
4778 Binder.restoreCallingIdentity(origId);
4779 }
4780 }
4781
Wale Ogunwale31913b52018-10-13 08:29:31 -07004782 void dumpLastANRLocked(PrintWriter pw) {
4783 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4784 if (mLastANRState == null) {
4785 pw.println(" <no ANR has occurred since boot>");
4786 } else {
4787 pw.println(mLastANRState);
4788 }
4789 }
4790
4791 void dumpLastANRTracesLocked(PrintWriter pw) {
4792 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4793
4794 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4795 if (ArrayUtils.isEmpty(files)) {
4796 pw.println(" <no ANR has occurred since boot>");
4797 return;
4798 }
4799 // Find the latest file.
4800 File latest = null;
4801 for (File f : files) {
4802 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4803 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004804 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004805 }
4806 pw.print("File: ");
4807 pw.print(latest.getName());
4808 pw.println();
4809 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4810 String line;
4811 while ((line = in.readLine()) != null) {
4812 pw.println(line);
4813 }
4814 } catch (IOException e) {
4815 pw.print("Unable to read: ");
4816 pw.print(e);
4817 pw.println();
4818 }
4819 }
4820
4821 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4822 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4823 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4824 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4825 }
4826
4827 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4828 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4829 pw.println(header);
4830
Wale Ogunwaled32da472018-11-16 07:19:28 -08004831 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004832 dumpPackage);
4833 boolean needSep = printedAnything;
4834
4835 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004836 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004837 " ResumedActivity: ");
4838 if (printed) {
4839 printedAnything = true;
4840 needSep = false;
4841 }
4842
4843 if (dumpPackage == null) {
4844 if (needSep) {
4845 pw.println();
4846 }
4847 printedAnything = true;
4848 mStackSupervisor.dump(pw, " ");
4849 }
4850
4851 if (!printedAnything) {
4852 pw.println(" (nothing)");
4853 }
4854 }
4855
4856 void dumpActivityContainersLocked(PrintWriter pw) {
4857 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004858 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004859 pw.println(" ");
4860 }
4861
4862 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4863 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4864 getActivityStartController().dump(pw, "", dumpPackage);
4865 }
4866
4867 /**
4868 * There are three things that cmd can be:
4869 * - a flattened component name that matches an existing activity
4870 * - the cmd arg isn't the flattened component name of an existing activity:
4871 * dump all activity whose component contains the cmd as a substring
4872 * - A hex number of the ActivityRecord object instance.
4873 *
4874 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4875 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4876 */
4877 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4878 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4879 ArrayList<ActivityRecord> activities;
4880
4881 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004882 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004883 dumpFocusedStackOnly);
4884 }
4885
4886 if (activities.size() <= 0) {
4887 return false;
4888 }
4889
4890 String[] newArgs = new String[args.length - opti];
4891 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4892
4893 TaskRecord lastTask = null;
4894 boolean needSep = false;
4895 for (int i = activities.size() - 1; i >= 0; i--) {
4896 ActivityRecord r = activities.get(i);
4897 if (needSep) {
4898 pw.println();
4899 }
4900 needSep = true;
4901 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004902 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004903 if (lastTask != task) {
4904 lastTask = task;
4905 pw.print("TASK "); pw.print(lastTask.affinity);
4906 pw.print(" id="); pw.print(lastTask.taskId);
4907 pw.print(" userId="); pw.println(lastTask.userId);
4908 if (dumpAll) {
4909 lastTask.dump(pw, " ");
4910 }
4911 }
4912 }
4913 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4914 }
4915 return true;
4916 }
4917
4918 /**
4919 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4920 * there is a thread associated with the activity.
4921 */
4922 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4923 final ActivityRecord r, String[] args, boolean dumpAll) {
4924 String innerPrefix = prefix + " ";
4925 synchronized (mGlobalLock) {
4926 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4927 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4928 pw.print(" pid=");
4929 if (r.hasProcess()) pw.println(r.app.getPid());
4930 else pw.println("(not running)");
4931 if (dumpAll) {
4932 r.dump(pw, innerPrefix);
4933 }
4934 }
4935 if (r.attachedToProcess()) {
4936 // flush anything that is already in the PrintWriter since the thread is going
4937 // to write to the file descriptor directly
4938 pw.flush();
4939 try {
4940 TransferPipe tp = new TransferPipe();
4941 try {
4942 r.app.getThread().dumpActivity(tp.getWriteFd(),
4943 r.appToken, innerPrefix, args);
4944 tp.go(fd);
4945 } finally {
4946 tp.kill();
4947 }
4948 } catch (IOException e) {
4949 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4950 } catch (RemoteException e) {
4951 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4952 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004953 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004954 }
4955
sanryhuang498e77e2018-12-06 14:57:01 +08004956 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4957 boolean testPssMode) {
4958 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4959 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4960 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004961 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004962 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4963 st.toString());
4964 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004965 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4966 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4967 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004968 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4969 testPssMode);
4970 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004971 }
4972
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004973 int getCurrentUserId() {
4974 return mAmInternal.getCurrentUserId();
4975 }
4976
4977 private void enforceNotIsolatedCaller(String caller) {
4978 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4979 throw new SecurityException("Isolated process not allowed to call " + caller);
4980 }
4981 }
4982
Wale Ogunwalef6733932018-06-27 05:14:34 -07004983 public Configuration getConfiguration() {
4984 Configuration ci;
4985 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004986 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004987 ci.userSetLocale = false;
4988 }
4989 return ci;
4990 }
4991
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004992 /**
4993 * Current global configuration information. Contains general settings for the entire system,
4994 * also corresponds to the merged configuration of the default display.
4995 */
4996 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004997 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004998 }
4999
5000 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5001 boolean initLocale) {
5002 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
5003 }
5004
5005 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5006 boolean initLocale, boolean deferResume) {
5007 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
5008 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
5009 UserHandle.USER_NULL, deferResume);
5010 }
5011
Wale Ogunwale59507092018-10-29 09:00:30 -07005012 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005013 final long origId = Binder.clearCallingIdentity();
5014 try {
5015 synchronized (mGlobalLock) {
5016 updateConfigurationLocked(values, null, false, true, userId,
5017 false /* deferResume */);
5018 }
5019 } finally {
5020 Binder.restoreCallingIdentity(origId);
5021 }
5022 }
5023
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005024 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5025 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
5026 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
5027 deferResume, null /* result */);
5028 }
5029
5030 /**
5031 * Do either or both things: (1) change the current configuration, and (2)
5032 * make sure the given activity is running with the (now) current
5033 * configuration. Returns true if the activity has been left running, or
5034 * false if <var>starting</var> is being destroyed to match the new
5035 * configuration.
5036 *
5037 * @param userId is only used when persistent parameter is set to true to persist configuration
5038 * for that particular user
5039 */
5040 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
5041 boolean initLocale, boolean persistent, int userId, boolean deferResume,
5042 ActivityTaskManagerService.UpdateConfigurationResult result) {
5043 int changes = 0;
5044 boolean kept = true;
5045
5046 if (mWindowManager != null) {
5047 mWindowManager.deferSurfaceLayout();
5048 }
5049 try {
5050 if (values != null) {
5051 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
5052 deferResume);
5053 }
5054
5055 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5056 } finally {
5057 if (mWindowManager != null) {
5058 mWindowManager.continueSurfaceLayout();
5059 }
5060 }
5061
5062 if (result != null) {
5063 result.changes = changes;
5064 result.activityRelaunched = !kept;
5065 }
5066 return kept;
5067 }
5068
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005069 /** Update default (global) configuration and notify listeners about changes. */
5070 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
5071 boolean persistent, int userId, boolean deferResume) {
5072 mTempConfig.setTo(getGlobalConfiguration());
5073 final int changes = mTempConfig.updateFrom(values);
5074 if (changes == 0) {
5075 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
5076 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
5077 // performDisplayOverrideConfigUpdate in order to send the new display configuration
5078 // (even if there are no actual changes) to unfreeze the window.
5079 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
5080 return 0;
5081 }
5082
5083 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
5084 "Updating global configuration to: " + values);
5085
5086 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
5087 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
5088 values.colorMode,
5089 values.densityDpi,
5090 values.fontScale,
5091 values.hardKeyboardHidden,
5092 values.keyboard,
5093 values.keyboardHidden,
5094 values.mcc,
5095 values.mnc,
5096 values.navigation,
5097 values.navigationHidden,
5098 values.orientation,
5099 values.screenHeightDp,
5100 values.screenLayout,
5101 values.screenWidthDp,
5102 values.smallestScreenWidthDp,
5103 values.touchscreen,
5104 values.uiMode);
5105
5106
5107 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5108 final LocaleList locales = values.getLocales();
5109 int bestLocaleIndex = 0;
5110 if (locales.size() > 1) {
5111 if (mSupportedSystemLocales == null) {
5112 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5113 }
5114 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5115 }
5116 SystemProperties.set("persist.sys.locale",
5117 locales.get(bestLocaleIndex).toLanguageTag());
5118 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005119
5120 final Message m = PooledLambda.obtainMessage(
5121 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5122 locales.get(bestLocaleIndex));
5123 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005124 }
5125
Yunfan Chen75157d72018-07-27 14:47:21 +09005126 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005127
5128 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005129 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005130
5131 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5132 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005133 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134
5135 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005136 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137
5138 AttributeCache ac = AttributeCache.instance();
5139 if (ac != null) {
5140 ac.updateConfiguration(mTempConfig);
5141 }
5142
5143 // Make sure all resources in our process are updated right now, so that anyone who is going
5144 // to retrieve resource values after we return will be sure to get the new ones. This is
5145 // especially important during boot, where the first config change needs to guarantee all
5146 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005147 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005148
5149 // We need another copy of global config because we're scheduling some calls instead of
5150 // running them in place. We need to be sure that object we send will be handled unchanged.
5151 final Configuration configCopy = new Configuration(mTempConfig);
5152 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005153 final Message msg = PooledLambda.obtainMessage(
5154 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5155 this, userId, configCopy);
5156 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005157 }
5158
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005159 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005160 final int pid = mPidMap.keyAt(i);
5161 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005162 if (DEBUG_CONFIGURATION) {
5163 Slog.v(TAG_CONFIGURATION, "Update process config of "
5164 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005165 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005166 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005167 }
5168
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005169 final Message msg = PooledLambda.obtainMessage(
5170 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5171 mAmInternal, changes, initLocale);
5172 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005173
5174 // Override configuration of the default display duplicates global config, so we need to
5175 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005176 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005177 DEFAULT_DISPLAY);
5178
5179 return changes;
5180 }
5181
5182 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5183 boolean deferResume, int displayId) {
5184 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5185 displayId, null /* result */);
5186 }
5187
5188 /**
5189 * Updates override configuration specific for the selected display. If no config is provided,
5190 * new one will be computed in WM based on current display info.
5191 */
5192 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5193 ActivityRecord starting, boolean deferResume, int displayId,
5194 ActivityTaskManagerService.UpdateConfigurationResult result) {
5195 int changes = 0;
5196 boolean kept = true;
5197
5198 if (mWindowManager != null) {
5199 mWindowManager.deferSurfaceLayout();
5200 }
5201 try {
5202 if (values != null) {
5203 if (displayId == DEFAULT_DISPLAY) {
5204 // Override configuration of the default display duplicates global config, so
5205 // we're calling global config update instead for default display. It will also
5206 // apply the correct override config.
5207 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5208 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5209 } else {
5210 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5211 }
5212 }
5213
5214 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5215 } finally {
5216 if (mWindowManager != null) {
5217 mWindowManager.continueSurfaceLayout();
5218 }
5219 }
5220
5221 if (result != null) {
5222 result.changes = changes;
5223 result.activityRelaunched = !kept;
5224 }
5225 return kept;
5226 }
5227
5228 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5229 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005230 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005231 final int changes = mTempConfig.updateFrom(values);
5232 if (changes != 0) {
5233 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5234 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005235 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005236
5237 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5238 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005239 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005240
Wale Ogunwale5c918702018-10-18 11:06:33 -07005241 // Post message to start process to avoid possible deadlock of calling into AMS with
5242 // the ATMS lock held.
5243 final Message msg = PooledLambda.obtainMessage(
5244 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5245 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5246 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005247 }
5248 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005249 return changes;
5250 }
5251
Wale Ogunwalef6733932018-06-27 05:14:34 -07005252 private void updateEventDispatchingLocked(boolean booted) {
5253 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5254 }
5255
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005256 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5257 final ContentResolver resolver = mContext.getContentResolver();
5258 Settings.System.putConfigurationForUser(resolver, config, userId);
5259 }
5260
5261 private void sendLocaleToMountDaemonMsg(Locale l) {
5262 try {
5263 IBinder service = ServiceManager.getService("mount");
5264 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5265 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5266 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5267 } catch (RemoteException e) {
5268 Log.e(TAG, "Error storing locale for decryption UI", e);
5269 }
5270 }
5271
Alison Cichowlas3e340502018-08-07 17:15:01 -04005272 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5273 mStartActivitySources.remove(permissionToken);
5274 mExpiredStartAsCallerTokens.add(permissionToken);
5275 }
5276
5277 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5278 mExpiredStartAsCallerTokens.remove(permissionToken);
5279 }
5280
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005281 boolean isActivityStartsLoggingEnabled() {
5282 return mAmInternal.isActivityStartsLoggingEnabled();
5283 }
5284
Michal Karpinski8596ded2018-11-14 14:43:48 +00005285 boolean isBackgroundActivityStartsEnabled() {
5286 return mAmInternal.isBackgroundActivityStartsEnabled();
5287 }
5288
Michal Karpinski666631b2019-02-26 16:59:11 +00005289 boolean isPackageNameWhitelistedForBgActivityStarts(String packageName) {
5290 return mAmInternal.isPackageNameWhitelistedForBgActivityStarts(packageName);
5291 }
5292
Wale Ogunwalef6733932018-06-27 05:14:34 -07005293 void enableScreenAfterBoot(boolean booted) {
5294 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5295 SystemClock.uptimeMillis());
5296 mWindowManager.enableScreenAfterBoot();
5297
5298 synchronized (mGlobalLock) {
5299 updateEventDispatchingLocked(booted);
5300 }
5301 }
5302
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005303 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5304 if (r == null || !r.hasProcess()) {
5305 return KEY_DISPATCHING_TIMEOUT_MS;
5306 }
5307 return getInputDispatchingTimeoutLocked(r.app);
5308 }
5309
5310 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005311 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005312 }
5313
Wale Ogunwalef6733932018-06-27 05:14:34 -07005314 /**
5315 * Decide based on the configuration whether we should show the ANR,
5316 * crash, etc dialogs. The idea is that if there is no affordance to
5317 * press the on-screen buttons, or the user experience would be more
5318 * greatly impacted than the crash itself, we shouldn't show the dialog.
5319 *
5320 * A thought: SystemUI might also want to get told about this, the Power
5321 * dialog / global actions also might want different behaviors.
5322 */
5323 private void updateShouldShowDialogsLocked(Configuration config) {
5324 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5325 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5326 && config.navigation == Configuration.NAVIGATION_NONAV);
5327 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5328 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5329 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5330 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5331 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5332 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5333 HIDE_ERROR_DIALOGS, 0) != 0;
5334 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5335 }
5336
5337 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5338 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5339 FONT_SCALE, 1.0f, userId);
5340
5341 synchronized (this) {
5342 if (getGlobalConfiguration().fontScale == scaleFactor) {
5343 return;
5344 }
5345
5346 final Configuration configuration
5347 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5348 configuration.fontScale = scaleFactor;
5349 updatePersistentConfiguration(configuration, userId);
5350 }
5351 }
5352
5353 // Actually is sleeping or shutting down or whatever else in the future
5354 // is an inactive state.
5355 boolean isSleepingOrShuttingDownLocked() {
5356 return isSleepingLocked() || mShuttingDown;
5357 }
5358
5359 boolean isSleepingLocked() {
5360 return mSleeping;
5361 }
5362
Riddle Hsu16567132018-08-16 21:37:47 +08005363 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005364 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005365 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005366 if (task.isActivityTypeStandard()) {
5367 if (mCurAppTimeTracker != r.appTimeTracker) {
5368 // We are switching app tracking. Complete the current one.
5369 if (mCurAppTimeTracker != null) {
5370 mCurAppTimeTracker.stop();
5371 mH.obtainMessage(
5372 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005373 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005374 mCurAppTimeTracker = null;
5375 }
5376 if (r.appTimeTracker != null) {
5377 mCurAppTimeTracker = r.appTimeTracker;
5378 startTimeTrackingFocusedActivityLocked();
5379 }
5380 } else {
5381 startTimeTrackingFocusedActivityLocked();
5382 }
5383 } else {
5384 r.appTimeTracker = null;
5385 }
5386 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5387 // TODO: Probably not, because we don't want to resume voice on switching
5388 // back to this activity
5389 if (task.voiceInteractor != null) {
5390 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5391 } else {
5392 finishRunningVoiceLocked();
5393
5394 if (mLastResumedActivity != null) {
5395 final IVoiceInteractionSession session;
5396
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005397 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005398 if (lastResumedActivityTask != null
5399 && lastResumedActivityTask.voiceSession != null) {
5400 session = lastResumedActivityTask.voiceSession;
5401 } else {
5402 session = mLastResumedActivity.voiceSession;
5403 }
5404
5405 if (session != null) {
5406 // We had been in a voice interaction session, but now focused has
5407 // move to something different. Just finish the session, we can't
5408 // return to it and retain the proper state and synchronization with
5409 // the voice interaction service.
5410 finishVoiceTask(session);
5411 }
5412 }
5413 }
5414
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005415 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5416 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005417 }
5418 updateResumedAppTrace(r);
5419 mLastResumedActivity = r;
5420
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005421 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005422
5423 applyUpdateLockStateLocked(r);
5424 applyUpdateVrModeLocked(r);
5425
5426 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005427 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005428 r == null ? "NULL" : r.shortComponentName,
5429 reason);
5430 }
5431
5432 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5433 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005434 final ActivityTaskManagerInternal.SleepToken token =
5435 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005436 updateSleepIfNeededLocked();
5437 return token;
5438 }
5439 }
5440
5441 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005442 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005443 final boolean wasSleeping = mSleeping;
5444 boolean updateOomAdj = false;
5445
5446 if (!shouldSleep) {
5447 // If wasSleeping is true, we need to wake up activity manager state from when
5448 // we started sleeping. In either case, we need to apply the sleep tokens, which
5449 // will wake up stacks or put them to sleep as appropriate.
5450 if (wasSleeping) {
5451 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005452 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5453 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005454 startTimeTrackingFocusedActivityLocked();
5455 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5456 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5457 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005458 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005459 if (wasSleeping) {
5460 updateOomAdj = true;
5461 }
5462 } else if (!mSleeping && shouldSleep) {
5463 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005464 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5465 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005466 if (mCurAppTimeTracker != null) {
5467 mCurAppTimeTracker.stop();
5468 }
5469 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5470 mStackSupervisor.goingToSleepLocked();
5471 updateResumedAppTrace(null /* resumed */);
5472 updateOomAdj = true;
5473 }
5474 if (updateOomAdj) {
5475 mH.post(mAmInternal::updateOomAdj);
5476 }
5477 }
5478
5479 void updateOomAdj() {
5480 mH.post(mAmInternal::updateOomAdj);
5481 }
5482
Wale Ogunwale53783742018-09-16 10:21:51 -07005483 void updateCpuStats() {
5484 mH.post(mAmInternal::updateCpuStats);
5485 }
5486
Hui Yu03d12402018-12-06 18:00:37 -08005487 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5488 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005489 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5490 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005491 mH.sendMessage(m);
5492 }
5493
Hui Yu03d12402018-12-06 18:00:37 -08005494 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005495 ComponentName taskRoot = null;
5496 final TaskRecord task = activity.getTaskRecord();
5497 if (task != null) {
5498 final ActivityRecord rootActivity = task.getRootActivity();
5499 if (rootActivity != null) {
5500 taskRoot = rootActivity.mActivityComponent;
5501 }
5502 }
5503
Hui Yu03d12402018-12-06 18:00:37 -08005504 final Message m = PooledLambda.obtainMessage(
5505 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005506 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005507 mH.sendMessage(m);
5508 }
5509
Wale Ogunwale53783742018-09-16 10:21:51 -07005510 void setBooting(boolean booting) {
5511 mAmInternal.setBooting(booting);
5512 }
5513
5514 boolean isBooting() {
5515 return mAmInternal.isBooting();
5516 }
5517
5518 void setBooted(boolean booted) {
5519 mAmInternal.setBooted(booted);
5520 }
5521
5522 boolean isBooted() {
5523 return mAmInternal.isBooted();
5524 }
5525
5526 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5527 mH.post(() -> {
5528 if (finishBooting) {
5529 mAmInternal.finishBooting();
5530 }
5531 if (enableScreen) {
5532 mInternal.enableScreenAfterBoot(isBooted());
5533 }
5534 });
5535 }
5536
5537 void setHeavyWeightProcess(ActivityRecord root) {
5538 mHeavyWeightProcess = root.app;
5539 final Message m = PooledLambda.obtainMessage(
5540 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005541 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005542 mH.sendMessage(m);
5543 }
5544
5545 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5546 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5547 return;
5548 }
5549
5550 mHeavyWeightProcess = null;
5551 final Message m = PooledLambda.obtainMessage(
5552 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5553 proc.mUserId);
5554 mH.sendMessage(m);
5555 }
5556
5557 private void cancelHeavyWeightProcessNotification(int userId) {
5558 final INotificationManager inm = NotificationManager.getService();
5559 if (inm == null) {
5560 return;
5561 }
5562 try {
5563 inm.cancelNotificationWithTag("android", null,
5564 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5565 } catch (RuntimeException e) {
5566 Slog.w(TAG, "Error canceling notification for service", e);
5567 } catch (RemoteException e) {
5568 }
5569
5570 }
5571
5572 private void postHeavyWeightProcessNotification(
5573 WindowProcessController proc, Intent intent, int userId) {
5574 if (proc == null) {
5575 return;
5576 }
5577
5578 final INotificationManager inm = NotificationManager.getService();
5579 if (inm == null) {
5580 return;
5581 }
5582
5583 try {
5584 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5585 String text = mContext.getString(R.string.heavy_weight_notification,
5586 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5587 Notification notification =
5588 new Notification.Builder(context,
5589 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5590 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5591 .setWhen(0)
5592 .setOngoing(true)
5593 .setTicker(text)
5594 .setColor(mContext.getColor(
5595 com.android.internal.R.color.system_notification_accent_color))
5596 .setContentTitle(text)
5597 .setContentText(
5598 mContext.getText(R.string.heavy_weight_notification_detail))
5599 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5600 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5601 new UserHandle(userId)))
5602 .build();
5603 try {
5604 inm.enqueueNotificationWithTag("android", "android", null,
5605 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5606 } catch (RuntimeException e) {
5607 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5608 } catch (RemoteException e) {
5609 }
5610 } catch (PackageManager.NameNotFoundException e) {
5611 Slog.w(TAG, "Unable to create context for heavy notification", e);
5612 }
5613
5614 }
5615
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005616 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5617 IBinder token, String resultWho, int requestCode, Intent[] intents,
5618 String[] resolvedTypes, int flags, Bundle bOptions) {
5619
5620 ActivityRecord activity = null;
5621 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5622 activity = ActivityRecord.isInStackLocked(token);
5623 if (activity == null) {
5624 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5625 return null;
5626 }
5627 if (activity.finishing) {
5628 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5629 return null;
5630 }
5631 }
5632
5633 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5634 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5635 bOptions);
5636 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5637 if (noCreate) {
5638 return rec;
5639 }
5640 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5641 if (activity.pendingResults == null) {
5642 activity.pendingResults = new HashSet<>();
5643 }
5644 activity.pendingResults.add(rec.ref);
5645 }
5646 return rec;
5647 }
5648
Andrii Kulian52d255c2018-07-13 11:32:19 -07005649 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005650 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005651 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005652 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5653 mCurAppTimeTracker.start(resumedActivity.packageName);
5654 }
5655 }
5656
5657 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5658 if (mTracedResumedActivity != null) {
5659 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5660 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5661 }
5662 if (resumed != null) {
5663 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5664 constructResumedTraceName(resumed.packageName), 0);
5665 }
5666 mTracedResumedActivity = resumed;
5667 }
5668
5669 private String constructResumedTraceName(String packageName) {
5670 return "focused app: " + packageName;
5671 }
5672
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005673 /** Applies latest configuration and/or visibility updates if needed. */
5674 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5675 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005676 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005677 // mainStack is null during startup.
5678 if (mainStack != null) {
5679 if (changes != 0 && starting == null) {
5680 // If the configuration changed, and the caller is not already
5681 // in the process of starting an activity, then find the top
5682 // activity to check if its configuration needs to change.
5683 starting = mainStack.topRunningActivityLocked();
5684 }
5685
5686 if (starting != null) {
5687 kept = starting.ensureActivityConfiguration(changes,
5688 false /* preserveWindow */);
5689 // And we need to make sure at this point that all other activities
5690 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005691 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005692 !PRESERVE_WINDOWS);
5693 }
5694 }
5695
5696 return kept;
5697 }
5698
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005699 void scheduleAppGcsLocked() {
5700 mH.post(() -> mAmInternal.scheduleAppGcs());
5701 }
5702
Wale Ogunwale53783742018-09-16 10:21:51 -07005703 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5704 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5705 }
5706
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005707 /**
5708 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5709 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5710 * on demand.
5711 */
5712 IPackageManager getPackageManager() {
5713 return AppGlobals.getPackageManager();
5714 }
5715
5716 PackageManagerInternal getPackageManagerInternalLocked() {
5717 if (mPmInternal == null) {
5718 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5719 }
5720 return mPmInternal;
5721 }
5722
Wale Ogunwale008163e2018-07-23 23:11:08 -07005723 AppWarnings getAppWarningsLocked() {
5724 return mAppWarnings;
5725 }
5726
Wale Ogunwale214f3482018-10-04 11:00:47 -07005727 Intent getHomeIntent() {
5728 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5729 intent.setComponent(mTopComponent);
5730 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5731 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5732 intent.addCategory(Intent.CATEGORY_HOME);
5733 }
5734 return intent;
5735 }
5736
Chilun2ef71f72018-11-16 17:57:15 +08005737 /**
5738 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5739 * activities.
5740 *
5741 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5742 * component defined in config_secondaryHomeComponent.
5743 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5744 */
5745 Intent getSecondaryHomeIntent(String preferredPackage) {
5746 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5747 if (preferredPackage == null) {
5748 // Using the component stored in config if no package name.
5749 final String secondaryHomeComponent = mContext.getResources().getString(
5750 com.android.internal.R.string.config_secondaryHomeComponent);
5751 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5752 } else {
5753 intent.setPackage(preferredPackage);
5754 }
5755 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5756 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5757 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5758 }
5759 return intent;
5760 }
5761
Wale Ogunwale214f3482018-10-04 11:00:47 -07005762 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5763 if (info == null) return null;
5764 ApplicationInfo newInfo = new ApplicationInfo(info);
5765 newInfo.initForUser(userId);
5766 return newInfo;
5767 }
5768
Wale Ogunwale9c103022018-10-18 07:44:54 -07005769 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005770 if (uid == SYSTEM_UID) {
5771 // The system gets to run in any process. If there are multiple processes with the same
5772 // uid, just pick the first (this should never happen).
5773 final SparseArray<WindowProcessController> procs =
5774 mProcessNames.getMap().get(processName);
5775 if (procs == null) return null;
5776 final int procCount = procs.size();
5777 for (int i = 0; i < procCount; i++) {
5778 final int procUid = procs.keyAt(i);
5779 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5780 // Don't use an app process or different user process for system component.
5781 continue;
5782 }
5783 return procs.valueAt(i);
5784 }
5785 }
5786
5787 return mProcessNames.get(processName, uid);
5788 }
5789
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005790 WindowProcessController getProcessController(IApplicationThread thread) {
5791 if (thread == null) {
5792 return null;
5793 }
5794
5795 final IBinder threadBinder = thread.asBinder();
5796 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5797 for (int i = pmap.size()-1; i >= 0; i--) {
5798 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5799 for (int j = procs.size() - 1; j >= 0; j--) {
5800 final WindowProcessController proc = procs.valueAt(j);
5801 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5802 return proc;
5803 }
5804 }
5805 }
5806
5807 return null;
5808 }
5809
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005810 WindowProcessController getProcessController(int pid, int uid) {
5811 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5812 for (int i = pmap.size()-1; i >= 0; i--) {
5813 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5814 for (int j = procs.size() - 1; j >= 0; j--) {
5815 final WindowProcessController proc = procs.valueAt(j);
5816 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5817 return proc;
5818 }
5819 }
5820 }
5821 return null;
5822 }
5823
Riddle Hsua0536432019-02-16 00:38:59 +08005824 int getUidState(int uid) {
5825 return mActiveUids.getUidState(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005826 }
5827
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005828 boolean isUidForeground(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08005829 return (getUidState(uid) == ActivityManager.PROCESS_STATE_TOP)
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005830 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5831 }
5832
Michal Karpinski4026cae2019-02-12 11:51:47 +00005833 boolean isDeviceOwner(String packageName) {
5834 if (packageName == null) {
5835 return false;
5836 }
5837 return packageName.equals(mDeviceOwnerPackageName);
5838 }
5839
5840 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5841 mDeviceOwnerPackageName = deviceOwnerPkg;
5842 }
5843
Wale Ogunwale9de19442018-10-18 19:05:03 -07005844 /**
5845 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5846 * the whitelist
5847 */
5848 String getPendingTempWhitelistTagForUidLocked(int uid) {
5849 return mPendingTempWhitelist.get(uid);
5850 }
5851
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005852 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5853 if (true || Build.IS_USER) {
5854 return;
5855 }
5856
5857 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5858 StrictMode.allowThreadDiskWrites();
5859 try {
5860 File tracesDir = new File("/data/anr");
5861 File tracesFile = null;
5862 try {
5863 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5864
5865 StringBuilder sb = new StringBuilder();
5866 Time tobj = new Time();
5867 tobj.set(System.currentTimeMillis());
5868 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5869 sb.append(": ");
5870 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5871 sb.append(" since ");
5872 sb.append(msg);
5873 FileOutputStream fos = new FileOutputStream(tracesFile);
5874 fos.write(sb.toString().getBytes());
5875 if (app == null) {
5876 fos.write("\n*** No application process!".getBytes());
5877 }
5878 fos.close();
5879 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5880 } catch (IOException e) {
5881 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5882 return;
5883 }
5884
5885 if (app != null && app.getPid() > 0) {
5886 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5887 firstPids.add(app.getPid());
5888 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5889 }
5890
5891 File lastTracesFile = null;
5892 File curTracesFile = null;
5893 for (int i=9; i>=0; i--) {
5894 String name = String.format(Locale.US, "slow%02d.txt", i);
5895 curTracesFile = new File(tracesDir, name);
5896 if (curTracesFile.exists()) {
5897 if (lastTracesFile != null) {
5898 curTracesFile.renameTo(lastTracesFile);
5899 } else {
5900 curTracesFile.delete();
5901 }
5902 }
5903 lastTracesFile = curTracesFile;
5904 }
5905 tracesFile.renameTo(curTracesFile);
5906 } finally {
5907 StrictMode.setThreadPolicy(oldPolicy);
5908 }
5909 }
5910
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005911 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005912 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005913
5914
Wale Ogunwale98875612018-10-12 07:53:02 -07005915 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5916 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005917
Riddle Hsud93a6c42018-11-29 21:50:06 +08005918 H(Looper looper) {
5919 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005920 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005921
5922 @Override
5923 public void handleMessage(Message msg) {
5924 switch (msg.what) {
5925 case REPORT_TIME_TRACKER_MSG: {
5926 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5927 tracker.deliverResult(mContext);
5928 } break;
5929 }
5930 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005931 }
5932
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005933 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005934 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005935
5936 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005937 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005938 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005939
5940 @Override
5941 public void handleMessage(Message msg) {
5942 switch (msg.what) {
5943 case DISMISS_DIALOG_UI_MSG: {
5944 final Dialog d = (Dialog) msg.obj;
5945 d.dismiss();
5946 break;
5947 }
5948 }
5949 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005950 }
5951
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005952 final class LocalService extends ActivityTaskManagerInternal {
5953 @Override
5954 public SleepToken acquireSleepToken(String tag, int displayId) {
5955 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005956 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005957 }
5958
5959 @Override
5960 public ComponentName getHomeActivityForUser(int userId) {
5961 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005962 final ActivityRecord homeActivity =
5963 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005964 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005965 }
5966 }
5967
5968 @Override
5969 public void onLocalVoiceInteractionStarted(IBinder activity,
5970 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5971 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005972 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005973 }
5974 }
5975
5976 @Override
5977 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5978 synchronized (mGlobalLock) {
5979 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5980 reasons, timestamp);
5981 }
5982 }
5983
5984 @Override
5985 public void notifyAppTransitionFinished() {
5986 synchronized (mGlobalLock) {
5987 mStackSupervisor.notifyAppTransitionDone();
5988 }
5989 }
5990
5991 @Override
5992 public void notifyAppTransitionCancelled() {
5993 synchronized (mGlobalLock) {
5994 mStackSupervisor.notifyAppTransitionDone();
5995 }
5996 }
5997
5998 @Override
5999 public List<IBinder> getTopVisibleActivities() {
6000 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006001 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006002 }
6003 }
6004
6005 @Override
6006 public void notifyDockedStackMinimizedChanged(boolean minimized) {
6007 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006008 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006009 }
6010 }
6011
6012 @Override
6013 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
6014 Bundle bOptions) {
6015 Preconditions.checkNotNull(intents, "intents");
6016 final String[] resolvedTypes = new String[intents.length];
6017
6018 // UID of the package on user userId.
6019 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
6020 // packageUid may not be initialized.
6021 int packageUid = 0;
6022 final long ident = Binder.clearCallingIdentity();
6023
6024 try {
6025 for (int i = 0; i < intents.length; i++) {
6026 resolvedTypes[i] =
6027 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
6028 }
6029
6030 packageUid = AppGlobals.getPackageManager().getPackageUid(
6031 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
6032 } catch (RemoteException e) {
6033 // Shouldn't happen.
6034 } finally {
6035 Binder.restoreCallingIdentity(ident);
6036 }
6037
Riddle Hsu591bf612019-02-14 17:55:31 +08006038 return getActivityStartController().startActivitiesInPackage(
6039 packageUid, packageName,
6040 intents, resolvedTypes, null /* resultTo */,
6041 SafeActivityOptions.fromBundle(bOptions), userId,
6042 false /* validateIncomingUser */, null /* originatingPendingIntent */,
6043 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006044 }
6045
6046 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006047 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
6048 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
6049 SafeActivityOptions options, int userId, boolean validateIncomingUser,
6050 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006051 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006052 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00006053 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
6054 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
6055 userId, validateIncomingUser, originatingPendingIntent,
6056 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006057 }
6058 }
6059
6060 @Override
6061 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
6062 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
6063 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
6064 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006065 PendingIntentRecord originatingPendingIntent,
6066 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006067 synchronized (mGlobalLock) {
6068 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
6069 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
6070 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00006071 validateIncomingUser, originatingPendingIntent,
6072 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006073 }
6074 }
6075
6076 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006077 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
6078 Intent intent, Bundle options, int userId) {
6079 return ActivityTaskManagerService.this.startActivityAsUser(
6080 caller, callerPacakge, intent,
6081 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
6082 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
6083 false /*validateIncomingUser*/);
6084 }
6085
6086 @Override
lumark588a3e82018-07-20 18:53:54 +08006087 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006088 synchronized (mGlobalLock) {
6089
6090 // We might change the visibilities here, so prepare an empty app transition which
6091 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08006092 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006093 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08006094 if (activityDisplay == null) {
6095 return;
6096 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006097 final DisplayContent dc = activityDisplay.mDisplayContent;
6098 final boolean wasTransitionSet =
6099 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006100 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006101 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006102 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006103 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006104
6105 // If there was a transition set already we don't want to interfere with it as we
6106 // might be starting it too early.
6107 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006108 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006109 }
6110 }
6111 if (callback != null) {
6112 callback.run();
6113 }
6114 }
6115
6116 @Override
6117 public void notifyKeyguardTrustedChanged() {
6118 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006119 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006120 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006121 }
6122 }
6123 }
6124
6125 /**
6126 * Called after virtual display Id is updated by
6127 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6128 * {@param vrVr2dDisplayId}.
6129 */
6130 @Override
6131 public void setVr2dDisplayId(int vr2dDisplayId) {
6132 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6133 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006134 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006135 }
6136 }
6137
6138 @Override
6139 public void setFocusedActivity(IBinder token) {
6140 synchronized (mGlobalLock) {
6141 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6142 if (r == null) {
6143 throw new IllegalArgumentException(
6144 "setFocusedActivity: No activity record matching token=" + token);
6145 }
Louis Chang19443452018-10-09 12:10:21 +08006146 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006147 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006148 }
6149 }
6150 }
6151
6152 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006153 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006154 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006155 }
6156
6157 @Override
6158 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006159 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006160 }
6161
6162 @Override
6163 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006164 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006165 }
6166
6167 @Override
6168 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6169 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6170 }
6171
6172 @Override
6173 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006174 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006175 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006176
6177 @Override
6178 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6179 synchronized (mGlobalLock) {
6180 mActiveVoiceInteractionServiceComponent = component;
6181 }
6182 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006183
6184 @Override
6185 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6186 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6187 return;
6188 }
6189 synchronized (mGlobalLock) {
6190 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6191 if (types == null) {
6192 if (uid < 0) {
6193 return;
6194 }
6195 types = new ArrayMap<>();
6196 mAllowAppSwitchUids.put(userId, types);
6197 }
6198 if (uid < 0) {
6199 types.remove(type);
6200 } else {
6201 types.put(type, uid);
6202 }
6203 }
6204 }
6205
6206 @Override
6207 public void onUserStopped(int userId) {
6208 synchronized (mGlobalLock) {
6209 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6210 mAllowAppSwitchUids.remove(userId);
6211 }
6212 }
6213
6214 @Override
6215 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6216 synchronized (mGlobalLock) {
6217 return ActivityTaskManagerService.this.isGetTasksAllowed(
6218 caller, callingPid, callingUid);
6219 }
6220 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006221
Riddle Hsua0536432019-02-16 00:38:59 +08006222 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006223 @Override
6224 public void onProcessAdded(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006225 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006226 mProcessNames.put(proc.mName, proc.mUid, proc);
6227 }
6228 }
6229
Riddle Hsua0536432019-02-16 00:38:59 +08006230 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006231 @Override
6232 public void onProcessRemoved(String name, int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08006233 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006234 mProcessNames.remove(name, uid);
6235 }
6236 }
6237
Riddle Hsua0536432019-02-16 00:38:59 +08006238 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006239 @Override
6240 public void onCleanUpApplicationRecord(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006241 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006242 if (proc == mHomeProcess) {
6243 mHomeProcess = null;
6244 }
6245 if (proc == mPreviousProcess) {
6246 mPreviousProcess = null;
6247 }
6248 }
6249 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006250
Riddle Hsua0536432019-02-16 00:38:59 +08006251 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006252 @Override
6253 public int getTopProcessState() {
Riddle Hsua0536432019-02-16 00:38:59 +08006254 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006255 return mTopProcessState;
6256 }
6257 }
6258
Riddle Hsua0536432019-02-16 00:38:59 +08006259 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalef6733932018-06-27 05:14:34 -07006260 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006261 public boolean isHeavyWeightProcess(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006262 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006263 return proc == mHeavyWeightProcess;
6264 }
6265 }
6266
Riddle Hsua0536432019-02-16 00:38:59 +08006267 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale53783742018-09-16 10:21:51 -07006268 @Override
6269 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006270 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006271 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6272 }
6273 }
6274
6275 @Override
6276 public void finishHeavyWeightApp() {
6277 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006278 if (mHeavyWeightProcess != null) {
6279 mHeavyWeightProcess.finishActivities();
6280 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006281 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6282 mHeavyWeightProcess);
6283 }
6284 }
6285
Riddle Hsua0536432019-02-16 00:38:59 +08006286 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale53783742018-09-16 10:21:51 -07006287 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006288 public boolean isSleeping() {
Riddle Hsua0536432019-02-16 00:38:59 +08006289 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07006290 return isSleepingLocked();
6291 }
6292 }
6293
6294 @Override
6295 public boolean isShuttingDown() {
6296 synchronized (mGlobalLock) {
6297 return mShuttingDown;
6298 }
6299 }
6300
6301 @Override
6302 public boolean shuttingDown(boolean booted, int timeout) {
6303 synchronized (mGlobalLock) {
6304 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006305 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006306 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006307 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006308 return mStackSupervisor.shutdownLocked(timeout);
6309 }
6310 }
6311
6312 @Override
6313 public void enableScreenAfterBoot(boolean booted) {
6314 synchronized (mGlobalLock) {
6315 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6316 SystemClock.uptimeMillis());
6317 mWindowManager.enableScreenAfterBoot();
6318 updateEventDispatchingLocked(booted);
6319 }
6320 }
6321
6322 @Override
6323 public boolean showStrictModeViolationDialog() {
6324 synchronized (mGlobalLock) {
6325 return mShowDialogs && !mSleeping && !mShuttingDown;
6326 }
6327 }
6328
6329 @Override
6330 public void showSystemReadyErrorDialogsIfNeeded() {
6331 synchronized (mGlobalLock) {
6332 try {
6333 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6334 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6335 + " data partition or your device will be unstable.");
6336 mUiHandler.post(() -> {
6337 if (mShowDialogs) {
6338 AlertDialog d = new BaseErrorDialog(mUiContext);
6339 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6340 d.setCancelable(false);
6341 d.setTitle(mUiContext.getText(R.string.android_system_label));
6342 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6343 d.setButton(DialogInterface.BUTTON_POSITIVE,
6344 mUiContext.getText(R.string.ok),
6345 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6346 d.show();
6347 }
6348 });
6349 }
6350 } catch (RemoteException e) {
6351 }
6352
6353 if (!Build.isBuildConsistent()) {
6354 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6355 mUiHandler.post(() -> {
6356 if (mShowDialogs) {
6357 AlertDialog d = new BaseErrorDialog(mUiContext);
6358 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6359 d.setCancelable(false);
6360 d.setTitle(mUiContext.getText(R.string.android_system_label));
6361 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6362 d.setButton(DialogInterface.BUTTON_POSITIVE,
6363 mUiContext.getText(R.string.ok),
6364 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6365 d.show();
6366 }
6367 });
6368 }
6369 }
6370 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006371
6372 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006373 public void onProcessMapped(int pid, WindowProcessController proc) {
6374 synchronized (mGlobalLock) {
6375 mPidMap.put(pid, proc);
6376 }
6377 }
6378
6379 @Override
6380 public void onProcessUnMapped(int pid) {
6381 synchronized (mGlobalLock) {
6382 mPidMap.remove(pid);
6383 }
6384 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006385
6386 @Override
6387 public void onPackageDataCleared(String name) {
6388 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006389 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006390 mAppWarnings.onPackageDataCleared(name);
6391 }
6392 }
6393
6394 @Override
6395 public void onPackageUninstalled(String name) {
6396 synchronized (mGlobalLock) {
6397 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006398 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006399 }
6400 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006401
6402 @Override
6403 public void onPackageAdded(String name, boolean replacing) {
6404 synchronized (mGlobalLock) {
6405 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6406 }
6407 }
6408
6409 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006410 public void onPackageReplaced(ApplicationInfo aInfo) {
6411 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006412 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006413 }
6414 }
6415
6416 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006417 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6418 synchronized (mGlobalLock) {
6419 return compatibilityInfoForPackageLocked(ai);
6420 }
6421 }
6422
Yunfan Chen75157d72018-07-27 14:47:21 +09006423 /**
6424 * Set the corresponding display information for the process global configuration. To be
6425 * called when we need to show IME on a different display.
6426 *
6427 * @param pid The process id associated with the IME window.
6428 * @param displayId The ID of the display showing the IME.
6429 */
6430 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006431 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006432 if (pid == MY_PID || pid < 0) {
6433 if (DEBUG_CONFIGURATION) {
6434 Slog.w(TAG,
6435 "Trying to update display configuration for system/invalid process.");
6436 }
6437 return;
6438 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006439 synchronized (mGlobalLock) {
6440 final ActivityDisplay activityDisplay =
6441 mRootActivityContainer.getActivityDisplay(displayId);
6442 if (activityDisplay == null) {
6443 // Call might come when display is not yet added or has been removed.
6444 if (DEBUG_CONFIGURATION) {
6445 Slog.w(TAG, "Trying to update display configuration for non-existing "
6446 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006447 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006448 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006449 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006450 final WindowProcessController process = mPidMap.get(pid);
6451 if (process == null) {
6452 if (DEBUG_CONFIGURATION) {
6453 Slog.w(TAG, "Trying to update display configuration for invalid "
6454 + "process, pid=" + pid);
6455 }
6456 return;
6457 }
6458 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6459 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006460 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006461
6462 @Override
6463 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6464 int requestCode, int resultCode, Intent data) {
6465 synchronized (mGlobalLock) {
6466 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006467 if (r != null && r.getActivityStack() != null) {
6468 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6469 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006470 }
6471 }
6472 }
6473
6474 @Override
6475 public void clearPendingResultForActivity(IBinder activityToken,
6476 WeakReference<PendingIntentRecord> pir) {
6477 synchronized (mGlobalLock) {
6478 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6479 if (r != null && r.pendingResults != null) {
6480 r.pendingResults.remove(pir);
6481 }
6482 }
6483 }
6484
6485 @Override
6486 public IIntentSender getIntentSender(int type, String packageName,
6487 int callingUid, int userId, IBinder token, String resultWho,
6488 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6489 Bundle bOptions) {
6490 synchronized (mGlobalLock) {
6491 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6492 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6493 }
6494 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006495
6496 @Override
6497 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6498 synchronized (mGlobalLock) {
6499 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6500 if (r == null) {
6501 return null;
6502 }
6503 if (r.mServiceConnectionsHolder == null) {
6504 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6505 ActivityTaskManagerService.this, r);
6506 }
6507
6508 return r.mServiceConnectionsHolder;
6509 }
6510 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006511
6512 @Override
6513 public Intent getHomeIntent() {
6514 synchronized (mGlobalLock) {
6515 return ActivityTaskManagerService.this.getHomeIntent();
6516 }
6517 }
6518
6519 @Override
6520 public boolean startHomeActivity(int userId, String reason) {
6521 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006522 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006523 }
6524 }
6525
6526 @Override
6527 public boolean startHomeOnAllDisplays(int userId, String reason) {
6528 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006529 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006530 }
6531 }
6532
Riddle Hsua0536432019-02-16 00:38:59 +08006533 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale214f3482018-10-04 11:00:47 -07006534 @Override
6535 public boolean isFactoryTestProcess(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006536 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07006537 if (mFactoryTest == FACTORY_TEST_OFF) {
6538 return false;
6539 }
6540 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6541 && wpc.mName.equals(mTopComponent.getPackageName())) {
6542 return true;
6543 }
6544 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6545 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6546 }
6547 }
6548
6549 @Override
6550 public void updateTopComponentForFactoryTest() {
6551 synchronized (mGlobalLock) {
6552 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6553 return;
6554 }
6555 final ResolveInfo ri = mContext.getPackageManager()
6556 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6557 final CharSequence errorMsg;
6558 if (ri != null) {
6559 final ActivityInfo ai = ri.activityInfo;
6560 final ApplicationInfo app = ai.applicationInfo;
6561 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6562 mTopAction = Intent.ACTION_FACTORY_TEST;
6563 mTopData = null;
6564 mTopComponent = new ComponentName(app.packageName, ai.name);
6565 errorMsg = null;
6566 } else {
6567 errorMsg = mContext.getResources().getText(
6568 com.android.internal.R.string.factorytest_not_system);
6569 }
6570 } else {
6571 errorMsg = mContext.getResources().getText(
6572 com.android.internal.R.string.factorytest_no_action);
6573 }
6574 if (errorMsg == null) {
6575 return;
6576 }
6577
6578 mTopAction = null;
6579 mTopData = null;
6580 mTopComponent = null;
6581 mUiHandler.post(() -> {
6582 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6583 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006584 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006585 });
6586 }
6587 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006588
Riddle Hsua0536432019-02-16 00:38:59 +08006589 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006590 @Override
6591 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6592 Runnable finishInstrumentationCallback) {
Riddle Hsua0536432019-02-16 00:38:59 +08006593 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006594 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006595 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006596
6597 wpc.clearRecentTasks();
6598 wpc.clearActivities();
6599
6600 if (wpc.isInstrumenting()) {
6601 finishInstrumentationCallback.run();
6602 }
6603
Jorim Jaggid0752812018-10-16 16:07:20 +02006604 if (!restarting && hasVisibleActivities) {
6605 mWindowManager.deferSurfaceLayout();
6606 try {
6607 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6608 // If there was nothing to resume, and we are not already restarting
6609 // this process, but there is a visible activity that is hosted by the
6610 // process...then make sure all visible activities are running, taking
6611 // care of restarting this process.
6612 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6613 !PRESERVE_WINDOWS);
6614 }
6615 } finally {
6616 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006617 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006618 }
6619 }
6620 }
6621
6622 @Override
6623 public void closeSystemDialogs(String reason) {
6624 enforceNotIsolatedCaller("closeSystemDialogs");
6625
6626 final int pid = Binder.getCallingPid();
6627 final int uid = Binder.getCallingUid();
6628 final long origId = Binder.clearCallingIdentity();
6629 try {
6630 synchronized (mGlobalLock) {
6631 // Only allow this from foreground processes, so that background
6632 // applications can't abuse it to prevent system UI from being shown.
6633 if (uid >= FIRST_APPLICATION_UID) {
6634 final WindowProcessController proc = mPidMap.get(pid);
6635 if (!proc.isPerceptible()) {
6636 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6637 + " from background process " + proc);
6638 return;
6639 }
6640 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006641 mWindowManager.closeSystemDialogs(reason);
6642
Wale Ogunwaled32da472018-11-16 07:19:28 -08006643 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006644 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006645 // Call into AM outside the synchronized block.
6646 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006647 } finally {
6648 Binder.restoreCallingIdentity(origId);
6649 }
6650 }
6651
6652 @Override
6653 public void cleanupDisabledPackageComponents(
6654 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6655 synchronized (mGlobalLock) {
6656 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006657 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006658 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006659 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006660 mStackSupervisor.scheduleIdleLocked();
6661 }
6662
6663 // Clean-up disabled tasks
6664 getRecentTasks().cleanupDisabledPackageTasksLocked(
6665 packageName, disabledClasses, userId);
6666 }
6667 }
6668
6669 @Override
6670 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6671 int userId) {
6672 synchronized (mGlobalLock) {
6673
6674 boolean didSomething =
6675 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006676 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006677 null, doit, evenPersistent, userId);
6678 return didSomething;
6679 }
6680 }
6681
6682 @Override
6683 public void resumeTopActivities(boolean scheduleIdle) {
6684 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006685 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006686 if (scheduleIdle) {
6687 mStackSupervisor.scheduleIdleLocked();
6688 }
6689 }
6690 }
6691
Riddle Hsua0536432019-02-16 00:38:59 +08006692 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006693 @Override
6694 public void preBindApplication(WindowProcessController wpc) {
Riddle Hsua0536432019-02-16 00:38:59 +08006695 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006696 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6697 }
6698 }
6699
Riddle Hsua0536432019-02-16 00:38:59 +08006700 @HotPath(caller = HotPath.PROCESS_CHANGE)
Wale Ogunwale31913b52018-10-13 08:29:31 -07006701 @Override
6702 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
Riddle Hsua0536432019-02-16 00:38:59 +08006703 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006704 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006705 }
6706 }
6707
6708 @Override
6709 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6710 try {
6711 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6712 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6713 }
6714 } catch (RemoteException ex) {
6715 throw new SecurityException("Fail to check is caller a privileged app", ex);
6716 }
6717
6718 synchronized (mGlobalLock) {
6719 final long ident = Binder.clearCallingIdentity();
6720 try {
6721 if (mAmInternal.shouldConfirmCredentials(userId)) {
6722 if (mKeyguardController.isKeyguardLocked()) {
6723 // Showing launcher to avoid user entering credential twice.
6724 startHomeActivity(currentUserId, "notifyLockedProfile");
6725 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006726 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006727 }
6728 } finally {
6729 Binder.restoreCallingIdentity(ident);
6730 }
6731 }
6732 }
6733
6734 @Override
6735 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6736 mAmInternal.enforceCallingPermission(
6737 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6738
6739 synchronized (mGlobalLock) {
6740 final long ident = Binder.clearCallingIdentity();
6741 try {
6742 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6743 FLAG_ACTIVITY_TASK_ON_HOME);
6744 ActivityOptions activityOptions = options != null
6745 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006746 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006747 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006748 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006749 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006750 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6752 UserHandle.CURRENT);
6753 } finally {
6754 Binder.restoreCallingIdentity(ident);
6755 }
6756 }
6757 }
6758
6759 @Override
6760 public void writeActivitiesToProto(ProtoOutputStream proto) {
6761 synchronized (mGlobalLock) {
6762 // The output proto of "activity --proto activities"
6763 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006764 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006765 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6766 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006767 }
6768 }
6769
6770 @Override
6771 public void saveANRState(String reason) {
6772 synchronized (mGlobalLock) {
6773 final StringWriter sw = new StringWriter();
6774 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6775 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6776 if (reason != null) {
6777 pw.println(" Reason: " + reason);
6778 }
6779 pw.println();
6780 getActivityStartController().dump(pw, " ", null);
6781 pw.println();
6782 pw.println("-------------------------------------------------------------------------------");
6783 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6784 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6785 "" /* header */);
6786 pw.println();
6787 pw.close();
6788
6789 mLastANRState = sw.toString();
6790 }
6791 }
6792
6793 @Override
6794 public void clearSavedANRState() {
6795 synchronized (mGlobalLock) {
6796 mLastANRState = null;
6797 }
6798 }
6799
6800 @Override
6801 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6802 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6803 synchronized (mGlobalLock) {
6804 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6805 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6806 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6807 dumpLastANRLocked(pw);
6808 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6809 dumpLastANRTracesLocked(pw);
6810 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6811 dumpActivityStarterLocked(pw, dumpPackage);
6812 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6813 dumpActivityContainersLocked(pw);
6814 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6815 if (getRecentTasks() != null) {
6816 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6817 }
6818 }
6819 }
6820 }
6821
6822 @Override
6823 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6824 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6825 int wakefulness) {
6826 synchronized (mGlobalLock) {
6827 if (mHomeProcess != null && (dumpPackage == null
6828 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6829 if (needSep) {
6830 pw.println();
6831 needSep = false;
6832 }
6833 pw.println(" mHomeProcess: " + mHomeProcess);
6834 }
6835 if (mPreviousProcess != null && (dumpPackage == null
6836 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6837 if (needSep) {
6838 pw.println();
6839 needSep = false;
6840 }
6841 pw.println(" mPreviousProcess: " + mPreviousProcess);
6842 }
6843 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6844 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6845 StringBuilder sb = new StringBuilder(128);
6846 sb.append(" mPreviousProcessVisibleTime: ");
6847 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6848 pw.println(sb);
6849 }
6850 if (mHeavyWeightProcess != null && (dumpPackage == null
6851 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6852 if (needSep) {
6853 pw.println();
6854 needSep = false;
6855 }
6856 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6857 }
6858 if (dumpPackage == null) {
6859 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006860 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 }
6862 if (dumpAll) {
6863 if (dumpPackage == null) {
6864 pw.println(" mConfigWillChange: "
6865 + getTopDisplayFocusedStack().mConfigWillChange);
6866 }
6867 if (mCompatModePackages.getPackages().size() > 0) {
6868 boolean printed = false;
6869 for (Map.Entry<String, Integer> entry
6870 : mCompatModePackages.getPackages().entrySet()) {
6871 String pkg = entry.getKey();
6872 int mode = entry.getValue();
6873 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6874 continue;
6875 }
6876 if (!printed) {
6877 pw.println(" mScreenCompatPackages:");
6878 printed = true;
6879 }
6880 pw.println(" " + pkg + ": " + mode);
6881 }
6882 }
6883 }
6884
6885 if (dumpPackage == null) {
6886 pw.println(" mWakefulness="
6887 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006888 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 if (mRunningVoice != null) {
6890 pw.println(" mRunningVoice=" + mRunningVoice);
6891 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6892 }
6893 pw.println(" mSleeping=" + mSleeping);
6894 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6895 pw.println(" mVrController=" + mVrController);
6896 }
6897 if (mCurAppTimeTracker != null) {
6898 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6899 }
6900 if (mAllowAppSwitchUids.size() > 0) {
6901 boolean printed = false;
6902 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6903 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6904 for (int j = 0; j < types.size(); j++) {
6905 if (dumpPackage == null ||
6906 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6907 if (needSep) {
6908 pw.println();
6909 needSep = false;
6910 }
6911 if (!printed) {
6912 pw.println(" mAllowAppSwitchUids:");
6913 printed = true;
6914 }
6915 pw.print(" User ");
6916 pw.print(mAllowAppSwitchUids.keyAt(i));
6917 pw.print(": Type ");
6918 pw.print(types.keyAt(j));
6919 pw.print(" = ");
6920 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6921 pw.println();
6922 }
6923 }
6924 }
6925 }
6926 if (dumpPackage == null) {
6927 if (mController != null) {
6928 pw.println(" mController=" + mController
6929 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6930 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006931 pw.println(" mGoingToSleepWakeLock=" + mStackSupervisor.mGoingToSleepWakeLock);
6932 pw.println(" mLaunchingActivityWakeLock="
6933 + mStackSupervisor.mLaunchingActivityWakeLock);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 }
6935
6936 return needSep;
6937 }
6938 }
6939
6940 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006941 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6942 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006943 synchronized (mGlobalLock) {
6944 if (dumpPackage == null) {
6945 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6946 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006947 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6948 if (mRunningVoice != null) {
6949 final long vrToken = proto.start(
6950 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6951 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6952 mRunningVoice.toString());
6953 mVoiceWakeLock.writeToProto(
6954 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6955 proto.end(vrToken);
6956 }
6957 mVrController.writeToProto(proto,
6958 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006959 if (mController != null) {
6960 final long token = proto.start(CONTROLLER);
6961 proto.write(CONTROLLER, mController.toString());
6962 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6963 proto.end(token);
6964 }
Andrii Kulianc598b2d2019-02-07 17:16:38 -08006965 mStackSupervisor.mGoingToSleepWakeLock.writeToProto(proto, GOING_TO_SLEEP);
6966 mStackSupervisor.mLaunchingActivityWakeLock.writeToProto(proto,
6967 LAUNCHING_ACTIVITY);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006968 }
6969
6970 if (mHomeProcess != null && (dumpPackage == null
6971 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006972 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006973 }
6974
6975 if (mPreviousProcess != null && (dumpPackage == null
6976 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006977 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006978 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6979 }
6980
6981 if (mHeavyWeightProcess != null && (dumpPackage == null
6982 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006983 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006984 }
6985
6986 for (Map.Entry<String, Integer> entry
6987 : mCompatModePackages.getPackages().entrySet()) {
6988 String pkg = entry.getKey();
6989 int mode = entry.getValue();
6990 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6991 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6992 proto.write(PACKAGE, pkg);
6993 proto.write(MODE, mode);
6994 proto.end(compatToken);
6995 }
6996 }
6997
6998 if (mCurAppTimeTracker != null) {
6999 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
7000 }
7001
7002 }
7003 }
7004
7005 @Override
7006 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
7007 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
7008 boolean dumpFocusedStackOnly) {
7009 synchronized (mGlobalLock) {
7010 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
7011 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
7012 }
7013 }
7014
7015 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007016 public void dumpForOom(PrintWriter pw) {
7017 synchronized (mGlobalLock) {
7018 pw.println(" mHomeProcess: " + mHomeProcess);
7019 pw.println(" mPreviousProcess: " + mPreviousProcess);
7020 if (mHeavyWeightProcess != null) {
7021 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
7022 }
7023 }
7024 }
7025
7026 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07007027 public boolean canGcNow() {
7028 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007029 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007030 }
7031 }
7032
Riddle Hsua0536432019-02-16 00:38:59 +08007033 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007034 @Override
7035 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007036 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007037 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007038 return top != null ? top.app : null;
7039 }
7040 }
7041
Riddle Hsua0536432019-02-16 00:38:59 +08007042 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwale31913b52018-10-13 08:29:31 -07007043 @Override
7044 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08007045 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007046 if (mRootActivityContainer != null) {
7047 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07007048 }
7049 }
7050 }
7051
7052 @Override
7053 public void scheduleDestroyAllActivities(String reason) {
7054 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007055 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007056 }
7057 }
7058
7059 @Override
7060 public void removeUser(int userId) {
7061 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007062 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007063 }
7064 }
7065
7066 @Override
7067 public boolean switchUser(int userId, UserState userState) {
7068 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007069 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007070 }
7071 }
7072
7073 @Override
7074 public void onHandleAppCrash(WindowProcessController wpc) {
7075 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007076 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07007077 }
7078 }
Wale Ogunwale64258362018-10-16 15:13:37 -07007079
7080 @Override
7081 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
7082 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08007083 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07007084 }
7085 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007086
Riddle Hsua0536432019-02-16 00:38:59 +08007087 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007088 @Override
7089 public void onUidActive(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007090 mActiveUids.onUidActive(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007091 }
7092
Riddle Hsua0536432019-02-16 00:38:59 +08007093 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007094 @Override
7095 public void onUidInactive(int uid) {
Riddle Hsua0536432019-02-16 00:38:59 +08007096 mActiveUids.onUidInactive(uid);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007097 }
7098
Riddle Hsua0536432019-02-16 00:38:59 +08007099 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007100 @Override
7101 public void onActiveUidsCleared() {
Riddle Hsua0536432019-02-16 00:38:59 +08007102 mActiveUids.onActiveUidsCleared();
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007103 }
7104
Riddle Hsua0536432019-02-16 00:38:59 +08007105 @HotPath(caller = HotPath.OOM_ADJUSTMENT)
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007106 @Override
7107 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsua0536432019-02-16 00:38:59 +08007108 mActiveUids.onUidProcStateChanged(uid, procState);
Wale Ogunwalebff2df42018-10-18 17:09:19 -07007109 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007110
7111 @Override
7112 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007113 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007114 mPendingTempWhitelist.put(uid, tag);
7115 }
7116 }
7117
7118 @Override
7119 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007120 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007121 mPendingTempWhitelist.remove(uid);
7122 }
7123 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007124
7125 @Override
7126 public boolean handleAppCrashInActivityController(String processName, int pid,
7127 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7128 Runnable killCrashingAppCallback) {
7129 synchronized (mGlobalLock) {
7130 if (mController == null) {
7131 return false;
7132 }
7133
7134 try {
7135 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7136 stackTrace)) {
7137 killCrashingAppCallback.run();
7138 return true;
7139 }
7140 } catch (RemoteException e) {
7141 mController = null;
7142 Watchdog.getInstance().setActivityController(null);
7143 }
7144 return false;
7145 }
7146 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007147
7148 @Override
7149 public void removeRecentTasksByPackageName(String packageName, int userId) {
7150 synchronized (mGlobalLock) {
7151 mRecentTasks.removeTasksByPackageName(packageName, userId);
7152 }
7153 }
7154
7155 @Override
7156 public void cleanupRecentTasksForUser(int userId) {
7157 synchronized (mGlobalLock) {
7158 mRecentTasks.cleanupLocked(userId);
7159 }
7160 }
7161
7162 @Override
7163 public void loadRecentTasksForUser(int userId) {
7164 synchronized (mGlobalLock) {
7165 mRecentTasks.loadUserRecentsLocked(userId);
7166 }
7167 }
7168
7169 @Override
7170 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7171 synchronized (mGlobalLock) {
7172 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7173 }
7174 }
7175
7176 @Override
7177 public void flushRecentTasks() {
7178 mRecentTasks.flush();
7179 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007180
7181 @Override
7182 public WindowProcessController getHomeProcess() {
7183 synchronized (mGlobalLock) {
7184 return mHomeProcess;
7185 }
7186 }
7187
7188 @Override
7189 public WindowProcessController getPreviousProcess() {
7190 synchronized (mGlobalLock) {
7191 return mPreviousProcess;
7192 }
7193 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007194
7195 @Override
7196 public void clearLockedTasks(String reason) {
7197 synchronized (mGlobalLock) {
7198 getLockTaskController().clearLockedTasks(reason);
7199 }
7200 }
7201
7202 @Override
7203 public void updateUserConfiguration() {
7204 synchronized (mGlobalLock) {
7205 final Configuration configuration = new Configuration(getGlobalConfiguration());
7206 final int currentUserId = mAmInternal.getCurrentUserId();
7207 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7208 configuration, currentUserId, Settings.System.canWrite(mContext));
7209 updateConfigurationLocked(configuration, null /* starting */,
7210 false /* initLocale */, false /* persistent */, currentUserId,
7211 false /* deferResume */);
7212 }
7213 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007214
7215 @Override
7216 public boolean canShowErrorDialogs() {
7217 synchronized (mGlobalLock) {
7218 return mShowDialogs && !mSleeping && !mShuttingDown
7219 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7220 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7221 mAmInternal.getCurrentUserId())
7222 && !(UserManager.isDeviceInDemoMode(mContext)
7223 && mAmInternal.getCurrentUser().isDemo());
7224 }
7225 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007226
7227 @Override
7228 public void setProfileApp(String profileApp) {
7229 synchronized (mGlobalLock) {
7230 mProfileApp = profileApp;
7231 }
7232 }
7233
7234 @Override
7235 public void setProfileProc(WindowProcessController wpc) {
7236 synchronized (mGlobalLock) {
7237 mProfileProc = wpc;
7238 }
7239 }
7240
7241 @Override
7242 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7243 synchronized (mGlobalLock) {
7244 mProfilerInfo = profilerInfo;
7245 }
7246 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007247
7248 @Override
7249 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7250 synchronized (mGlobalLock) {
7251 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7252 }
7253 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007254
7255 @Override
7256 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7257 synchronized (mGlobalLock) {
7258 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7259 }
7260 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007261
7262 @Override
7263 public boolean isUidForeground(int uid) {
7264 synchronized (mGlobalLock) {
7265 return ActivityTaskManagerService.this.isUidForeground(uid);
7266 }
7267 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007268
7269 @Override
7270 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7271 synchronized (mGlobalLock) {
7272 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7273 }
7274 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007275 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007276}