blob: d8bc3bc0a2fffff14283a940164b97fe36d5ebc8 [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;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Wale Ogunwale59507092018-10-29 09:00:30 -070085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto
86 .PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Wale Ogunwale59507092018-10-29 09:00:30 -070088import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
89 .MODE;
90import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
91 .PACKAGE;
92import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
93import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
94import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
95import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
96import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
97import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
98import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
112import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
113import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
114import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
115import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
116import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700117import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
118import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
119import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
120import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800121import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
122import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700123import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
124import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
wilsonshihe7903ea2018-09-26 16:17:59 +0800125import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
126import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
127import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700128
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700130import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700131import android.annotation.Nullable;
132import android.annotation.UserIdInt;
133import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700134import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700135import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700136import android.app.ActivityOptions;
137import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700138import android.app.ActivityThread;
139import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700140import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700141import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700142import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700143import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.IApplicationThread;
145import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700146import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700148import android.app.Notification;
149import android.app.NotificationManager;
150import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700151import android.app.PictureInPictureParams;
152import android.app.ProfilerInfo;
153import android.app.RemoteAction;
154import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700155import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700156import android.app.admin.DevicePolicyCache;
157import android.app.assist.AssistContent;
158import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700159import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700160import android.content.ActivityNotFoundException;
161import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700162import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700163import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700164import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700165import android.content.IIntentSender;
166import android.content.Intent;
167import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700168import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900169import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700170import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700171import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700172import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.pm.ParceledListSlice;
174import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700175import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700177import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700178import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.graphics.Bitmap;
180import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.metrics.LogMaker;
183import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700186import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700187import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700189import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700190import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700191import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700192import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700193import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700194import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700195import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700196import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700197import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700198import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700199import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700200import android.os.SystemClock;
201import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700203import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700204import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700205import android.os.UserManager;
206import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700207import android.os.storage.IStorageManager;
208import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700209import android.provider.Settings;
210import android.service.voice.IVoiceInteractionSession;
211import android.service.voice.VoiceInteractionManagerInternal;
212import android.telecom.TelecomManager;
213import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700214import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700215import android.util.ArrayMap;
216import android.util.EventLog;
217import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700218import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700220import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700221import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700222import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700223import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700224import android.view.IRecentsAnimationRunner;
225import android.view.RemoteAnimationAdapter;
226import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700227import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700228
Evan Rosky4505b352018-09-06 11:20:40 -0700229import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700230import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700231import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700232import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700233import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700234import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700236import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700237import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
238import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700239import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700240import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700241import com.android.internal.policy.IKeyguardDismissCallback;
242import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.util.ArrayUtils;
244import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700245import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700246import com.android.internal.util.function.pooled.PooledLambda;
Evan Rosky4505b352018-09-06 11:20:40 -0700247import com.android.server.AppOpsService;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700248import com.android.server.AttributeCache;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800249import com.android.server.DisplayThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700250import com.android.server.LocalServices;
251import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700252import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800253import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700254import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700255import com.android.server.am.ActivityManagerService;
256import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
257import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
258import com.android.server.am.AppTimeTracker;
259import com.android.server.am.BaseErrorDialog;
260import com.android.server.am.EventLogTags;
261import com.android.server.am.PendingIntentController;
262import com.android.server.am.PendingIntentRecord;
263import com.android.server.am.UserState;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700264import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700265import com.android.server.pm.UserManagerService;
266import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700267import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700270import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700273import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700274import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700275import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700276import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700277import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700278import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700279import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700280import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400282import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700283import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700284import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700285import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700286import java.util.Map;
287import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700288
289/**
290 * System service for managing activities and their containers (task, stacks, displays,... ).
291 *
292 * {@hide}
293 */
294public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700295 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700296 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700297 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
298 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
299 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
300 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
301 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700302 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700303
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700307 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700308
Wale Ogunwale98875612018-10-12 07:53:02 -0700309 /** Used to indicate that an app transition should be animated. */
310 static final boolean ANIMATE = true;
311
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700312 /** Hardware-reported OpenGLES version. */
313 final int GL_ES_VERSION;
314
Wale Ogunwale31913b52018-10-13 08:29:31 -0700315 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
316 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
317 public static final String DUMP_LASTANR_CMD = "lastanr" ;
318 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
319 public static final String DUMP_STARTER_CMD = "starter" ;
320 public static final String DUMP_CONTAINERS_CMD = "containers" ;
321 public static final String DUMP_RECENTS_CMD = "recents" ;
322 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
323
Wale Ogunwale64258362018-10-16 15:13:37 -0700324 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
325 public static final int RELAUNCH_REASON_NONE = 0;
326 /** This activity is being relaunched due to windowing mode change. */
327 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
328 /** This activity is being relaunched due to a free-resize operation. */
329 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
330
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700331 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700332
Wale Ogunwalef6733932018-06-27 05:14:34 -0700333 /**
334 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
335 * change at runtime. Use mContext for non-UI purposes.
336 */
337 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700338 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700339 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700341 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700342 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700343 private PackageManagerInternal mPmInternal;
Wale Ogunwale38f72bd2018-11-20 02:53:49 +0000344 private ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700345 PowerManagerInternal mPowerManagerInternal;
346 private UsageStatsManagerInternal mUsageStatsInternal;
347
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700348 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700349 IntentFirewall mIntentFirewall;
350
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700351 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800352 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700353 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700355 private UserManagerService mUserManager;
356 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700357 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700358 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
359 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700360 /** All processes currently running that might have a window organized by name. */
361 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700362 /** All processes we currently have running mapped by pid */
363 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700364 /** This is the process holding what we currently consider to be the "home" activity. */
365 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700366 /** The currently running heavy-weight process, if any. */
367 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700368 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700369 /**
370 * This is the process holding the activity the user last visited that is in a different process
371 * from the one they are currently in.
372 */
373 WindowProcessController mPreviousProcess;
374 /** The time at which the previous process was last visible. */
375 long mPreviousProcessVisibleTime;
376
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 /** List of intents that were used to start the most recent tasks. */
378 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700379 /** State of external calls telling us if the device is awake or asleep. */
380 private boolean mKeyguardShown = false;
381
382 // Wrapper around VoiceInteractionServiceManager
383 private AssistUtils mAssistUtils;
384
385 // VoiceInteraction session ID that changes for each new request except when
386 // being called for multi-window assist in a single session.
387 private int mViSessionId = 1000;
388
389 // How long to wait in getAssistContextExtras for the activity and foreground services
390 // to respond with the result.
391 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
392
393 // How long top wait when going through the modern assist (which doesn't need to block
394 // on getting this result before starting to launch its UI).
395 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
396
397 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
398 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
399
Alison Cichowlas3e340502018-08-07 17:15:01 -0400400 // Permission tokens are used to temporarily granted a trusted app the ability to call
401 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
402 // showing any appropriate error messages to the user.
403 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
404 10 * MINUTE_IN_MILLIS;
405
406 // How long before the service actually expires a token. This is slightly longer than
407 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
408 // expiration exception.
409 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
410 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
411
412 // How long the service will remember expired tokens, for the purpose of providing error
413 // messaging when a client uses an expired token.
414 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
415 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
416
417 // Activity tokens of system activities that are delegating their call to
418 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
419 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
420
421 // Permission tokens that have expired, but we remember for error reporting.
422 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700424 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
425
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700426 // Keeps track of the active voice interaction service component, notified from
427 // VoiceInteractionManagerService
428 ComponentName mActiveVoiceInteractionServiceComponent;
429
Wale Ogunwalee2172292018-10-25 10:11:10 -0700430 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700431 KeyguardController mKeyguardController;
432 private final ClientLifecycleManager mLifecycleManager;
433 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700434 /** The controller for all operations related to locktask. */
435 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700436 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700437
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700438 boolean mSuppressResizeConfigChanges;
439
440 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
441 new UpdateConfigurationResult();
442
443 static final class UpdateConfigurationResult {
444 // Configuration changes that were updated.
445 int changes;
446 // If the activity was relaunched to match the new configuration.
447 boolean activityRelaunched;
448
449 void reset() {
450 changes = 0;
451 activityRelaunched = false;
452 }
453 }
454
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700455 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700456 private int mConfigurationSeq;
457 // To cache the list of supported system locales
458 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700459
460 /**
461 * Temp object used when global and/or display override configuration is updated. It is also
462 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
463 * anyone...
464 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700465 private Configuration mTempConfig = new Configuration();
466
Wale Ogunwalef6733932018-06-27 05:14:34 -0700467 /** Temporary to avoid allocations. */
468 final StringBuilder mStringBuilder = new StringBuilder(256);
469
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700470 // Amount of time after a call to stopAppSwitches() during which we will
471 // prevent further untrusted switches from happening.
472 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
473
474 /**
475 * The time at which we will allow normal application switches again,
476 * after a call to {@link #stopAppSwitches()}.
477 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700478 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 /**
480 * This is set to true after the first switch after mAppSwitchesAllowedTime
481 * is set; any switches after that will clear the time.
482 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700483 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484
485 IActivityController mController = null;
486 boolean mControllerIsAMonkey = false;
487
Wale Ogunwale214f3482018-10-04 11:00:47 -0700488 final int mFactoryTest;
489
490 /** Used to control how we initialize the service. */
491 ComponentName mTopComponent;
492 String mTopAction = Intent.ACTION_MAIN;
493 String mTopData;
494
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800495 /** Profiling app information. */
496 String mProfileApp = null;
497 WindowProcessController mProfileProc = null;
498 ProfilerInfo mProfilerInfo = null;
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700501 * Dump of the activity state at the time of the last ANR. Cleared after
502 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
503 */
504 String mLastANRState;
505
506 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 * Used to retain an update lock when the foreground activity is in
508 * immersive mode.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
512 /**
513 * Packages that are being allowed to perform unrestricted app switches. Mapping is
514 * User -> Type -> uid.
515 */
516 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
517
518 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700519 private int mThumbnailWidth;
520 private int mThumbnailHeight;
521 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522
523 /**
524 * Flag that indicates if multi-window is enabled.
525 *
526 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
527 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
528 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
529 * At least one of the forms of multi-window must be enabled in order for this flag to be
530 * initialized to 'true'.
531 *
532 * @see #mSupportsSplitScreenMultiWindow
533 * @see #mSupportsFreeformWindowManagement
534 * @see #mSupportsPictureInPicture
535 * @see #mSupportsMultiDisplay
536 */
537 boolean mSupportsMultiWindow;
538 boolean mSupportsSplitScreenMultiWindow;
539 boolean mSupportsFreeformWindowManagement;
540 boolean mSupportsPictureInPicture;
541 boolean mSupportsMultiDisplay;
542 boolean mForceResizableActivities;
543
544 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
545
546 // VR Vr2d Display Id.
547 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700548
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 /**
550 * Set while we are wanting to sleep, to prevent any
551 * activities from being started/resumed.
552 *
553 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
554 *
555 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
556 * while in the sleep state until there is a pending transition out of sleep, in which case
557 * mSleeping is set to false, and remains false while awake.
558 *
559 * Whether mSleeping can quickly toggled between true/false without the device actually
560 * display changing states is undefined.
561 */
562 private boolean mSleeping = false;
563
564 /**
565 * The process state used for processes that are running the top activities.
566 * This changes between TOP and TOP_SLEEPING to following mSleeping.
567 */
568 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
569
570 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
571 // automatically. Important for devices without direct input devices.
572 private boolean mShowDialogs = true;
573
574 /** Set if we are shutting down the system, similar to sleeping. */
575 boolean mShuttingDown = false;
576
577 /**
578 * We want to hold a wake lock while running a voice interaction session, since
579 * this may happen with the screen off and we need to keep the CPU running to
580 * be able to continue to interact with the user.
581 */
582 PowerManager.WakeLock mVoiceWakeLock;
583
584 /**
585 * Set while we are running a voice interaction. This overrides sleeping while it is active.
586 */
587 IVoiceInteractionSession mRunningVoice;
588
589 /**
590 * The last resumed activity. This is identical to the current resumed activity most
591 * of the time but could be different when we're pausing one activity before we resume
592 * another activity.
593 */
594 ActivityRecord mLastResumedActivity;
595
596 /**
597 * The activity that is currently being traced as the active resumed activity.
598 *
599 * @see #updateResumedAppTrace
600 */
601 private @Nullable ActivityRecord mTracedResumedActivity;
602
603 /** If non-null, we are tracking the time the user spends in the currently focused app. */
604 AppTimeTracker mCurAppTimeTracker;
605
Wale Ogunwale008163e2018-07-23 23:11:08 -0700606 private AppWarnings mAppWarnings;
607
Wale Ogunwale53783742018-09-16 10:21:51 -0700608 /**
609 * Packages that the user has asked to have run in screen size
610 * compatibility mode instead of filling the screen.
611 */
612 CompatModePackages mCompatModePackages;
613
Wale Ogunwalef6733932018-06-27 05:14:34 -0700614 private FontScaleSettingObserver mFontScaleSettingObserver;
615
616 private final class FontScaleSettingObserver extends ContentObserver {
617 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
618 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
619
620 public FontScaleSettingObserver() {
621 super(mH);
622 final ContentResolver resolver = mContext.getContentResolver();
623 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
624 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
625 UserHandle.USER_ALL);
626 }
627
628 @Override
629 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
630 if (mFontScaleUri.equals(uri)) {
631 updateFontScaleIfNeeded(userId);
632 } else if (mHideErrorDialogsUri.equals(uri)) {
633 synchronized (mGlobalLock) {
634 updateShouldShowDialogsLocked(getGlobalConfiguration());
635 }
636 }
637 }
638 }
639
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700640 ActivityTaskManagerService(Context context) {
641 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700642 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700643 mSystemThread = ActivityThread.currentActivityThread();
644 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700645 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700646 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700647 }
648
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700649 public void onSystemReady() {
650 synchronized (mGlobalLock) {
651 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
652 PackageManager.FEATURE_CANT_SAVE_STATE);
653 mAssistUtils = new AssistUtils(mContext);
654 mVrController.onSystemReady();
655 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700656 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700657 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700658 }
659
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700660 public void onInitPowerManagement() {
661 synchronized (mGlobalLock) {
662 mStackSupervisor.initPowerManagement();
663 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
664 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
665 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
666 mVoiceWakeLock.setReferenceCounted(false);
667 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700668 }
669
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700670 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700671 mFontScaleSettingObserver = new FontScaleSettingObserver();
672 }
673
Wale Ogunwale59507092018-10-29 09:00:30 -0700674 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700675 final boolean freeformWindowManagement =
676 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
677 || Settings.Global.getInt(
678 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
679
680 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
681 final boolean supportsPictureInPicture = supportsMultiWindow &&
682 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
683 final boolean supportsSplitScreenMultiWindow =
684 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
685 final boolean supportsMultiDisplay = mContext.getPackageManager()
686 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700687 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
688 final boolean forceResizable = Settings.Global.getInt(
689 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700690 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700691
692 // Transfer any global setting for forcing RTL layout, into a System Property
693 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
694
695 final Configuration configuration = new Configuration();
696 Settings.System.getConfiguration(resolver, configuration);
697 if (forceRtl) {
698 // This will take care of setting the correct layout direction flags
699 configuration.setLayoutDirection(configuration.locale);
700 }
701
702 synchronized (mGlobalLock) {
703 mForceResizableActivities = forceResizable;
704 final boolean multiWindowFormEnabled = freeformWindowManagement
705 || supportsSplitScreenMultiWindow
706 || supportsPictureInPicture
707 || supportsMultiDisplay;
708 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
709 mSupportsMultiWindow = true;
710 mSupportsFreeformWindowManagement = freeformWindowManagement;
711 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
712 mSupportsPictureInPicture = supportsPictureInPicture;
713 mSupportsMultiDisplay = supportsMultiDisplay;
714 } else {
715 mSupportsMultiWindow = false;
716 mSupportsFreeformWindowManagement = false;
717 mSupportsSplitScreenMultiWindow = false;
718 mSupportsPictureInPicture = false;
719 mSupportsMultiDisplay = false;
720 }
721 mWindowManager.setForceResizableTasks(mForceResizableActivities);
722 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700723 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
724 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700725 // This happens before any activities are started, so we can change global configuration
726 // in-place.
727 updateConfigurationLocked(configuration, null, true);
728 final Configuration globalConfig = getGlobalConfiguration();
729 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
730
731 // Load resources only after the current configuration has been set.
732 final Resources res = mContext.getResources();
733 mThumbnailWidth = res.getDimensionPixelSize(
734 com.android.internal.R.dimen.thumbnail_width);
735 mThumbnailHeight = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_height);
737
738 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
739 mFullscreenThumbnailScale = (float) res
740 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
741 (float) globalConfig.screenWidthDp;
742 } else {
743 mFullscreenThumbnailScale = res.getFraction(
744 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
745 }
746 }
747 }
748
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800749 public WindowManagerGlobalLock getGlobalLock() {
750 return mGlobalLock;
751 }
752
753 public void setActivityManagerService(IntentFirewall intentFirewall,
754 PendingIntentController intentController) {
755 mH = new H();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700756 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700757 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700758 final File systemDir = SystemServiceManager.ensureSystemDir();
759 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
760 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700761 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700762
763 mTempConfig.setToDefaults();
764 mTempConfig.setLocales(LocaleList.getDefault());
765 mConfigurationSeq = mTempConfig.seq = 1;
766 mStackSupervisor = createStackSupervisor();
767 mStackSupervisor.onConfigurationChanged(mTempConfig);
768
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700769 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700770 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700771 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700772 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700773 mRecentTasks = createRecentTasks();
774 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700775 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700776 mKeyguardController = mStackSupervisor.getKeyguardController();
777 }
778
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700779 public void onActivityManagerInternalAdded() {
780 synchronized (mGlobalLock) {
781 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
782 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
783 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700784 }
785
Yunfan Chen75157d72018-07-27 14:47:21 +0900786 int increaseConfigurationSeqLocked() {
787 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
788 return mConfigurationSeq;
789 }
790
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700791 protected ActivityStackSupervisor createStackSupervisor() {
792 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
793 supervisor.initialize();
794 return supervisor;
795 }
796
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700797 public void setWindowManager(WindowManagerService wm) {
798 synchronized (mGlobalLock) {
799 mWindowManager = wm;
800 mLockTaskController.setWindowManager(wm);
801 mStackSupervisor.setWindowManager(wm);
802 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700803 }
804
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700805 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
806 synchronized (mGlobalLock) {
807 mUsageStatsInternal = usageStatsManager;
808 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700809 }
810
Wale Ogunwalef6733932018-06-27 05:14:34 -0700811 UserManagerService getUserManager() {
812 if (mUserManager == null) {
813 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
814 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
815 }
816 return mUserManager;
817 }
818
819 AppOpsService getAppOpsService() {
820 if (mAppOpsService == null) {
821 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
822 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
823 }
824 return mAppOpsService;
825 }
826
827 boolean hasUserRestriction(String restriction, int userId) {
828 return getUserManager().hasUserRestriction(restriction, userId);
829 }
830
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700831 protected RecentTasks createRecentTasks() {
832 return new RecentTasks(this, mStackSupervisor);
833 }
834
835 RecentTasks getRecentTasks() {
836 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700837 }
838
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700839 ClientLifecycleManager getLifecycleManager() {
840 return mLifecycleManager;
841 }
842
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700843 ActivityStartController getActivityStartController() {
844 return mActivityStartController;
845 }
846
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700847 TaskChangeNotificationController getTaskChangeNotificationController() {
848 return mTaskChangeNotificationController;
849 }
850
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700851 LockTaskController getLockTaskController() {
852 return mLockTaskController;
853 }
854
Yunfan Chen75157d72018-07-27 14:47:21 +0900855 /**
856 * Return the global configuration used by the process corresponding to the input pid. This is
857 * usually the global configuration with some overrides specific to that process.
858 */
859 Configuration getGlobalConfigurationForCallingPid() {
860 final int pid = Binder.getCallingPid();
861 if (pid == MY_PID || pid < 0) {
862 return getGlobalConfiguration();
863 }
864 synchronized (mGlobalLock) {
865 final WindowProcessController app = mPidMap.get(pid);
866 return app != null ? app.getConfiguration() : getGlobalConfiguration();
867 }
868 }
869
870 /**
871 * Return the device configuration info used by the process corresponding to the input pid.
872 * The value is consistent with the global configuration for the process.
873 */
874 @Override
875 public ConfigurationInfo getDeviceConfigurationInfo() {
876 ConfigurationInfo config = new ConfigurationInfo();
877 synchronized (mGlobalLock) {
878 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
879 config.reqTouchScreen = globalConfig.touchscreen;
880 config.reqKeyboardType = globalConfig.keyboard;
881 config.reqNavigation = globalConfig.navigation;
882 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
883 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
884 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
885 }
886 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
887 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
888 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
889 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700890 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900891 }
892 return config;
893 }
894
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700895 private void start() {
Wale Ogunwale38f72bd2018-11-20 02:53:49 +0000896 mInternal = new LocalService();
Wale Ogunwale53783742018-09-16 10:21:51 -0700897 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700898 }
899
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700900 public static final class Lifecycle extends SystemService {
901 private final ActivityTaskManagerService mService;
902
903 public Lifecycle(Context context) {
904 super(context);
905 mService = new ActivityTaskManagerService(context);
906 }
907
908 @Override
909 public void onStart() {
910 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700911 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700912 }
913
Garfield Tan891146c2018-10-09 12:14:00 -0700914 @Override
915 public void onUnlockUser(int userId) {
916 synchronized (mService.getGlobalLock()) {
917 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
918 }
919 }
920
921 @Override
922 public void onCleanupUser(int userId) {
923 synchronized (mService.getGlobalLock()) {
924 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
925 }
926 }
927
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700928 public ActivityTaskManagerService getService() {
929 return mService;
930 }
931 }
932
933 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700934 public final int startActivity(IApplicationThread caller, String callingPackage,
935 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
936 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
937 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
938 resultWho, requestCode, startFlags, profilerInfo, bOptions,
939 UserHandle.getCallingUserId());
940 }
941
942 @Override
943 public final int startActivities(IApplicationThread caller, String callingPackage,
944 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
945 int userId) {
946 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700947 enforceNotIsolatedCaller(reason);
948 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700949 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700950 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100951 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
952 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700953 }
954
955 @Override
956 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
957 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
958 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
959 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
960 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
961 true /*validateIncomingUser*/);
962 }
963
964 int startActivityAsUser(IApplicationThread caller, String callingPackage,
965 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
966 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
967 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700968 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700969
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700970 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700971 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
972
973 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700974 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700975 .setCaller(caller)
976 .setCallingPackage(callingPackage)
977 .setResolvedType(resolvedType)
978 .setResultTo(resultTo)
979 .setResultWho(resultWho)
980 .setRequestCode(requestCode)
981 .setStartFlags(startFlags)
982 .setProfilerInfo(profilerInfo)
983 .setActivityOptions(bOptions)
984 .setMayWait(userId)
985 .execute();
986
987 }
988
989 @Override
990 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
991 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700992 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
993 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700994 // Refuse possible leaked file descriptors
995 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
996 throw new IllegalArgumentException("File descriptors passed in Intent");
997 }
998
999 if (!(target instanceof PendingIntentRecord)) {
1000 throw new IllegalArgumentException("Bad PendingIntent object");
1001 }
1002
1003 PendingIntentRecord pir = (PendingIntentRecord)target;
1004
1005 synchronized (mGlobalLock) {
1006 // If this is coming from the currently resumed activity, it is
1007 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001008 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001009 if (stack.mResumedActivity != null &&
1010 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001011 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001012 }
1013 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001014 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 }
1017
1018 @Override
1019 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1020 Bundle bOptions) {
1021 // Refuse possible leaked file descriptors
1022 if (intent != null && intent.hasFileDescriptors()) {
1023 throw new IllegalArgumentException("File descriptors passed in Intent");
1024 }
1025 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1026
1027 synchronized (mGlobalLock) {
1028 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1029 if (r == null) {
1030 SafeActivityOptions.abort(options);
1031 return false;
1032 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001033 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001034 // The caller is not running... d'oh!
1035 SafeActivityOptions.abort(options);
1036 return false;
1037 }
1038 intent = new Intent(intent);
1039 // The caller is not allowed to change the data.
1040 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1041 // And we are resetting to find the next component...
1042 intent.setComponent(null);
1043
1044 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1045
1046 ActivityInfo aInfo = null;
1047 try {
1048 List<ResolveInfo> resolves =
1049 AppGlobals.getPackageManager().queryIntentActivities(
1050 intent, r.resolvedType,
1051 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1052 UserHandle.getCallingUserId()).getList();
1053
1054 // Look for the original activity in the list...
1055 final int N = resolves != null ? resolves.size() : 0;
1056 for (int i=0; i<N; i++) {
1057 ResolveInfo rInfo = resolves.get(i);
1058 if (rInfo.activityInfo.packageName.equals(r.packageName)
1059 && rInfo.activityInfo.name.equals(r.info.name)) {
1060 // We found the current one... the next matching is
1061 // after it.
1062 i++;
1063 if (i<N) {
1064 aInfo = resolves.get(i).activityInfo;
1065 }
1066 if (debug) {
1067 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1068 + "/" + r.info.name);
1069 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1070 ? "null" : aInfo.packageName + "/" + aInfo.name));
1071 }
1072 break;
1073 }
1074 }
1075 } catch (RemoteException e) {
1076 }
1077
1078 if (aInfo == null) {
1079 // Nobody who is next!
1080 SafeActivityOptions.abort(options);
1081 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1082 return false;
1083 }
1084
1085 intent.setComponent(new ComponentName(
1086 aInfo.applicationInfo.packageName, aInfo.name));
1087 intent.setFlags(intent.getFlags()&~(
1088 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1089 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1090 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1091 FLAG_ACTIVITY_NEW_TASK));
1092
1093 // Okay now we need to start the new activity, replacing the currently running activity.
1094 // This is a little tricky because we want to start the new one as if the current one is
1095 // finished, but not finish the current one first so that there is no flicker.
1096 // And thus...
1097 final boolean wasFinishing = r.finishing;
1098 r.finishing = true;
1099
1100 // Propagate reply information over to the new activity.
1101 final ActivityRecord resultTo = r.resultTo;
1102 final String resultWho = r.resultWho;
1103 final int requestCode = r.requestCode;
1104 r.resultTo = null;
1105 if (resultTo != null) {
1106 resultTo.removeResultsLocked(r, resultWho, requestCode);
1107 }
1108
1109 final long origId = Binder.clearCallingIdentity();
1110 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001111 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001112 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001113 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001114 .setResolvedType(r.resolvedType)
1115 .setActivityInfo(aInfo)
1116 .setResultTo(resultTo != null ? resultTo.appToken : null)
1117 .setResultWho(resultWho)
1118 .setRequestCode(requestCode)
1119 .setCallingPid(-1)
1120 .setCallingUid(r.launchedFromUid)
1121 .setCallingPackage(r.launchedFromPackage)
1122 .setRealCallingPid(-1)
1123 .setRealCallingUid(r.launchedFromUid)
1124 .setActivityOptions(options)
1125 .execute();
1126 Binder.restoreCallingIdentity(origId);
1127
1128 r.finishing = wasFinishing;
1129 if (res != ActivityManager.START_SUCCESS) {
1130 return false;
1131 }
1132 return true;
1133 }
1134 }
1135
1136 @Override
1137 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1138 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1139 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1140 final WaitResult res = new WaitResult();
1141 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001142 enforceNotIsolatedCaller("startActivityAndWait");
1143 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1144 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001145 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001146 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001147 .setCaller(caller)
1148 .setCallingPackage(callingPackage)
1149 .setResolvedType(resolvedType)
1150 .setResultTo(resultTo)
1151 .setResultWho(resultWho)
1152 .setRequestCode(requestCode)
1153 .setStartFlags(startFlags)
1154 .setActivityOptions(bOptions)
1155 .setMayWait(userId)
1156 .setProfilerInfo(profilerInfo)
1157 .setWaitResult(res)
1158 .execute();
1159 }
1160 return res;
1161 }
1162
1163 @Override
1164 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1165 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1166 int startFlags, Configuration config, Bundle bOptions, int userId) {
1167 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001168 enforceNotIsolatedCaller("startActivityWithConfig");
1169 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1170 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001171 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001172 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001173 .setCaller(caller)
1174 .setCallingPackage(callingPackage)
1175 .setResolvedType(resolvedType)
1176 .setResultTo(resultTo)
1177 .setResultWho(resultWho)
1178 .setRequestCode(requestCode)
1179 .setStartFlags(startFlags)
1180 .setGlobalConfiguration(config)
1181 .setActivityOptions(bOptions)
1182 .setMayWait(userId)
1183 .execute();
1184 }
1185 }
1186
Alison Cichowlas3e340502018-08-07 17:15:01 -04001187
1188 @Override
1189 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1190 int callingUid = Binder.getCallingUid();
1191 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1192 throw new SecurityException("Only the system process can request a permission token, "
1193 + "received request from uid: " + callingUid);
1194 }
1195 IBinder permissionToken = new Binder();
1196 synchronized (mGlobalLock) {
1197 mStartActivitySources.put(permissionToken, delegatorToken);
1198 }
1199
1200 Message expireMsg = PooledLambda.obtainMessage(
1201 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1202 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1203
1204 Message forgetMsg = PooledLambda.obtainMessage(
1205 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1206 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1207
1208 return permissionToken;
1209 }
1210
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001211 @Override
1212 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1213 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001214 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1215 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001216 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001217 // permission grants) as any app that may launch one of your own activities. So we only
1218 // allow this in two cases:
1219 // 1) The caller is an activity that is part of the core framework, and then only when it
1220 // is running as the system.
1221 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1222 // can only be requested by a system activity, which may then delegate this call to
1223 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001224 final ActivityRecord sourceRecord;
1225 final int targetUid;
1226 final String targetPackage;
1227 final boolean isResolver;
1228 synchronized (mGlobalLock) {
1229 if (resultTo == null) {
1230 throw new SecurityException("Must be called from an activity");
1231 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001232 final IBinder sourceToken;
1233 if (permissionToken != null) {
1234 // To even attempt to use a permissionToken, an app must also have this signature
1235 // permission.
1236 mAmInternal.enforceCallingPermission(
1237 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1238 "startActivityAsCaller");
1239 // If called with a permissionToken, we want the sourceRecord from the delegator
1240 // activity that requested this token.
1241 sourceToken = mStartActivitySources.remove(permissionToken);
1242 if (sourceToken == null) {
1243 // Invalid permissionToken, check if it recently expired.
1244 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1245 throw new SecurityException("Called with expired permission token: "
1246 + permissionToken);
1247 } else {
1248 throw new SecurityException("Called with invalid permission token: "
1249 + permissionToken);
1250 }
1251 }
1252 } else {
1253 // This method was called directly by the source.
1254 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001255 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001256
1257 sourceRecord = mStackSupervisor.isInAnyStackLocked(sourceToken);
1258 if (sourceRecord == null) {
1259 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001260 }
1261 if (sourceRecord.app == null) {
1262 throw new SecurityException("Called without a process attached to activity");
1263 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001264
1265 // Whether called directly or from a delegate, the source activity must be from the
1266 // android package.
1267 if (!sourceRecord.info.packageName.equals("android")) {
1268 throw new SecurityException("Must be called from an activity that is "
1269 + "declared in the android package");
1270 }
1271
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001272 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001273 // This is still okay, as long as this activity is running under the
1274 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001275 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001277 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001278 + " must be system uid or original calling uid "
1279 + sourceRecord.launchedFromUid);
1280 }
1281 }
1282 if (ignoreTargetSecurity) {
1283 if (intent.getComponent() == null) {
1284 throw new SecurityException(
1285 "Component must be specified with ignoreTargetSecurity");
1286 }
1287 if (intent.getSelector() != null) {
1288 throw new SecurityException(
1289 "Selector not allowed with ignoreTargetSecurity");
1290 }
1291 }
1292 targetUid = sourceRecord.launchedFromUid;
1293 targetPackage = sourceRecord.launchedFromPackage;
1294 isResolver = sourceRecord.isResolverOrChildActivity();
1295 }
1296
1297 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001298 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 }
1300
1301 // TODO: Switch to user app stacks here.
1302 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001303 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001304 .setCallingUid(targetUid)
1305 .setCallingPackage(targetPackage)
1306 .setResolvedType(resolvedType)
1307 .setResultTo(resultTo)
1308 .setResultWho(resultWho)
1309 .setRequestCode(requestCode)
1310 .setStartFlags(startFlags)
1311 .setActivityOptions(bOptions)
1312 .setMayWait(userId)
1313 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1314 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1315 .execute();
1316 } catch (SecurityException e) {
1317 // XXX need to figure out how to propagate to original app.
1318 // A SecurityException here is generally actually a fault of the original
1319 // calling activity (such as a fairly granting permissions), so propagate it
1320 // back to them.
1321 /*
1322 StringBuilder msg = new StringBuilder();
1323 msg.append("While launching");
1324 msg.append(intent.toString());
1325 msg.append(": ");
1326 msg.append(e.getMessage());
1327 */
1328 throw e;
1329 }
1330 }
1331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001332 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1333 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1334 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1335 }
1336
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001337 @Override
1338 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1339 Intent intent, String resolvedType, IVoiceInteractionSession session,
1340 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1341 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001342 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001343 if (session == null || interactor == null) {
1344 throw new NullPointerException("null session or interactor");
1345 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001346 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001348 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001349 .setCallingUid(callingUid)
1350 .setCallingPackage(callingPackage)
1351 .setResolvedType(resolvedType)
1352 .setVoiceSession(session)
1353 .setVoiceInteractor(interactor)
1354 .setStartFlags(startFlags)
1355 .setProfilerInfo(profilerInfo)
1356 .setActivityOptions(bOptions)
1357 .setMayWait(userId)
1358 .execute();
1359 }
1360
1361 @Override
1362 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1363 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001364 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1365 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001366
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001367 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 .setCallingUid(callingUid)
1369 .setCallingPackage(callingPackage)
1370 .setResolvedType(resolvedType)
1371 .setActivityOptions(bOptions)
1372 .setMayWait(userId)
1373 .execute();
1374 }
1375
1376 @Override
1377 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1378 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001379 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 final int callingPid = Binder.getCallingPid();
1381 final long origId = Binder.clearCallingIdentity();
1382 try {
1383 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001384 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1385 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001386
1387 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001388 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1389 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1391 recentsUid, assistDataReceiver);
1392 }
1393 } finally {
1394 Binder.restoreCallingIdentity(origId);
1395 }
1396 }
1397
1398 @Override
1399 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001400 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 "startActivityFromRecents()");
1402
1403 final int callingPid = Binder.getCallingPid();
1404 final int callingUid = Binder.getCallingUid();
1405 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1406 final long origId = Binder.clearCallingIdentity();
1407 try {
1408 synchronized (mGlobalLock) {
1409 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1410 safeOptions);
1411 }
1412 } finally {
1413 Binder.restoreCallingIdentity(origId);
1414 }
1415 }
1416
1417 /**
1418 * This is the internal entry point for handling Activity.finish().
1419 *
1420 * @param token The Binder token referencing the Activity we want to finish.
1421 * @param resultCode Result code, if any, from this Activity.
1422 * @param resultData Result data (Intent), if any, from this Activity.
1423 * @param finishTask Whether to finish the task associated with this Activity.
1424 *
1425 * @return Returns true if the activity successfully finished, or false if it is still running.
1426 */
1427 @Override
1428 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1429 int finishTask) {
1430 // Refuse possible leaked file descriptors
1431 if (resultData != null && resultData.hasFileDescriptors()) {
1432 throw new IllegalArgumentException("File descriptors passed in Intent");
1433 }
1434
1435 synchronized (mGlobalLock) {
1436 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1437 if (r == null) {
1438 return true;
1439 }
1440 // Keep track of the root activity of the task before we finish it
1441 TaskRecord tr = r.getTask();
1442 ActivityRecord rootR = tr.getRootActivity();
1443 if (rootR == null) {
1444 Slog.w(TAG, "Finishing task with all activities already finished");
1445 }
1446 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1447 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001448 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001449 return false;
1450 }
1451
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001452 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1453 // We should consolidate.
1454 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001455 // Find the first activity that is not finishing.
1456 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1457 if (next != null) {
1458 // ask watcher if this is allowed
1459 boolean resumeOK = true;
1460 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001461 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001462 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001463 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 Watchdog.getInstance().setActivityController(null);
1465 }
1466
1467 if (!resumeOK) {
1468 Slog.i(TAG, "Not finishing activity because controller resumed");
1469 return false;
1470 }
1471 }
1472 }
1473 final long origId = Binder.clearCallingIdentity();
1474 try {
1475 boolean res;
1476 final boolean finishWithRootActivity =
1477 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1478 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1479 || (finishWithRootActivity && r == rootR)) {
1480 // If requested, remove the task that is associated to this activity only if it
1481 // was the root activity in the task. The result code and data is ignored
1482 // because we don't support returning them across task boundaries. Also, to
1483 // keep backwards compatibility we remove the task from recents when finishing
1484 // task with root activity.
1485 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1486 finishWithRootActivity, "finish-activity");
1487 if (!res) {
1488 Slog.i(TAG, "Removing task failed to finish activity");
1489 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001490 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001491 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001492 } else {
1493 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1494 resultData, "app-request", true);
1495 if (!res) {
1496 Slog.i(TAG, "Failed to finish by app-request");
1497 }
1498 }
1499 return res;
1500 } finally {
1501 Binder.restoreCallingIdentity(origId);
1502 }
1503 }
1504 }
1505
1506 @Override
1507 public boolean finishActivityAffinity(IBinder token) {
1508 synchronized (mGlobalLock) {
1509 final long origId = Binder.clearCallingIdentity();
1510 try {
1511 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1512 if (r == null) {
1513 return false;
1514 }
1515
1516 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1517 // can finish.
1518 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001519 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001520 return false;
1521 }
1522 return task.getStack().finishActivityAffinityLocked(r);
1523 } finally {
1524 Binder.restoreCallingIdentity(origId);
1525 }
1526 }
1527 }
1528
1529 @Override
1530 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1531 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001532 try {
1533 WindowProcessController proc = null;
1534 synchronized (mGlobalLock) {
1535 ActivityStack stack = ActivityRecord.getStackLocked(token);
1536 if (stack == null) {
1537 return;
1538 }
1539 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1540 false /* fromTimeout */, false /* processPausingActivities */, config);
1541 if (r != null) {
1542 proc = r.app;
1543 }
1544 if (stopProfiling && proc != null) {
1545 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001546 }
1547 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001548 } finally {
1549 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001550 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 }
1552
1553 @Override
1554 public final void activityResumed(IBinder token) {
1555 final long origId = Binder.clearCallingIdentity();
1556 synchronized (mGlobalLock) {
1557 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001558 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001559 }
1560 Binder.restoreCallingIdentity(origId);
1561 }
1562
1563 @Override
1564 public final void activityPaused(IBinder token) {
1565 final long origId = Binder.clearCallingIdentity();
1566 synchronized (mGlobalLock) {
1567 ActivityStack stack = ActivityRecord.getStackLocked(token);
1568 if (stack != null) {
1569 stack.activityPausedLocked(token, false);
1570 }
1571 }
1572 Binder.restoreCallingIdentity(origId);
1573 }
1574
1575 @Override
1576 public final void activityStopped(IBinder token, Bundle icicle,
1577 PersistableBundle persistentState, CharSequence description) {
1578 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1579
1580 // Refuse possible leaked file descriptors
1581 if (icicle != null && icicle.hasFileDescriptors()) {
1582 throw new IllegalArgumentException("File descriptors passed in Bundle");
1583 }
1584
1585 final long origId = Binder.clearCallingIdentity();
1586
1587 synchronized (mGlobalLock) {
1588 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1589 if (r != null) {
1590 r.activityStoppedLocked(icicle, persistentState, description);
1591 }
1592 }
1593
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001594 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595
1596 Binder.restoreCallingIdentity(origId);
1597 }
1598
1599 @Override
1600 public final void activityDestroyed(IBinder token) {
1601 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1602 synchronized (mGlobalLock) {
1603 ActivityStack stack = ActivityRecord.getStackLocked(token);
1604 if (stack != null) {
1605 stack.activityDestroyedLocked(token, "activityDestroyed");
1606 }
1607 }
1608 }
1609
1610 @Override
1611 public final void activityRelaunched(IBinder token) {
1612 final long origId = Binder.clearCallingIdentity();
1613 synchronized (mGlobalLock) {
1614 mStackSupervisor.activityRelaunchedLocked(token);
1615 }
1616 Binder.restoreCallingIdentity(origId);
1617 }
1618
1619 public final void activitySlept(IBinder token) {
1620 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1621
1622 final long origId = Binder.clearCallingIdentity();
1623
1624 synchronized (mGlobalLock) {
1625 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1626 if (r != null) {
1627 mStackSupervisor.activitySleptLocked(r);
1628 }
1629 }
1630
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633
1634 @Override
1635 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1636 synchronized (mGlobalLock) {
1637 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1638 if (r == null) {
1639 return;
1640 }
1641 final long origId = Binder.clearCallingIdentity();
1642 try {
1643 r.setRequestedOrientation(requestedOrientation);
1644 } finally {
1645 Binder.restoreCallingIdentity(origId);
1646 }
1647 }
1648 }
1649
1650 @Override
1651 public int getRequestedOrientation(IBinder token) {
1652 synchronized (mGlobalLock) {
1653 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1654 if (r == null) {
1655 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1656 }
1657 return r.getRequestedOrientation();
1658 }
1659 }
1660
1661 @Override
1662 public void setImmersive(IBinder token, boolean immersive) {
1663 synchronized (mGlobalLock) {
1664 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1665 if (r == null) {
1666 throw new IllegalArgumentException();
1667 }
1668 r.immersive = immersive;
1669
1670 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001671 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001672 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001673 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 }
1675 }
1676 }
1677
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001678 void applyUpdateLockStateLocked(ActivityRecord r) {
1679 // Modifications to the UpdateLock state are done on our handler, outside
1680 // the activity manager's locks. The new state is determined based on the
1681 // state *now* of the relevant activity record. The object is passed to
1682 // the handler solely for logging detail, not to be consulted/modified.
1683 final boolean nextState = r != null && r.immersive;
1684 mH.post(() -> {
1685 if (mUpdateLock.isHeld() != nextState) {
1686 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1687 "Applying new update lock state '" + nextState + "' for " + r);
1688 if (nextState) {
1689 mUpdateLock.acquire();
1690 } else {
1691 mUpdateLock.release();
1692 }
1693 }
1694 });
1695 }
1696
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001697 @Override
1698 public boolean isImmersive(IBinder token) {
1699 synchronized (mGlobalLock) {
1700 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1701 if (r == null) {
1702 throw new IllegalArgumentException();
1703 }
1704 return r.immersive;
1705 }
1706 }
1707
1708 @Override
1709 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001710 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001711 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001712 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001713 return (r != null) ? r.immersive : false;
1714 }
1715 }
1716
1717 @Override
1718 public void overridePendingTransition(IBinder token, String packageName,
1719 int enterAnim, int exitAnim) {
1720 synchronized (mGlobalLock) {
1721 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1722 if (self == null) {
1723 return;
1724 }
1725
1726 final long origId = Binder.clearCallingIdentity();
1727
1728 if (self.isState(
1729 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001730 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1731 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001732 }
1733
1734 Binder.restoreCallingIdentity(origId);
1735 }
1736 }
1737
1738 @Override
1739 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001740 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001741 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001742 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001743 if (r == null) {
1744 return ActivityManager.COMPAT_MODE_UNKNOWN;
1745 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001746 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001747 }
1748 }
1749
1750 @Override
1751 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001752 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001753 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001754 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001755 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001756 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001757 if (r == null) {
1758 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1759 return;
1760 }
1761 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001762 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001763 }
1764 }
1765
1766 @Override
1767 public int getLaunchedFromUid(IBinder activityToken) {
1768 ActivityRecord srec;
1769 synchronized (mGlobalLock) {
1770 srec = ActivityRecord.forTokenLocked(activityToken);
1771 }
1772 if (srec == null) {
1773 return -1;
1774 }
1775 return srec.launchedFromUid;
1776 }
1777
1778 @Override
1779 public String getLaunchedFromPackage(IBinder activityToken) {
1780 ActivityRecord srec;
1781 synchronized (mGlobalLock) {
1782 srec = ActivityRecord.forTokenLocked(activityToken);
1783 }
1784 if (srec == null) {
1785 return null;
1786 }
1787 return srec.launchedFromPackage;
1788 }
1789
1790 @Override
1791 public boolean convertFromTranslucent(IBinder token) {
1792 final long origId = Binder.clearCallingIdentity();
1793 try {
1794 synchronized (mGlobalLock) {
1795 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1796 if (r == null) {
1797 return false;
1798 }
1799 final boolean translucentChanged = r.changeWindowTranslucency(true);
1800 if (translucentChanged) {
1801 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1802 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001803 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001804 return translucentChanged;
1805 }
1806 } finally {
1807 Binder.restoreCallingIdentity(origId);
1808 }
1809 }
1810
1811 @Override
1812 public boolean convertToTranslucent(IBinder token, Bundle options) {
1813 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1814 final long origId = Binder.clearCallingIdentity();
1815 try {
1816 synchronized (mGlobalLock) {
1817 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1818 if (r == null) {
1819 return false;
1820 }
1821 final TaskRecord task = r.getTask();
1822 int index = task.mActivities.lastIndexOf(r);
1823 if (index > 0) {
1824 ActivityRecord under = task.mActivities.get(index - 1);
1825 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1826 }
1827 final boolean translucentChanged = r.changeWindowTranslucency(false);
1828 if (translucentChanged) {
1829 r.getStack().convertActivityToTranslucent(r);
1830 }
1831 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001832 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001833 return translucentChanged;
1834 }
1835 } finally {
1836 Binder.restoreCallingIdentity(origId);
1837 }
1838 }
1839
1840 @Override
1841 public void notifyActivityDrawn(IBinder token) {
1842 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1843 synchronized (mGlobalLock) {
1844 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1845 if (r != null) {
1846 r.getStack().notifyActivityDrawnLocked(r);
1847 }
1848 }
1849 }
1850
1851 @Override
1852 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1853 synchronized (mGlobalLock) {
1854 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1855 if (r == null) {
1856 return;
1857 }
1858 r.reportFullyDrawnLocked(restoredFromBundle);
1859 }
1860 }
1861
1862 @Override
1863 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1864 synchronized (mGlobalLock) {
1865 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1866 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1867 return stack.mDisplayId;
1868 }
1869 return DEFAULT_DISPLAY;
1870 }
1871 }
1872
1873 @Override
1874 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001875 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 long ident = Binder.clearCallingIdentity();
1877 try {
1878 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001879 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 if (focusedStack != null) {
1881 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1882 }
1883 return null;
1884 }
1885 } finally {
1886 Binder.restoreCallingIdentity(ident);
1887 }
1888 }
1889
1890 @Override
1891 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001892 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1894 final long callingId = Binder.clearCallingIdentity();
1895 try {
1896 synchronized (mGlobalLock) {
1897 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1898 if (stack == null) {
1899 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1900 return;
1901 }
1902 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001903 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001904 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001905 }
1906 }
1907 } finally {
1908 Binder.restoreCallingIdentity(callingId);
1909 }
1910 }
1911
1912 @Override
1913 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001914 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1916 final long callingId = Binder.clearCallingIdentity();
1917 try {
1918 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001919 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1920 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001921 if (task == null) {
1922 return;
1923 }
1924 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001925 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001926 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 }
1928 }
1929 } finally {
1930 Binder.restoreCallingIdentity(callingId);
1931 }
1932 }
1933
1934 @Override
1935 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001936 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001937 synchronized (mGlobalLock) {
1938 final long ident = Binder.clearCallingIdentity();
1939 try {
1940 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1941 "remove-task");
1942 } finally {
1943 Binder.restoreCallingIdentity(ident);
1944 }
1945 }
1946 }
1947
1948 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001949 public void removeAllVisibleRecentTasks() {
1950 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1951 synchronized (mGlobalLock) {
1952 final long ident = Binder.clearCallingIdentity();
1953 try {
1954 getRecentTasks().removeAllVisibleTasks();
1955 } finally {
1956 Binder.restoreCallingIdentity(ident);
1957 }
1958 }
1959 }
1960
1961 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1963 synchronized (mGlobalLock) {
1964 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1965 if (srec != null) {
1966 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1967 }
1968 }
1969 return false;
1970 }
1971
1972 @Override
1973 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1974 Intent resultData) {
1975
1976 synchronized (mGlobalLock) {
1977 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1978 if (r != null) {
1979 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1980 }
1981 return false;
1982 }
1983 }
1984
1985 /**
1986 * Attempts to move a task backwards in z-order (the order of activities within the task is
1987 * unchanged).
1988 *
1989 * There are several possible results of this call:
1990 * - if the task is locked, then we will show the lock toast
1991 * - if there is a task behind the provided task, then that task is made visible and resumed as
1992 * this task is moved to the back
1993 * - otherwise, if there are no other tasks in the stack:
1994 * - if this task is in the pinned stack, then we remove the stack completely, which will
1995 * have the effect of moving the task to the top or bottom of the fullscreen stack
1996 * (depending on whether it is visible)
1997 * - otherwise, we simply return home and hide this task
1998 *
1999 * @param token A reference to the activity we wish to move
2000 * @param nonRoot If false then this only works if the activity is the root
2001 * of a task; if true it will work for any activity in a task.
2002 * @return Returns true if the move completed, false if not.
2003 */
2004 @Override
2005 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002006 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002007 synchronized (mGlobalLock) {
2008 final long origId = Binder.clearCallingIdentity();
2009 try {
2010 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
2011 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2012 if (task != null) {
2013 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2014 }
2015 } finally {
2016 Binder.restoreCallingIdentity(origId);
2017 }
2018 }
2019 return false;
2020 }
2021
2022 @Override
2023 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002024 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002025 long ident = Binder.clearCallingIdentity();
2026 Rect rect = new Rect();
2027 try {
2028 synchronized (mGlobalLock) {
2029 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2030 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2031 if (task == null) {
2032 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2033 return rect;
2034 }
2035 if (task.getStack() != null) {
2036 // Return the bounds from window manager since it will be adjusted for various
2037 // things like the presense of a docked stack for tasks that aren't resizeable.
2038 task.getWindowContainerBounds(rect);
2039 } else {
2040 // Task isn't in window manager yet since it isn't associated with a stack.
2041 // Return the persist value from activity manager
2042 if (!task.matchParentBounds()) {
2043 rect.set(task.getBounds());
2044 } else if (task.mLastNonFullscreenBounds != null) {
2045 rect.set(task.mLastNonFullscreenBounds);
2046 }
2047 }
2048 }
2049 } finally {
2050 Binder.restoreCallingIdentity(ident);
2051 }
2052 return rect;
2053 }
2054
2055 @Override
2056 public ActivityManager.TaskDescription getTaskDescription(int id) {
2057 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002058 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
2060 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
2061 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2062 if (tr != null) {
2063 return tr.lastTaskDescription;
2064 }
2065 }
2066 return null;
2067 }
2068
2069 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002070 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2071 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2072 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2073 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2074 return;
2075 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002076 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002077 synchronized (mGlobalLock) {
2078 final long ident = Binder.clearCallingIdentity();
2079 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002080 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2081 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002082 if (task == null) {
2083 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2084 return;
2085 }
2086
2087 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2088 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2089
2090 if (!task.isActivityTypeStandardOrUndefined()) {
2091 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2092 + " non-standard task " + taskId + " to windowing mode="
2093 + windowingMode);
2094 }
2095
2096 final ActivityStack stack = task.getStack();
2097 if (toTop) {
2098 stack.moveToFront("setTaskWindowingMode", task);
2099 }
2100 stack.setWindowingMode(windowingMode);
2101 } finally {
2102 Binder.restoreCallingIdentity(ident);
2103 }
2104 }
2105 }
2106
2107 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002109 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002110 ActivityRecord r = getCallingRecordLocked(token);
2111 return r != null ? r.info.packageName : null;
2112 }
2113 }
2114
2115 @Override
2116 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002117 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 ActivityRecord r = getCallingRecordLocked(token);
2119 return r != null ? r.intent.getComponent() : null;
2120 }
2121 }
2122
2123 private ActivityRecord getCallingRecordLocked(IBinder token) {
2124 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2125 if (r == null) {
2126 return null;
2127 }
2128 return r.resultTo;
2129 }
2130
2131 @Override
2132 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002133 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002134
2135 synchronized (mGlobalLock) {
2136 final long origId = Binder.clearCallingIdentity();
2137 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002138 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002139 } finally {
2140 Binder.restoreCallingIdentity(origId);
2141 }
2142 }
2143 }
2144
2145 /**
2146 * TODO: Add mController hook
2147 */
2148 @Override
2149 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002150 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002151
2152 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2153 synchronized (mGlobalLock) {
2154 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2155 false /* fromRecents */);
2156 }
2157 }
2158
2159 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2160 boolean fromRecents) {
2161
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002162 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002163 Binder.getCallingUid(), -1, -1, "Task to front")) {
2164 SafeActivityOptions.abort(options);
2165 return;
2166 }
2167 final long origId = Binder.clearCallingIdentity();
2168 try {
2169 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2170 if (task == null) {
2171 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002172 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002173 return;
2174 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002175 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002176 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002177 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 return;
2179 }
2180 ActivityOptions realOptions = options != null
2181 ? options.getOptions(mStackSupervisor)
2182 : null;
2183 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2184 false /* forceNonResizable */);
2185
2186 final ActivityRecord topActivity = task.getTopActivity();
2187 if (topActivity != null) {
2188
2189 // We are reshowing a task, use a starting window to hide the initial draw delay
2190 // so the transition can start earlier.
2191 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2192 true /* taskSwitch */, fromRecents);
2193 }
2194 } finally {
2195 Binder.restoreCallingIdentity(origId);
2196 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002197 }
2198
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002199 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2200 int callingPid, int callingUid, String name) {
2201 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2202 return true;
2203 }
2204
2205 if (getRecentTasks().isCallerRecents(sourceUid)) {
2206 return true;
2207 }
2208
2209 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2210 if (perm == PackageManager.PERMISSION_GRANTED) {
2211 return true;
2212 }
2213 if (checkAllowAppSwitchUid(sourceUid)) {
2214 return true;
2215 }
2216
2217 // If the actual IPC caller is different from the logical source, then
2218 // also see if they are allowed to control app switches.
2219 if (callingUid != -1 && callingUid != sourceUid) {
2220 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2221 if (perm == PackageManager.PERMISSION_GRANTED) {
2222 return true;
2223 }
2224 if (checkAllowAppSwitchUid(callingUid)) {
2225 return true;
2226 }
2227 }
2228
2229 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2230 return false;
2231 }
2232
2233 private boolean checkAllowAppSwitchUid(int uid) {
2234 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2235 if (types != null) {
2236 for (int i = types.size() - 1; i >= 0; i--) {
2237 if (types.valueAt(i).intValue() == uid) {
2238 return true;
2239 }
2240 }
2241 }
2242 return false;
2243 }
2244
2245 @Override
2246 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2247 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2248 "setActivityController()");
2249 synchronized (mGlobalLock) {
2250 mController = controller;
2251 mControllerIsAMonkey = imAMonkey;
2252 Watchdog.getInstance().setActivityController(controller);
2253 }
2254 }
2255
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002256 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002257 synchronized (mGlobalLock) {
2258 return mController != null && mControllerIsAMonkey;
2259 }
2260 }
2261
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002262 @Override
2263 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2264 synchronized (mGlobalLock) {
2265 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2266 }
2267 }
2268
2269 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002270 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2271 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2272 }
2273
2274 @Override
2275 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2276 @WindowConfiguration.ActivityType int ignoreActivityType,
2277 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2278 final int callingUid = Binder.getCallingUid();
2279 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2280
2281 synchronized (mGlobalLock) {
2282 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2283
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002284 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002285 callingUid);
2286 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2287 ignoreWindowingMode, callingUid, allowed);
2288 }
2289
2290 return list;
2291 }
2292
2293 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002294 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2295 synchronized (mGlobalLock) {
2296 final long origId = Binder.clearCallingIdentity();
2297 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2298 if (r != null) {
2299 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2300 }
2301 Binder.restoreCallingIdentity(origId);
2302 }
2303 }
2304
2305 @Override
2306 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002307 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002308 ActivityStack stack = ActivityRecord.getStackLocked(token);
2309 if (stack != null) {
2310 return stack.willActivityBeVisibleLocked(token);
2311 }
2312 return false;
2313 }
2314 }
2315
2316 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002317 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002318 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002319 synchronized (mGlobalLock) {
2320 final long ident = Binder.clearCallingIdentity();
2321 try {
2322 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2323 if (task == null) {
2324 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2325 return;
2326 }
2327
2328 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2329 + " to stackId=" + stackId + " toTop=" + toTop);
2330
2331 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2332 if (stack == null) {
2333 throw new IllegalStateException(
2334 "moveTaskToStack: No stack for stackId=" + stackId);
2335 }
2336 if (!stack.isActivityTypeStandardOrUndefined()) {
2337 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2338 + taskId + " to stack " + stackId);
2339 }
2340 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002341 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002342 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2343 }
2344 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2345 "moveTaskToStack");
2346 } finally {
2347 Binder.restoreCallingIdentity(ident);
2348 }
2349 }
2350 }
2351
2352 @Override
2353 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2354 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002355 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002356
2357 final long ident = Binder.clearCallingIdentity();
2358 try {
2359 synchronized (mGlobalLock) {
2360 if (animate) {
2361 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2362 if (stack == null) {
2363 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2364 return;
2365 }
2366 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2367 throw new IllegalArgumentException("Stack: " + stackId
2368 + " doesn't support animated resize.");
2369 }
2370 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2371 animationDuration, false /* fromFullscreen */);
2372 } else {
2373 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2374 if (stack == null) {
2375 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2376 return;
2377 }
2378 mStackSupervisor.resizeStackLocked(stack, destBounds,
2379 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2380 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2381 }
2382 }
2383 } finally {
2384 Binder.restoreCallingIdentity(ident);
2385 }
2386 }
2387
2388 /**
2389 * Moves the specified task to the primary-split-screen stack.
2390 *
2391 * @param taskId Id of task to move.
2392 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2393 * exist already. See
2394 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2395 * and
2396 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2397 * @param toTop If the task and stack should be moved to the top.
2398 * @param animate Whether we should play an animation for the moving the task.
2399 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2400 * stack. Pass {@code null} to use default bounds.
2401 * @param showRecents If the recents activity should be shown on the other side of the task
2402 * going into split-screen mode.
2403 */
2404 @Override
2405 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2406 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002407 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002408 "setTaskWindowingModeSplitScreenPrimary()");
2409 synchronized (mGlobalLock) {
2410 final long ident = Binder.clearCallingIdentity();
2411 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002412 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2413 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002414 if (task == null) {
2415 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2416 return false;
2417 }
2418 if (DEBUG_STACK) Slog.d(TAG_STACK,
2419 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2420 + " to createMode=" + createMode + " toTop=" + toTop);
2421 if (!task.isActivityTypeStandardOrUndefined()) {
2422 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2423 + " non-standard task " + taskId + " to split-screen windowing mode");
2424 }
2425
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002426 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002427 final int windowingMode = task.getWindowingMode();
2428 final ActivityStack stack = task.getStack();
2429 if (toTop) {
2430 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2431 }
2432 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002433 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2434 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002435 return windowingMode != task.getWindowingMode();
2436 } finally {
2437 Binder.restoreCallingIdentity(ident);
2438 }
2439 }
2440 }
2441
2442 /**
2443 * Removes stacks in the input windowing modes from the system if they are of activity type
2444 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2445 */
2446 @Override
2447 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002448 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002449 "removeStacksInWindowingModes()");
2450
2451 synchronized (mGlobalLock) {
2452 final long ident = Binder.clearCallingIdentity();
2453 try {
2454 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2455 } finally {
2456 Binder.restoreCallingIdentity(ident);
2457 }
2458 }
2459 }
2460
2461 @Override
2462 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002463 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002464 "removeStacksWithActivityTypes()");
2465
2466 synchronized (mGlobalLock) {
2467 final long ident = Binder.clearCallingIdentity();
2468 try {
2469 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2470 } finally {
2471 Binder.restoreCallingIdentity(ident);
2472 }
2473 }
2474 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002475
2476 @Override
2477 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2478 int userId) {
2479 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002480 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2481 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002482 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002483 final boolean detailed = checkGetTasksPermission(
2484 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2485 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002486 == PackageManager.PERMISSION_GRANTED;
2487
2488 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002489 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002490 callingUid);
2491 }
2492 }
2493
2494 @Override
2495 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002497 long ident = Binder.clearCallingIdentity();
2498 try {
2499 synchronized (mGlobalLock) {
2500 return mStackSupervisor.getAllStackInfosLocked();
2501 }
2502 } finally {
2503 Binder.restoreCallingIdentity(ident);
2504 }
2505 }
2506
2507 @Override
2508 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002509 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002510 long ident = Binder.clearCallingIdentity();
2511 try {
2512 synchronized (mGlobalLock) {
2513 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2514 }
2515 } finally {
2516 Binder.restoreCallingIdentity(ident);
2517 }
2518 }
2519
2520 @Override
2521 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002522 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002523 final long callingUid = Binder.getCallingUid();
2524 final long origId = Binder.clearCallingIdentity();
2525 try {
2526 synchronized (mGlobalLock) {
2527 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002528 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002529 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2530 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2531 }
2532 } finally {
2533 Binder.restoreCallingIdentity(origId);
2534 }
2535 }
2536
2537 @Override
2538 public void startLockTaskModeByToken(IBinder token) {
2539 synchronized (mGlobalLock) {
2540 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2541 if (r == null) {
2542 return;
2543 }
2544 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2545 }
2546 }
2547
2548 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002549 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002550 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002551 // This makes inner call to look as if it was initiated by system.
2552 long ident = Binder.clearCallingIdentity();
2553 try {
2554 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002555 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2556 MATCH_TASK_IN_STACKS_ONLY);
2557 if (task == null) {
2558 return;
2559 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002560
2561 // When starting lock task mode the stack must be in front and focused
2562 task.getStack().moveToFront("startSystemLockTaskMode");
2563 startLockTaskModeLocked(task, true /* isSystemCaller */);
2564 }
2565 } finally {
2566 Binder.restoreCallingIdentity(ident);
2567 }
2568 }
2569
2570 @Override
2571 public void stopLockTaskModeByToken(IBinder token) {
2572 synchronized (mGlobalLock) {
2573 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2574 if (r == null) {
2575 return;
2576 }
2577 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2578 }
2579 }
2580
2581 /**
2582 * This API should be called by SystemUI only when user perform certain action to dismiss
2583 * lock task mode. We should only dismiss pinned lock task mode in this case.
2584 */
2585 @Override
2586 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002587 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002588 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2589 }
2590
2591 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2592 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2593 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2594 return;
2595 }
2596
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002597 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 if (stack == null || task != stack.topTask()) {
2599 throw new IllegalArgumentException("Invalid task, not in foreground");
2600 }
2601
2602 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2603 // system or a specific app.
2604 // * System-initiated requests will only start the pinned mode (screen pinning)
2605 // * App-initiated requests
2606 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2607 // - will start the pinned mode, otherwise
2608 final int callingUid = Binder.getCallingUid();
2609 long ident = Binder.clearCallingIdentity();
2610 try {
2611 // When a task is locked, dismiss the pinned stack if it exists
2612 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2613
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002614 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002615 } finally {
2616 Binder.restoreCallingIdentity(ident);
2617 }
2618 }
2619
2620 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2621 final int callingUid = Binder.getCallingUid();
2622 long ident = Binder.clearCallingIdentity();
2623 try {
2624 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002625 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002626 }
2627 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2628 // task and jumping straight into a call in the case of emergency call back.
2629 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2630 if (tm != null) {
2631 tm.showInCallScreen(false);
2632 }
2633 } finally {
2634 Binder.restoreCallingIdentity(ident);
2635 }
2636 }
2637
2638 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002639 public void updateLockTaskPackages(int userId, String[] packages) {
2640 final int callingUid = Binder.getCallingUid();
2641 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2642 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2643 "updateLockTaskPackages()");
2644 }
2645 synchronized (this) {
2646 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2647 + Arrays.toString(packages));
2648 getLockTaskController().updateLockTaskPackages(userId, packages);
2649 }
2650 }
2651
2652 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002653 public boolean isInLockTaskMode() {
2654 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2655 }
2656
2657 @Override
2658 public int getLockTaskModeState() {
2659 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002660 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661 }
2662 }
2663
2664 @Override
2665 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2666 synchronized (mGlobalLock) {
2667 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2668 if (r != null) {
2669 r.setTaskDescription(td);
2670 final TaskRecord task = r.getTask();
2671 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002672 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002673 }
2674 }
2675 }
2676
2677 @Override
2678 public Bundle getActivityOptions(IBinder token) {
2679 final long origId = Binder.clearCallingIdentity();
2680 try {
2681 synchronized (mGlobalLock) {
2682 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2683 if (r != null) {
2684 final ActivityOptions activityOptions = r.takeOptionsLocked();
2685 return activityOptions == null ? null : activityOptions.toBundle();
2686 }
2687 return null;
2688 }
2689 } finally {
2690 Binder.restoreCallingIdentity(origId);
2691 }
2692 }
2693
2694 @Override
2695 public List<IBinder> getAppTasks(String callingPackage) {
2696 int callingUid = Binder.getCallingUid();
2697 long ident = Binder.clearCallingIdentity();
2698 try {
2699 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002700 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 }
2702 } finally {
2703 Binder.restoreCallingIdentity(ident);
2704 }
2705 }
2706
2707 @Override
2708 public void finishVoiceTask(IVoiceInteractionSession session) {
2709 synchronized (mGlobalLock) {
2710 final long origId = Binder.clearCallingIdentity();
2711 try {
2712 // TODO: VI Consider treating local voice interactions and voice tasks
2713 // differently here
2714 mStackSupervisor.finishVoiceTask(session);
2715 } finally {
2716 Binder.restoreCallingIdentity(origId);
2717 }
2718 }
2719
2720 }
2721
2722 @Override
2723 public boolean isTopOfTask(IBinder token) {
2724 synchronized (mGlobalLock) {
2725 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002726 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002727 }
2728 }
2729
2730 @Override
2731 public void notifyLaunchTaskBehindComplete(IBinder token) {
2732 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2733 }
2734
2735 @Override
2736 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002737 mH.post(() -> {
2738 synchronized (mGlobalLock) {
2739 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002740 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002741 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002742 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002743 } catch (RemoteException e) {
2744 }
2745 }
2746 }
2747
2748 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002749 }
2750
2751 /** Called from an app when assist data is ready. */
2752 @Override
2753 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2754 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002755 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 synchronized (pae) {
2757 pae.result = extras;
2758 pae.structure = structure;
2759 pae.content = content;
2760 if (referrer != null) {
2761 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2762 }
2763 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002764 // Pre-fill the task/activity component for all assist data receivers
2765 structure.setTaskId(pae.activity.getTask().taskId);
2766 structure.setActivityComponent(pae.activity.realActivity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 structure.setHomeActivity(pae.isHome);
2768 }
2769 pae.haveResult = true;
2770 pae.notifyAll();
2771 if (pae.intent == null && pae.receiver == null) {
2772 // Caller is just waiting for the result.
2773 return;
2774 }
2775 }
2776 // We are now ready to launch the assist activity.
2777 IAssistDataReceiver sendReceiver = null;
2778 Bundle sendBundle = null;
2779 synchronized (mGlobalLock) {
2780 buildAssistBundleLocked(pae, extras);
2781 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002782 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002783 if (!exists) {
2784 // Timed out.
2785 return;
2786 }
2787
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 // Caller wants result sent back to them.
2790 sendBundle = new Bundle();
2791 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2792 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2793 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2794 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2795 }
2796 }
2797 if (sendReceiver != null) {
2798 try {
2799 sendReceiver.onHandleAssistData(sendBundle);
2800 } catch (RemoteException e) {
2801 }
2802 return;
2803 }
2804
2805 final long ident = Binder.clearCallingIdentity();
2806 try {
2807 if (TextUtils.equals(pae.intent.getAction(),
2808 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2809 pae.intent.putExtras(pae.extras);
2810 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2811 } else {
2812 pae.intent.replaceExtras(pae.extras);
2813 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2814 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2815 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002816 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002817
2818 try {
2819 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2820 } catch (ActivityNotFoundException e) {
2821 Slog.w(TAG, "No activity to handle assist action.", e);
2822 }
2823 }
2824 } finally {
2825 Binder.restoreCallingIdentity(ident);
2826 }
2827 }
2828
2829 @Override
2830 public int addAppTask(IBinder activityToken, Intent intent,
2831 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2832 final int callingUid = Binder.getCallingUid();
2833 final long callingIdent = Binder.clearCallingIdentity();
2834
2835 try {
2836 synchronized (mGlobalLock) {
2837 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2838 if (r == null) {
2839 throw new IllegalArgumentException("Activity does not exist; token="
2840 + activityToken);
2841 }
2842 ComponentName comp = intent.getComponent();
2843 if (comp == null) {
2844 throw new IllegalArgumentException("Intent " + intent
2845 + " must specify explicit component");
2846 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002847 if (thumbnail.getWidth() != mThumbnailWidth
2848 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 throw new IllegalArgumentException("Bad thumbnail size: got "
2850 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002851 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 }
2853 if (intent.getSelector() != null) {
2854 intent.setSelector(null);
2855 }
2856 if (intent.getSourceBounds() != null) {
2857 intent.setSourceBounds(null);
2858 }
2859 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2860 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2861 // The caller has added this as an auto-remove task... that makes no
2862 // sense, so turn off auto-remove.
2863 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2864 }
2865 }
2866 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2867 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2868 if (ainfo.applicationInfo.uid != callingUid) {
2869 throw new SecurityException(
2870 "Can't add task for another application: target uid="
2871 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2872 }
2873
2874 final ActivityStack stack = r.getStack();
2875 final TaskRecord task = stack.createTaskRecord(
2876 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2877 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002878 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002879 // The app has too many tasks already and we can't add any more
2880 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2881 return INVALID_TASK_ID;
2882 }
2883 task.lastTaskDescription.copyFrom(description);
2884
2885 // TODO: Send the thumbnail to WM to store it.
2886
2887 return task.taskId;
2888 }
2889 } finally {
2890 Binder.restoreCallingIdentity(callingIdent);
2891 }
2892 }
2893
2894 @Override
2895 public Point getAppTaskThumbnailSize() {
2896 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002897 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002898 }
2899 }
2900
2901 @Override
2902 public void setTaskResizeable(int taskId, int resizeableMode) {
2903 synchronized (mGlobalLock) {
2904 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2905 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2906 if (task == null) {
2907 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2908 return;
2909 }
2910 task.setResizeMode(resizeableMode);
2911 }
2912 }
2913
2914 @Override
2915 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002916 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002917 long ident = Binder.clearCallingIdentity();
2918 try {
2919 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002920 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2921 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 if (task == null) {
2923 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2924 return;
2925 }
2926 // Place the task in the right stack if it isn't there already based on
2927 // the requested bounds.
2928 // The stack transition logic is:
2929 // - a null bounds on a freeform task moves that task to fullscreen
2930 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2931 // that task to freeform
2932 // - otherwise the task is not moved
2933 ActivityStack stack = task.getStack();
2934 if (!task.getWindowConfiguration().canResizeTask()) {
2935 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2936 }
2937 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2938 stack = stack.getDisplay().getOrCreateStack(
2939 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2940 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2941 stack = stack.getDisplay().getOrCreateStack(
2942 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2943 }
2944
2945 // Reparent the task to the right stack if necessary
2946 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2947 if (stack != task.getStack()) {
2948 // Defer resume until the task is resized below
2949 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2950 DEFER_RESUME, "resizeTask");
2951 preserveWindow = false;
2952 }
2953
2954 // After reparenting (which only resizes the task to the stack bounds), resize the
2955 // task to the actual bounds provided
2956 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2957 }
2958 } finally {
2959 Binder.restoreCallingIdentity(ident);
2960 }
2961 }
2962
2963 @Override
2964 public boolean releaseActivityInstance(IBinder token) {
2965 synchronized (mGlobalLock) {
2966 final long origId = Binder.clearCallingIdentity();
2967 try {
2968 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2969 if (r == null) {
2970 return false;
2971 }
2972 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2973 } finally {
2974 Binder.restoreCallingIdentity(origId);
2975 }
2976 }
2977 }
2978
2979 @Override
2980 public void releaseSomeActivities(IApplicationThread appInt) {
2981 synchronized (mGlobalLock) {
2982 final long origId = Binder.clearCallingIdentity();
2983 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002984 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002985 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2986 } finally {
2987 Binder.restoreCallingIdentity(origId);
2988 }
2989 }
2990 }
2991
2992 @Override
2993 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002994 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002995 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002996 != PackageManager.PERMISSION_GRANTED) {
2997 throw new SecurityException("Requires permission "
2998 + android.Manifest.permission.DEVICE_POWER);
2999 }
3000
3001 synchronized (mGlobalLock) {
3002 long ident = Binder.clearCallingIdentity();
3003 if (mKeyguardShown != keyguardShowing) {
3004 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003005 final Message msg = PooledLambda.obtainMessage(
3006 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3007 keyguardShowing);
3008 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003009 }
3010 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003011 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003012 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003013 } finally {
3014 Binder.restoreCallingIdentity(ident);
3015 }
3016 }
3017
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003018 mH.post(() -> {
3019 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3020 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3021 }
3022 });
3023 }
3024
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003025 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003026 mH.post(() -> {
3027 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3028 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3029 }
3030 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003031 }
3032
3033 @Override
3034 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003035 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3036 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003037
3038 final File passedIconFile = new File(filePath);
3039 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3040 passedIconFile.getName());
3041 if (!legitIconFile.getPath().equals(filePath)
3042 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3043 throw new IllegalArgumentException("Bad file path: " + filePath
3044 + " passed for userId " + userId);
3045 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003046 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003047 }
3048
3049 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003050 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003051 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3052 final ActivityOptions activityOptions = safeOptions != null
3053 ? safeOptions.getOptions(mStackSupervisor)
3054 : null;
3055 if (activityOptions == null
3056 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3057 || activityOptions.getCustomInPlaceResId() == 0) {
3058 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3059 "with valid animation");
3060 }
lumark588a3e82018-07-20 18:53:54 +08003061 // Get top display of front most application.
3062 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3063 if (focusedStack != null) {
3064 final DisplayWindowController dwc =
3065 focusedStack.getDisplay().getWindowContainerController();
3066 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3067 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3068 activityOptions.getCustomInPlaceResId());
3069 dwc.executeAppTransition();
3070 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003071 }
3072
3073 @Override
3074 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003075 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 synchronized (mGlobalLock) {
3077 final long ident = Binder.clearCallingIdentity();
3078 try {
3079 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3080 if (stack == null) {
3081 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3082 return;
3083 }
3084 if (!stack.isActivityTypeStandardOrUndefined()) {
3085 throw new IllegalArgumentException(
3086 "Removing non-standard stack is not allowed.");
3087 }
3088 mStackSupervisor.removeStack(stack);
3089 } finally {
3090 Binder.restoreCallingIdentity(ident);
3091 }
3092 }
3093 }
3094
3095 @Override
3096 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003097 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098
3099 synchronized (mGlobalLock) {
3100 final long ident = Binder.clearCallingIdentity();
3101 try {
3102 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3103 + " to displayId=" + displayId);
3104 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
3105 } finally {
3106 Binder.restoreCallingIdentity(ident);
3107 }
3108 }
3109 }
3110
3111 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 public void exitFreeformMode(IBinder token) {
3113 synchronized (mGlobalLock) {
3114 long ident = Binder.clearCallingIdentity();
3115 try {
3116 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3117 if (r == null) {
3118 throw new IllegalArgumentException(
3119 "exitFreeformMode: No activity record matching token=" + token);
3120 }
3121
3122 final ActivityStack stack = r.getStack();
3123 if (stack == null || !stack.inFreeformWindowingMode()) {
3124 throw new IllegalStateException(
3125 "exitFreeformMode: You can only go fullscreen from freeform.");
3126 }
3127
3128 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3129 } finally {
3130 Binder.restoreCallingIdentity(ident);
3131 }
3132 }
3133 }
3134
3135 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3136 @Override
3137 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003138 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003140 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141 }
3142
3143 /** Unregister a task stack listener so that it stops receiving callbacks. */
3144 @Override
3145 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003146 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003147 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003148 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003149 }
3150
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 @Override
3152 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3153 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3154 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3155 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3156 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3157 }
3158
3159 @Override
3160 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3161 IBinder activityToken, int flags) {
3162 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3163 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3164 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3165 }
3166
3167 @Override
3168 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3169 Bundle args) {
3170 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3171 true /* focused */, true /* newSessionId */, userHandle, args,
3172 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3173 }
3174
3175 @Override
3176 public Bundle getAssistContextExtras(int requestType) {
3177 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3178 null, null, true /* focused */, true /* newSessionId */,
3179 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3180 if (pae == null) {
3181 return null;
3182 }
3183 synchronized (pae) {
3184 while (!pae.haveResult) {
3185 try {
3186 pae.wait();
3187 } catch (InterruptedException e) {
3188 }
3189 }
3190 }
3191 synchronized (mGlobalLock) {
3192 buildAssistBundleLocked(pae, pae.result);
3193 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003194 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003195 }
3196 return pae.extras;
3197 }
3198
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003199 /**
3200 * Binder IPC calls go through the public entry point.
3201 * This can be called with or without the global lock held.
3202 */
3203 private static int checkCallingPermission(String permission) {
3204 return checkPermission(
3205 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3206 }
3207
3208 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003209 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003210 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3211 mAmInternal.enforceCallingPermission(permission, func);
3212 }
3213 }
3214
3215 @VisibleForTesting
3216 int checkGetTasksPermission(String permission, int pid, int uid) {
3217 return checkPermission(permission, pid, uid);
3218 }
3219
3220 static int checkPermission(String permission, int pid, int uid) {
3221 if (permission == null) {
3222 return PackageManager.PERMISSION_DENIED;
3223 }
3224 return checkComponentPermission(permission, pid, uid, -1, true);
3225 }
3226
Wale Ogunwale214f3482018-10-04 11:00:47 -07003227 public static int checkComponentPermission(String permission, int pid, int uid,
3228 int owningUid, boolean exported) {
3229 return ActivityManagerService.checkComponentPermission(
3230 permission, pid, uid, owningUid, exported);
3231 }
3232
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003233 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3234 if (getRecentTasks().isCallerRecents(callingUid)) {
3235 // Always allow the recents component to get tasks
3236 return true;
3237 }
3238
3239 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3240 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3241 if (!allowed) {
3242 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3243 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3244 // Temporary compatibility: some existing apps on the system image may
3245 // still be requesting the old permission and not switched to the new
3246 // one; if so, we'll still allow them full access. This means we need
3247 // to see if they are holding the old permission and are a system app.
3248 try {
3249 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3250 allowed = true;
3251 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3252 + " is using old GET_TASKS but privileged; allowing");
3253 }
3254 } catch (RemoteException e) {
3255 }
3256 }
3257 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3258 + " does not hold REAL_GET_TASKS; limiting output");
3259 }
3260 return allowed;
3261 }
3262
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003263 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3264 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3265 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3266 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003267 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003268 "enqueueAssistContext()");
3269
3270 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003271 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003272 if (activity == null) {
3273 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3274 return null;
3275 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003276 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003277 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3278 return null;
3279 }
3280 if (focused) {
3281 if (activityToken != null) {
3282 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3283 if (activity != caller) {
3284 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3285 + " is not current top " + activity);
3286 return null;
3287 }
3288 }
3289 } else {
3290 activity = ActivityRecord.forTokenLocked(activityToken);
3291 if (activity == null) {
3292 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3293 + " couldn't be found");
3294 return null;
3295 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003296 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3298 return null;
3299 }
3300 }
3301
3302 PendingAssistExtras pae;
3303 Bundle extras = new Bundle();
3304 if (args != null) {
3305 extras.putAll(args);
3306 }
3307 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003308 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309
3310 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3311 userHandle);
3312 pae.isHome = activity.isActivityTypeHome();
3313
3314 // Increment the sessionId if necessary
3315 if (newSessionId) {
3316 mViSessionId++;
3317 }
3318 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003319 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3320 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003321 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003322 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 } catch (RemoteException e) {
3324 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3325 return null;
3326 }
3327 return pae;
3328 }
3329 }
3330
3331 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3332 if (result != null) {
3333 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3334 }
3335 if (pae.hint != null) {
3336 pae.extras.putBoolean(pae.hint, true);
3337 }
3338 }
3339
3340 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3341 IAssistDataReceiver receiver;
3342 synchronized (mGlobalLock) {
3343 mPendingAssistExtras.remove(pae);
3344 receiver = pae.receiver;
3345 }
3346 if (receiver != null) {
3347 // Caller wants result sent back to them.
3348 Bundle sendBundle = new Bundle();
3349 // At least return the receiver extras
3350 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3351 try {
3352 pae.receiver.onHandleAssistData(sendBundle);
3353 } catch (RemoteException e) {
3354 }
3355 }
3356 }
3357
3358 public class PendingAssistExtras extends Binder implements Runnable {
3359 public final ActivityRecord activity;
3360 public boolean isHome;
3361 public final Bundle extras;
3362 public final Intent intent;
3363 public final String hint;
3364 public final IAssistDataReceiver receiver;
3365 public final int userHandle;
3366 public boolean haveResult = false;
3367 public Bundle result = null;
3368 public AssistStructure structure = null;
3369 public AssistContent content = null;
3370 public Bundle receiverExtras;
3371
3372 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3373 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3374 int _userHandle) {
3375 activity = _activity;
3376 extras = _extras;
3377 intent = _intent;
3378 hint = _hint;
3379 receiver = _receiver;
3380 receiverExtras = _receiverExtras;
3381 userHandle = _userHandle;
3382 }
3383
3384 @Override
3385 public void run() {
3386 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3387 synchronized (this) {
3388 haveResult = true;
3389 notifyAll();
3390 }
3391 pendingAssistExtrasTimedOut(this);
3392 }
3393 }
3394
3395 @Override
3396 public boolean isAssistDataAllowedOnCurrentActivity() {
3397 int userId;
3398 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003399 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003400 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3401 return false;
3402 }
3403
3404 final ActivityRecord activity = focusedStack.getTopActivity();
3405 if (activity == null) {
3406 return false;
3407 }
3408 userId = activity.userId;
3409 }
3410 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3411 }
3412
3413 @Override
3414 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3415 long ident = Binder.clearCallingIdentity();
3416 try {
3417 synchronized (mGlobalLock) {
3418 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003419 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003420 if (top != caller) {
3421 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3422 + " is not current top " + top);
3423 return false;
3424 }
3425 if (!top.nowVisible) {
3426 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3427 + " is not visible");
3428 return false;
3429 }
3430 }
3431 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3432 token);
3433 } finally {
3434 Binder.restoreCallingIdentity(ident);
3435 }
3436 }
3437
3438 @Override
3439 public boolean isRootVoiceInteraction(IBinder token) {
3440 synchronized (mGlobalLock) {
3441 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3442 if (r == null) {
3443 return false;
3444 }
3445 return r.rootVoiceInteraction;
3446 }
3447 }
3448
Wale Ogunwalef6733932018-06-27 05:14:34 -07003449 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3450 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3451 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3452 if (activityToCallback == null) return;
3453 activityToCallback.setVoiceSessionLocked(voiceSession);
3454
3455 // Inform the activity
3456 try {
3457 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3458 voiceInteractor);
3459 long token = Binder.clearCallingIdentity();
3460 try {
3461 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3462 } finally {
3463 Binder.restoreCallingIdentity(token);
3464 }
3465 // TODO: VI Should we cache the activity so that it's easier to find later
3466 // rather than scan through all the stacks and activities?
3467 } catch (RemoteException re) {
3468 activityToCallback.clearVoiceSessionLocked();
3469 // TODO: VI Should this terminate the voice session?
3470 }
3471 }
3472
3473 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3474 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3475 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3476 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3477 boolean wasRunningVoice = mRunningVoice != null;
3478 mRunningVoice = session;
3479 if (!wasRunningVoice) {
3480 mVoiceWakeLock.acquire();
3481 updateSleepIfNeededLocked();
3482 }
3483 }
3484 }
3485
3486 void finishRunningVoiceLocked() {
3487 if (mRunningVoice != null) {
3488 mRunningVoice = null;
3489 mVoiceWakeLock.release();
3490 updateSleepIfNeededLocked();
3491 }
3492 }
3493
3494 @Override
3495 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3496 synchronized (mGlobalLock) {
3497 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3498 if (keepAwake) {
3499 mVoiceWakeLock.acquire();
3500 } else {
3501 mVoiceWakeLock.release();
3502 }
3503 }
3504 }
3505 }
3506
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 @Override
3508 public ComponentName getActivityClassForToken(IBinder token) {
3509 synchronized (mGlobalLock) {
3510 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3511 if (r == null) {
3512 return null;
3513 }
3514 return r.intent.getComponent();
3515 }
3516 }
3517
3518 @Override
3519 public String getPackageForToken(IBinder token) {
3520 synchronized (mGlobalLock) {
3521 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3522 if (r == null) {
3523 return null;
3524 }
3525 return r.packageName;
3526 }
3527 }
3528
3529 @Override
3530 public void showLockTaskEscapeMessage(IBinder token) {
3531 synchronized (mGlobalLock) {
3532 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3533 if (r == null) {
3534 return;
3535 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003536 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003537 }
3538 }
3539
3540 @Override
3541 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003542 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003543 final long token = Binder.clearCallingIdentity();
3544 try {
3545 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003546 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003547 }
3548 } finally {
3549 Binder.restoreCallingIdentity(token);
3550 }
3551 }
3552
3553 /**
3554 * Try to place task to provided position. The final position might be different depending on
3555 * current user and stacks state. The task will be moved to target stack if it's currently in
3556 * different stack.
3557 */
3558 @Override
3559 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003560 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003561 synchronized (mGlobalLock) {
3562 long ident = Binder.clearCallingIdentity();
3563 try {
3564 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3565 + taskId + " in stackId=" + stackId + " at position=" + position);
3566 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3567 if (task == null) {
3568 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3569 + taskId);
3570 }
3571
3572 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3573
3574 if (stack == null) {
3575 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3576 + stackId);
3577 }
3578 if (!stack.isActivityTypeStandardOrUndefined()) {
3579 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3580 + " the position of task " + taskId + " in/to non-standard stack");
3581 }
3582
3583 // TODO: Have the callers of this API call a separate reparent method if that is
3584 // what they intended to do vs. having this method also do reparenting.
3585 if (task.getStack() == stack) {
3586 // Change position in current stack.
3587 stack.positionChildAt(task, position);
3588 } else {
3589 // Reparent to new stack.
3590 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3591 !DEFER_RESUME, "positionTaskInStack");
3592 }
3593 } finally {
3594 Binder.restoreCallingIdentity(ident);
3595 }
3596 }
3597 }
3598
3599 @Override
3600 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3601 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3602 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3603 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3604 synchronized (mGlobalLock) {
3605 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3606 if (record == null) {
3607 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3608 + "found for: " + token);
3609 }
3610 record.setSizeConfigurations(horizontalSizeConfiguration,
3611 verticalSizeConfigurations, smallestSizeConfigurations);
3612 }
3613 }
3614
3615 /**
3616 * Dismisses split-screen multi-window mode.
3617 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3618 */
3619 @Override
3620 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003621 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003622 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3623 final long ident = Binder.clearCallingIdentity();
3624 try {
3625 synchronized (mGlobalLock) {
3626 final ActivityStack stack =
3627 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3628 if (stack == null) {
3629 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3630 return;
3631 }
3632
3633 if (toTop) {
3634 // Caller wants the current split-screen primary stack to be the top stack after
3635 // it goes fullscreen, so move it to the front.
3636 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003637 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003638 // In this case the current split-screen primary stack shouldn't be the top
3639 // stack after it goes fullscreen, but it current has focus, so we move the
3640 // focus to the top-most split-screen secondary stack next to it.
3641 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3642 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3643 if (otherStack != null) {
3644 otherStack.moveToFront("dismissSplitScreenMode_other");
3645 }
3646 }
3647
Evan Rosky10475742018-09-05 19:02:48 -07003648 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 }
3650 } finally {
3651 Binder.restoreCallingIdentity(ident);
3652 }
3653 }
3654
3655 /**
3656 * Dismisses Pip
3657 * @param animate True if the dismissal should be animated.
3658 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3659 * default animation duration should be used.
3660 */
3661 @Override
3662 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003663 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003664 final long ident = Binder.clearCallingIdentity();
3665 try {
3666 synchronized (mGlobalLock) {
3667 final PinnedActivityStack stack =
3668 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3669 if (stack == null) {
3670 Slog.w(TAG, "dismissPip: pinned stack not found.");
3671 return;
3672 }
3673 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3674 throw new IllegalArgumentException("Stack: " + stack
3675 + " doesn't support animated resize.");
3676 }
3677 if (animate) {
3678 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3679 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3680 } else {
3681 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3682 }
3683 }
3684 } finally {
3685 Binder.restoreCallingIdentity(ident);
3686 }
3687 }
3688
3689 @Override
3690 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003691 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003692 synchronized (mGlobalLock) {
3693 mSuppressResizeConfigChanges = suppress;
3694 }
3695 }
3696
3697 /**
3698 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3699 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3700 * activity and clearing the task at the same time.
3701 */
3702 @Override
3703 // TODO: API should just be about changing windowing modes...
3704 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003705 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003706 "moveTasksToFullscreenStack()");
3707 synchronized (mGlobalLock) {
3708 final long origId = Binder.clearCallingIdentity();
3709 try {
3710 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3711 if (stack != null){
3712 if (!stack.isActivityTypeStandardOrUndefined()) {
3713 throw new IllegalArgumentException(
3714 "You can't move tasks from non-standard stacks.");
3715 }
3716 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3717 }
3718 } finally {
3719 Binder.restoreCallingIdentity(origId);
3720 }
3721 }
3722 }
3723
3724 /**
3725 * Moves the top activity in the input stackId to the pinned stack.
3726 *
3727 * @param stackId Id of stack to move the top activity to pinned stack.
3728 * @param bounds Bounds to use for pinned stack.
3729 *
3730 * @return True if the top activity of the input stack was successfully moved to the pinned
3731 * stack.
3732 */
3733 @Override
3734 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003735 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003736 "moveTopActivityToPinnedStack()");
3737 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003738 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003739 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3740 + "Device doesn't support picture-in-picture mode");
3741 }
3742
3743 long ident = Binder.clearCallingIdentity();
3744 try {
3745 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3746 } finally {
3747 Binder.restoreCallingIdentity(ident);
3748 }
3749 }
3750 }
3751
3752 @Override
3753 public boolean isInMultiWindowMode(IBinder token) {
3754 final long origId = Binder.clearCallingIdentity();
3755 try {
3756 synchronized (mGlobalLock) {
3757 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3758 if (r == null) {
3759 return false;
3760 }
3761 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3762 return r.inMultiWindowMode();
3763 }
3764 } finally {
3765 Binder.restoreCallingIdentity(origId);
3766 }
3767 }
3768
3769 @Override
3770 public boolean isInPictureInPictureMode(IBinder token) {
3771 final long origId = Binder.clearCallingIdentity();
3772 try {
3773 synchronized (mGlobalLock) {
3774 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3775 }
3776 } finally {
3777 Binder.restoreCallingIdentity(origId);
3778 }
3779 }
3780
3781 private boolean isInPictureInPictureMode(ActivityRecord r) {
3782 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3783 || r.getStack().isInStackLocked(r) == null) {
3784 return false;
3785 }
3786
3787 // If we are animating to fullscreen then we have already dispatched the PIP mode
3788 // changed, so we should reflect that check here as well.
3789 final PinnedActivityStack stack = r.getStack();
3790 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3791 return !windowController.isAnimatingBoundsToFullscreen();
3792 }
3793
3794 @Override
3795 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3796 final long origId = Binder.clearCallingIdentity();
3797 try {
3798 synchronized (mGlobalLock) {
3799 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3800 "enterPictureInPictureMode", token, params);
3801
3802 // If the activity is already in picture in picture mode, then just return early
3803 if (isInPictureInPictureMode(r)) {
3804 return true;
3805 }
3806
3807 // Activity supports picture-in-picture, now check that we can enter PiP at this
3808 // point, if it is
3809 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3810 false /* beforeStopping */)) {
3811 return false;
3812 }
3813
3814 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003815 synchronized (mGlobalLock) {
3816 // Only update the saved args from the args that are set
3817 r.pictureInPictureArgs.copyOnlySet(params);
3818 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3819 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3820 // Adjust the source bounds by the insets for the transition down
3821 final Rect sourceBounds = new Rect(
3822 r.pictureInPictureArgs.getSourceRectHint());
3823 mStackSupervisor.moveActivityToPinnedStackLocked(
3824 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3825 final PinnedActivityStack stack = r.getStack();
3826 stack.setPictureInPictureAspectRatio(aspectRatio);
3827 stack.setPictureInPictureActions(actions);
3828 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3829 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3830 logPictureInPictureArgs(params);
3831 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003832 };
3833
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003834 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003835 // If the keyguard is showing or occluded, then try and dismiss it before
3836 // entering picture-in-picture (this will prompt the user to authenticate if the
3837 // device is currently locked).
3838 dismissKeyguard(token, new KeyguardDismissCallback() {
3839 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003840 public void onDismissSucceeded() {
3841 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003842 }
3843 }, null /* message */);
3844 } else {
3845 // Enter picture in picture immediately otherwise
3846 enterPipRunnable.run();
3847 }
3848 return true;
3849 }
3850 } finally {
3851 Binder.restoreCallingIdentity(origId);
3852 }
3853 }
3854
3855 @Override
3856 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3857 final long origId = Binder.clearCallingIdentity();
3858 try {
3859 synchronized (mGlobalLock) {
3860 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3861 "setPictureInPictureParams", token, params);
3862
3863 // Only update the saved args from the args that are set
3864 r.pictureInPictureArgs.copyOnlySet(params);
3865 if (r.inPinnedWindowingMode()) {
3866 // If the activity is already in picture-in-picture, update the pinned stack now
3867 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3868 // be used the next time the activity enters PiP
3869 final PinnedActivityStack stack = r.getStack();
3870 if (!stack.isAnimatingBoundsToFullscreen()) {
3871 stack.setPictureInPictureAspectRatio(
3872 r.pictureInPictureArgs.getAspectRatio());
3873 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3874 }
3875 }
3876 logPictureInPictureArgs(params);
3877 }
3878 } finally {
3879 Binder.restoreCallingIdentity(origId);
3880 }
3881 }
3882
3883 @Override
3884 public int getMaxNumPictureInPictureActions(IBinder token) {
3885 // Currently, this is a static constant, but later, we may change this to be dependent on
3886 // the context of the activity
3887 return 3;
3888 }
3889
3890 private void logPictureInPictureArgs(PictureInPictureParams params) {
3891 if (params.hasSetActions()) {
3892 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3893 params.getActions().size());
3894 }
3895 if (params.hasSetAspectRatio()) {
3896 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3897 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3898 MetricsLogger.action(lm);
3899 }
3900 }
3901
3902 /**
3903 * Checks the state of the system and the activity associated with the given {@param token} to
3904 * verify that picture-in-picture is supported for that activity.
3905 *
3906 * @return the activity record for the given {@param token} if all the checks pass.
3907 */
3908 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3909 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003910 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003911 throw new IllegalStateException(caller
3912 + ": Device doesn't support picture-in-picture mode.");
3913 }
3914
3915 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3916 if (r == null) {
3917 throw new IllegalStateException(caller
3918 + ": Can't find activity for token=" + token);
3919 }
3920
3921 if (!r.supportsPictureInPicture()) {
3922 throw new IllegalStateException(caller
3923 + ": Current activity does not support picture-in-picture.");
3924 }
3925
3926 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003927 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003928 params.getAspectRatio())) {
3929 final float minAspectRatio = mContext.getResources().getFloat(
3930 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3931 final float maxAspectRatio = mContext.getResources().getFloat(
3932 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3933 throw new IllegalArgumentException(String.format(caller
3934 + ": Aspect ratio is too extreme (must be between %f and %f).",
3935 minAspectRatio, maxAspectRatio));
3936 }
3937
3938 // Truncate the number of actions if necessary
3939 params.truncateActions(getMaxNumPictureInPictureActions(token));
3940
3941 return r;
3942 }
3943
3944 @Override
3945 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003946 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003947 synchronized (mGlobalLock) {
3948 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3949 if (r == null) {
3950 throw new IllegalArgumentException("Activity does not exist; token="
3951 + activityToken);
3952 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003953 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003954 }
3955 }
3956
3957 @Override
3958 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3959 Rect tempDockedTaskInsetBounds,
3960 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003961 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003962 long ident = Binder.clearCallingIdentity();
3963 try {
3964 synchronized (mGlobalLock) {
3965 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3966 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3967 PRESERVE_WINDOWS);
3968 }
3969 } finally {
3970 Binder.restoreCallingIdentity(ident);
3971 }
3972 }
3973
3974 @Override
3975 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003976 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003977 final long ident = Binder.clearCallingIdentity();
3978 try {
3979 synchronized (mGlobalLock) {
3980 mStackSupervisor.setSplitScreenResizing(resizing);
3981 }
3982 } finally {
3983 Binder.restoreCallingIdentity(ident);
3984 }
3985 }
3986
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003987 /**
3988 * Check that we have the features required for VR-related API calls, and throw an exception if
3989 * not.
3990 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003991 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 if (!mContext.getPackageManager().hasSystemFeature(
3993 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3994 throw new UnsupportedOperationException("VR mode not supported on this device!");
3995 }
3996 }
3997
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 @Override
3999 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004000 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004001
4002 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4003
4004 ActivityRecord r;
4005 synchronized (mGlobalLock) {
4006 r = ActivityRecord.isInStackLocked(token);
4007 }
4008
4009 if (r == null) {
4010 throw new IllegalArgumentException();
4011 }
4012
4013 int err;
4014 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
4015 VrManagerInternal.NO_ERROR) {
4016 return err;
4017 }
4018
4019 // Clear the binder calling uid since this path may call moveToTask().
4020 final long callingId = Binder.clearCallingIdentity();
4021 try {
4022 synchronized (mGlobalLock) {
4023 r.requestedVrComponent = (enabled) ? packageName : null;
4024
4025 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004026 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004027 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004028 }
4029 return 0;
4030 }
4031 } finally {
4032 Binder.restoreCallingIdentity(callingId);
4033 }
4034 }
4035
4036 @Override
4037 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4038 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4039 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004040 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004041 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4042 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4043 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004044 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 || activity.voiceSession != null) {
4046 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4047 return;
4048 }
4049 if (activity.pendingVoiceInteractionStart) {
4050 Slog.w(TAG, "Pending start of voice interaction already.");
4051 return;
4052 }
4053 activity.pendingVoiceInteractionStart = true;
4054 }
4055 LocalServices.getService(VoiceInteractionManagerInternal.class)
4056 .startLocalVoiceInteraction(callingActivity, options);
4057 }
4058
4059 @Override
4060 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4061 LocalServices.getService(VoiceInteractionManagerInternal.class)
4062 .stopLocalVoiceInteraction(callingActivity);
4063 }
4064
4065 @Override
4066 public boolean supportsLocalVoiceInteraction() {
4067 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4068 .supportsLocalVoiceInteraction();
4069 }
4070
4071 /** Notifies all listeners when the pinned stack animation starts. */
4072 @Override
4073 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004074 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004075 }
4076
4077 /** Notifies all listeners when the pinned stack animation ends. */
4078 @Override
4079 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004080 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004081 }
4082
4083 @Override
4084 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004085 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 final long ident = Binder.clearCallingIdentity();
4087 try {
4088 synchronized (mGlobalLock) {
4089 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4090 }
4091 } finally {
4092 Binder.restoreCallingIdentity(ident);
4093 }
4094 }
4095
4096 @Override
4097 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004098 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004099
4100 synchronized (mGlobalLock) {
4101 // Check if display is initialized in AM.
4102 if (!mStackSupervisor.isDisplayAdded(displayId)) {
4103 // Call might come when display is not yet added or has already been removed.
4104 if (DEBUG_CONFIGURATION) {
4105 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4106 + displayId);
4107 }
4108 return false;
4109 }
4110
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004111 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004112 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004113 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004114 }
4115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004116 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004117 final Message msg = PooledLambda.obtainMessage(
4118 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4119 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 }
4121
4122 final long origId = Binder.clearCallingIdentity();
4123 try {
4124 if (values != null) {
4125 Settings.System.clearConfiguration(values);
4126 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004127 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004128 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4129 return mTmpUpdateConfigurationResult.changes != 0;
4130 } finally {
4131 Binder.restoreCallingIdentity(origId);
4132 }
4133 }
4134 }
4135
4136 @Override
4137 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004138 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004139
4140 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004141 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004142 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004143 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 }
4145
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004146 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004147 final Message msg = PooledLambda.obtainMessage(
4148 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4149 DEFAULT_DISPLAY);
4150 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004151 }
4152
4153 final long origId = Binder.clearCallingIdentity();
4154 try {
4155 if (values != null) {
4156 Settings.System.clearConfiguration(values);
4157 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 UserHandle.USER_NULL, false /* deferResume */,
4160 mTmpUpdateConfigurationResult);
4161 return mTmpUpdateConfigurationResult.changes != 0;
4162 } finally {
4163 Binder.restoreCallingIdentity(origId);
4164 }
4165 }
4166 }
4167
4168 @Override
4169 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4170 CharSequence message) {
4171 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004172 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4174 }
4175 final long callingId = Binder.clearCallingIdentity();
4176 try {
4177 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004178 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004179 }
4180 } finally {
4181 Binder.restoreCallingIdentity(callingId);
4182 }
4183 }
4184
4185 @Override
4186 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004187 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188 "cancelTaskWindowTransition()");
4189 final long ident = Binder.clearCallingIdentity();
4190 try {
4191 synchronized (mGlobalLock) {
4192 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4193 MATCH_TASK_IN_STACKS_ONLY);
4194 if (task == null) {
4195 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4196 return;
4197 }
4198 task.cancelWindowTransition();
4199 }
4200 } finally {
4201 Binder.restoreCallingIdentity(ident);
4202 }
4203 }
4204
4205 @Override
4206 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004207 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004208 final long ident = Binder.clearCallingIdentity();
4209 try {
4210 final TaskRecord task;
4211 synchronized (mGlobalLock) {
4212 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4213 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4214 if (task == null) {
4215 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4216 return null;
4217 }
4218 }
4219 // Don't call this while holding the lock as this operation might hit the disk.
4220 return task.getSnapshot(reducedResolution);
4221 } finally {
4222 Binder.restoreCallingIdentity(ident);
4223 }
4224 }
4225
4226 @Override
4227 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4228 synchronized (mGlobalLock) {
4229 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4230 if (r == null) {
4231 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4232 + token);
4233 return;
4234 }
4235 final long origId = Binder.clearCallingIdentity();
4236 try {
4237 r.setDisablePreviewScreenshots(disable);
4238 } finally {
4239 Binder.restoreCallingIdentity(origId);
4240 }
4241 }
4242 }
4243
4244 /** Return the user id of the last resumed activity. */
4245 @Override
4246 public @UserIdInt
4247 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004248 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004249 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4250 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004251 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004252 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004253 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004254 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004255 }
4256 }
4257
4258 @Override
4259 public void updateLockTaskFeatures(int userId, int flags) {
4260 final int callingUid = Binder.getCallingUid();
4261 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004262 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004263 "updateLockTaskFeatures()");
4264 }
4265 synchronized (mGlobalLock) {
4266 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4267 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004268 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004269 }
4270 }
4271
4272 @Override
4273 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4274 synchronized (mGlobalLock) {
4275 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4276 if (r == null) {
4277 return;
4278 }
4279 final long origId = Binder.clearCallingIdentity();
4280 try {
4281 r.setShowWhenLocked(showWhenLocked);
4282 } finally {
4283 Binder.restoreCallingIdentity(origId);
4284 }
4285 }
4286 }
4287
4288 @Override
4289 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4290 synchronized (mGlobalLock) {
4291 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4292 if (r == null) {
4293 return;
4294 }
4295 final long origId = Binder.clearCallingIdentity();
4296 try {
4297 r.setTurnScreenOn(turnScreenOn);
4298 } finally {
4299 Binder.restoreCallingIdentity(origId);
4300 }
4301 }
4302 }
4303
4304 @Override
4305 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 "registerRemoteAnimations");
4308 definition.setCallingPid(Binder.getCallingPid());
4309 synchronized (mGlobalLock) {
4310 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4311 if (r == null) {
4312 return;
4313 }
4314 final long origId = Binder.clearCallingIdentity();
4315 try {
4316 r.registerRemoteAnimations(definition);
4317 } finally {
4318 Binder.restoreCallingIdentity(origId);
4319 }
4320 }
4321 }
4322
4323 @Override
4324 public void registerRemoteAnimationForNextActivityStart(String packageName,
4325 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004326 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327 "registerRemoteAnimationForNextActivityStart");
4328 adapter.setCallingPid(Binder.getCallingPid());
4329 synchronized (mGlobalLock) {
4330 final long origId = Binder.clearCallingIdentity();
4331 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004332 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004333 packageName, adapter);
4334 } finally {
4335 Binder.restoreCallingIdentity(origId);
4336 }
4337 }
4338 }
4339
4340 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4341 @Override
4342 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4343 synchronized (mGlobalLock) {
4344 final long origId = Binder.clearCallingIdentity();
4345 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004346 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004347 } finally {
4348 Binder.restoreCallingIdentity(origId);
4349 }
4350 }
4351 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004352
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004353 @Override
4354 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004355 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004356 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004357 final int pid = Binder.getCallingPid();
4358 final WindowProcessController wpc = mPidMap.get(pid);
4359 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004360 }
4361 }
4362
4363 @Override
4364 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004365 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004366 != PERMISSION_GRANTED) {
4367 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4368 + Binder.getCallingPid()
4369 + ", uid=" + Binder.getCallingUid()
4370 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4371 Slog.w(TAG, msg);
4372 throw new SecurityException(msg);
4373 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004374 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004375 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004376 final int pid = Binder.getCallingPid();
4377 final WindowProcessController proc = mPidMap.get(pid);
4378 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004379 }
4380 }
4381
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004382 @Override
4383 public void stopAppSwitches() {
4384 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4385 synchronized (mGlobalLock) {
4386 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4387 mDidAppSwitch = false;
4388 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4389 }
4390 }
4391
4392 @Override
4393 public void resumeAppSwitches() {
4394 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4395 synchronized (mGlobalLock) {
4396 // Note that we don't execute any pending app switches... we will
4397 // let those wait until either the timeout, or the next start
4398 // activity request.
4399 mAppSwitchesAllowedTime = 0;
4400 }
4401 }
4402
4403 void onStartActivitySetDidAppSwitch() {
4404 if (mDidAppSwitch) {
4405 // This is the second allowed switch since we stopped switches, so now just generally
4406 // allow switches. Use case:
4407 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4408 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4409 // anyone to switch again).
4410 mAppSwitchesAllowedTime = 0;
4411 } else {
4412 mDidAppSwitch = true;
4413 }
4414 }
4415
4416 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004417 boolean shouldDisableNonVrUiLocked() {
4418 return mVrController.shouldDisableNonVrUiLocked();
4419 }
4420
Wale Ogunwale53783742018-09-16 10:21:51 -07004421 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004422 // VR apps are expected to run in a main display. If an app is turning on VR for
4423 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4424 // fullscreen stack before enabling VR Mode.
4425 // TODO: The goal of this code is to keep the VR app on the main display. When the
4426 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4427 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4428 // option would be a better choice here.
4429 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4430 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4431 + " to main stack for VR");
4432 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4433 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4434 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4435 }
4436 mH.post(() -> {
4437 if (!mVrController.onVrModeChanged(r)) {
4438 return;
4439 }
4440 synchronized (mGlobalLock) {
4441 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4442 mWindowManager.disableNonVrUi(disableNonVrUi);
4443 if (disableNonVrUi) {
4444 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4445 // then remove the pinned stack.
4446 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4447 }
4448 }
4449 });
4450 }
4451
Wale Ogunwale53783742018-09-16 10:21:51 -07004452 @Override
4453 public int getPackageScreenCompatMode(String packageName) {
4454 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4455 synchronized (mGlobalLock) {
4456 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4457 }
4458 }
4459
4460 @Override
4461 public void setPackageScreenCompatMode(String packageName, int mode) {
4462 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4463 "setPackageScreenCompatMode");
4464 synchronized (mGlobalLock) {
4465 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4466 }
4467 }
4468
4469 @Override
4470 public boolean getPackageAskScreenCompat(String packageName) {
4471 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4472 synchronized (mGlobalLock) {
4473 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4474 }
4475 }
4476
4477 @Override
4478 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4479 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4480 "setPackageAskScreenCompat");
4481 synchronized (mGlobalLock) {
4482 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4483 }
4484 }
4485
Wale Ogunwale64258362018-10-16 15:13:37 -07004486 public static String relaunchReasonToString(int relaunchReason) {
4487 switch (relaunchReason) {
4488 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4489 return "window_resize";
4490 case RELAUNCH_REASON_FREE_RESIZE:
4491 return "free_resize";
4492 default:
4493 return null;
4494 }
4495 }
4496
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004497 ActivityStack getTopDisplayFocusedStack() {
4498 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004499 }
4500
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004501 /** Pokes the task persister. */
4502 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4503 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4504 }
4505
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004506 boolean isKeyguardLocked() {
4507 return mKeyguardController.isKeyguardLocked();
4508 }
4509
Wale Ogunwale31913b52018-10-13 08:29:31 -07004510 void dumpLastANRLocked(PrintWriter pw) {
4511 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4512 if (mLastANRState == null) {
4513 pw.println(" <no ANR has occurred since boot>");
4514 } else {
4515 pw.println(mLastANRState);
4516 }
4517 }
4518
4519 void dumpLastANRTracesLocked(PrintWriter pw) {
4520 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4521
4522 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4523 if (ArrayUtils.isEmpty(files)) {
4524 pw.println(" <no ANR has occurred since boot>");
4525 return;
4526 }
4527 // Find the latest file.
4528 File latest = null;
4529 for (File f : files) {
4530 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4531 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004532 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004533 }
4534 pw.print("File: ");
4535 pw.print(latest.getName());
4536 pw.println();
4537 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4538 String line;
4539 while ((line = in.readLine()) != null) {
4540 pw.println(line);
4541 }
4542 } catch (IOException e) {
4543 pw.print("Unable to read: ");
4544 pw.print(e);
4545 pw.println();
4546 }
4547 }
4548
4549 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4550 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4551 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4552 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4553 }
4554
4555 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4556 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4557 pw.println(header);
4558
4559 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4560 dumpPackage);
4561 boolean needSep = printedAnything;
4562
4563 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4564 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4565 " ResumedActivity: ");
4566 if (printed) {
4567 printedAnything = true;
4568 needSep = false;
4569 }
4570
4571 if (dumpPackage == null) {
4572 if (needSep) {
4573 pw.println();
4574 }
4575 printedAnything = true;
4576 mStackSupervisor.dump(pw, " ");
4577 }
4578
4579 if (!printedAnything) {
4580 pw.println(" (nothing)");
4581 }
4582 }
4583
4584 void dumpActivityContainersLocked(PrintWriter pw) {
4585 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4586 mStackSupervisor.dumpChildrenNames(pw, " ");
4587 pw.println(" ");
4588 }
4589
4590 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4591 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4592 getActivityStartController().dump(pw, "", dumpPackage);
4593 }
4594
4595 /**
4596 * There are three things that cmd can be:
4597 * - a flattened component name that matches an existing activity
4598 * - the cmd arg isn't the flattened component name of an existing activity:
4599 * dump all activity whose component contains the cmd as a substring
4600 * - A hex number of the ActivityRecord object instance.
4601 *
4602 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4603 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4604 */
4605 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4606 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4607 ArrayList<ActivityRecord> activities;
4608
4609 synchronized (mGlobalLock) {
4610 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4611 dumpFocusedStackOnly);
4612 }
4613
4614 if (activities.size() <= 0) {
4615 return false;
4616 }
4617
4618 String[] newArgs = new String[args.length - opti];
4619 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4620
4621 TaskRecord lastTask = null;
4622 boolean needSep = false;
4623 for (int i = activities.size() - 1; i >= 0; i--) {
4624 ActivityRecord r = activities.get(i);
4625 if (needSep) {
4626 pw.println();
4627 }
4628 needSep = true;
4629 synchronized (mGlobalLock) {
4630 final TaskRecord task = r.getTask();
4631 if (lastTask != task) {
4632 lastTask = task;
4633 pw.print("TASK "); pw.print(lastTask.affinity);
4634 pw.print(" id="); pw.print(lastTask.taskId);
4635 pw.print(" userId="); pw.println(lastTask.userId);
4636 if (dumpAll) {
4637 lastTask.dump(pw, " ");
4638 }
4639 }
4640 }
4641 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4642 }
4643 return true;
4644 }
4645
4646 /**
4647 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4648 * there is a thread associated with the activity.
4649 */
4650 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4651 final ActivityRecord r, String[] args, boolean dumpAll) {
4652 String innerPrefix = prefix + " ";
4653 synchronized (mGlobalLock) {
4654 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4655 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4656 pw.print(" pid=");
4657 if (r.hasProcess()) pw.println(r.app.getPid());
4658 else pw.println("(not running)");
4659 if (dumpAll) {
4660 r.dump(pw, innerPrefix);
4661 }
4662 }
4663 if (r.attachedToProcess()) {
4664 // flush anything that is already in the PrintWriter since the thread is going
4665 // to write to the file descriptor directly
4666 pw.flush();
4667 try {
4668 TransferPipe tp = new TransferPipe();
4669 try {
4670 r.app.getThread().dumpActivity(tp.getWriteFd(),
4671 r.appToken, innerPrefix, args);
4672 tp.go(fd);
4673 } finally {
4674 tp.kill();
4675 }
4676 } catch (IOException e) {
4677 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4678 } catch (RemoteException e) {
4679 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4680 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004681 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004682 }
4683
Wale Ogunwalef6733932018-06-27 05:14:34 -07004684 void writeSleepStateToProto(ProtoOutputStream proto) {
4685 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4686 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4687 st.toString());
4688 }
4689
4690 if (mRunningVoice != null) {
4691 final long vrToken = proto.start(
4692 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4693 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4694 mRunningVoice.toString());
4695 mVoiceWakeLock.writeToProto(
4696 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4697 proto.end(vrToken);
4698 }
4699
4700 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4701 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4702 mShuttingDown);
4703 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004704 }
4705
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004706 int getCurrentUserId() {
4707 return mAmInternal.getCurrentUserId();
4708 }
4709
4710 private void enforceNotIsolatedCaller(String caller) {
4711 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4712 throw new SecurityException("Isolated process not allowed to call " + caller);
4713 }
4714 }
4715
Wale Ogunwalef6733932018-06-27 05:14:34 -07004716 public Configuration getConfiguration() {
4717 Configuration ci;
4718 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004719 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004720 ci.userSetLocale = false;
4721 }
4722 return ci;
4723 }
4724
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004725 /**
4726 * Current global configuration information. Contains general settings for the entire system,
4727 * also corresponds to the merged configuration of the default display.
4728 */
4729 Configuration getGlobalConfiguration() {
4730 return mStackSupervisor.getConfiguration();
4731 }
4732
4733 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4734 boolean initLocale) {
4735 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4736 }
4737
4738 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4739 boolean initLocale, boolean deferResume) {
4740 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4741 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4742 UserHandle.USER_NULL, deferResume);
4743 }
4744
Wale Ogunwale59507092018-10-29 09:00:30 -07004745 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004746 final long origId = Binder.clearCallingIdentity();
4747 try {
4748 synchronized (mGlobalLock) {
4749 updateConfigurationLocked(values, null, false, true, userId,
4750 false /* deferResume */);
4751 }
4752 } finally {
4753 Binder.restoreCallingIdentity(origId);
4754 }
4755 }
4756
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004757 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4758 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4759 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4760 deferResume, null /* result */);
4761 }
4762
4763 /**
4764 * Do either or both things: (1) change the current configuration, and (2)
4765 * make sure the given activity is running with the (now) current
4766 * configuration. Returns true if the activity has been left running, or
4767 * false if <var>starting</var> is being destroyed to match the new
4768 * configuration.
4769 *
4770 * @param userId is only used when persistent parameter is set to true to persist configuration
4771 * for that particular user
4772 */
4773 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4774 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4775 ActivityTaskManagerService.UpdateConfigurationResult result) {
4776 int changes = 0;
4777 boolean kept = true;
4778
4779 if (mWindowManager != null) {
4780 mWindowManager.deferSurfaceLayout();
4781 }
4782 try {
4783 if (values != null) {
4784 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4785 deferResume);
4786 }
4787
4788 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4789 } finally {
4790 if (mWindowManager != null) {
4791 mWindowManager.continueSurfaceLayout();
4792 }
4793 }
4794
4795 if (result != null) {
4796 result.changes = changes;
4797 result.activityRelaunched = !kept;
4798 }
4799 return kept;
4800 }
4801
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004802 /** Update default (global) configuration and notify listeners about changes. */
4803 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4804 boolean persistent, int userId, boolean deferResume) {
4805 mTempConfig.setTo(getGlobalConfiguration());
4806 final int changes = mTempConfig.updateFrom(values);
4807 if (changes == 0) {
4808 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4809 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4810 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4811 // (even if there are no actual changes) to unfreeze the window.
4812 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4813 return 0;
4814 }
4815
4816 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4817 "Updating global configuration to: " + values);
4818
4819 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4820 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4821 values.colorMode,
4822 values.densityDpi,
4823 values.fontScale,
4824 values.hardKeyboardHidden,
4825 values.keyboard,
4826 values.keyboardHidden,
4827 values.mcc,
4828 values.mnc,
4829 values.navigation,
4830 values.navigationHidden,
4831 values.orientation,
4832 values.screenHeightDp,
4833 values.screenLayout,
4834 values.screenWidthDp,
4835 values.smallestScreenWidthDp,
4836 values.touchscreen,
4837 values.uiMode);
4838
4839
4840 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4841 final LocaleList locales = values.getLocales();
4842 int bestLocaleIndex = 0;
4843 if (locales.size() > 1) {
4844 if (mSupportedSystemLocales == null) {
4845 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4846 }
4847 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4848 }
4849 SystemProperties.set("persist.sys.locale",
4850 locales.get(bestLocaleIndex).toLanguageTag());
4851 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004852
4853 final Message m = PooledLambda.obtainMessage(
4854 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4855 locales.get(bestLocaleIndex));
4856 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004857 }
4858
Yunfan Chen75157d72018-07-27 14:47:21 +09004859 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004860
4861 // Update stored global config and notify everyone about the change.
4862 mStackSupervisor.onConfigurationChanged(mTempConfig);
4863
4864 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4865 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004866 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004867
4868 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004869 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004870
4871 AttributeCache ac = AttributeCache.instance();
4872 if (ac != null) {
4873 ac.updateConfiguration(mTempConfig);
4874 }
4875
4876 // Make sure all resources in our process are updated right now, so that anyone who is going
4877 // to retrieve resource values after we return will be sure to get the new ones. This is
4878 // especially important during boot, where the first config change needs to guarantee all
4879 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004880 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004881
4882 // We need another copy of global config because we're scheduling some calls instead of
4883 // running them in place. We need to be sure that object we send will be handled unchanged.
4884 final Configuration configCopy = new Configuration(mTempConfig);
4885 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004886 final Message msg = PooledLambda.obtainMessage(
4887 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4888 this, userId, configCopy);
4889 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004890 }
4891
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004892 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004893 final int pid = mPidMap.keyAt(i);
4894 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004895 if (DEBUG_CONFIGURATION) {
4896 Slog.v(TAG_CONFIGURATION, "Update process config of "
4897 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004898 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004899 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004900 }
4901
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004902 final Message msg = PooledLambda.obtainMessage(
4903 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4904 mAmInternal, changes, initLocale);
4905 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004906
4907 // Override configuration of the default display duplicates global config, so we need to
4908 // update it also. This will also notify WindowManager about changes.
4909 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4910 DEFAULT_DISPLAY);
4911
4912 return changes;
4913 }
4914
4915 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4916 boolean deferResume, int displayId) {
4917 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4918 displayId, null /* result */);
4919 }
4920
4921 /**
4922 * Updates override configuration specific for the selected display. If no config is provided,
4923 * new one will be computed in WM based on current display info.
4924 */
4925 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4926 ActivityRecord starting, boolean deferResume, int displayId,
4927 ActivityTaskManagerService.UpdateConfigurationResult result) {
4928 int changes = 0;
4929 boolean kept = true;
4930
4931 if (mWindowManager != null) {
4932 mWindowManager.deferSurfaceLayout();
4933 }
4934 try {
4935 if (values != null) {
4936 if (displayId == DEFAULT_DISPLAY) {
4937 // Override configuration of the default display duplicates global config, so
4938 // we're calling global config update instead for default display. It will also
4939 // apply the correct override config.
4940 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4941 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4942 } else {
4943 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4944 }
4945 }
4946
4947 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4948 } finally {
4949 if (mWindowManager != null) {
4950 mWindowManager.continueSurfaceLayout();
4951 }
4952 }
4953
4954 if (result != null) {
4955 result.changes = changes;
4956 result.activityRelaunched = !kept;
4957 }
4958 return kept;
4959 }
4960
4961 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4962 int displayId) {
4963 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4964 final int changes = mTempConfig.updateFrom(values);
4965 if (changes != 0) {
4966 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4967 + mTempConfig + " for displayId=" + displayId);
4968 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4969
4970 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4971 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004972 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004973
Wale Ogunwale5c918702018-10-18 11:06:33 -07004974 // Post message to start process to avoid possible deadlock of calling into AMS with
4975 // the ATMS lock held.
4976 final Message msg = PooledLambda.obtainMessage(
4977 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4978 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4979 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004980 }
4981 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004982 return changes;
4983 }
4984
Wale Ogunwalef6733932018-06-27 05:14:34 -07004985 private void updateEventDispatchingLocked(boolean booted) {
4986 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4987 }
4988
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004989 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4990 final ContentResolver resolver = mContext.getContentResolver();
4991 Settings.System.putConfigurationForUser(resolver, config, userId);
4992 }
4993
4994 private void sendLocaleToMountDaemonMsg(Locale l) {
4995 try {
4996 IBinder service = ServiceManager.getService("mount");
4997 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
4998 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
4999 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5000 } catch (RemoteException e) {
5001 Log.e(TAG, "Error storing locale for decryption UI", e);
5002 }
5003 }
5004
Alison Cichowlas3e340502018-08-07 17:15:01 -04005005 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5006 mStartActivitySources.remove(permissionToken);
5007 mExpiredStartAsCallerTokens.add(permissionToken);
5008 }
5009
5010 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5011 mExpiredStartAsCallerTokens.remove(permissionToken);
5012 }
5013
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005014 boolean isActivityStartsLoggingEnabled() {
5015 return mAmInternal.isActivityStartsLoggingEnabled();
5016 }
5017
Wale Ogunwalef6733932018-06-27 05:14:34 -07005018 void enableScreenAfterBoot(boolean booted) {
5019 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5020 SystemClock.uptimeMillis());
5021 mWindowManager.enableScreenAfterBoot();
5022
5023 synchronized (mGlobalLock) {
5024 updateEventDispatchingLocked(booted);
5025 }
5026 }
5027
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005028 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5029 if (r == null || !r.hasProcess()) {
5030 return KEY_DISPATCHING_TIMEOUT_MS;
5031 }
5032 return getInputDispatchingTimeoutLocked(r.app);
5033 }
5034
5035 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005036 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005037 }
5038
Wale Ogunwalef6733932018-06-27 05:14:34 -07005039 /**
5040 * Decide based on the configuration whether we should show the ANR,
5041 * crash, etc dialogs. The idea is that if there is no affordance to
5042 * press the on-screen buttons, or the user experience would be more
5043 * greatly impacted than the crash itself, we shouldn't show the dialog.
5044 *
5045 * A thought: SystemUI might also want to get told about this, the Power
5046 * dialog / global actions also might want different behaviors.
5047 */
5048 private void updateShouldShowDialogsLocked(Configuration config) {
5049 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5050 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5051 && config.navigation == Configuration.NAVIGATION_NONAV);
5052 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5053 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5054 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5055 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5056 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5057 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5058 HIDE_ERROR_DIALOGS, 0) != 0;
5059 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5060 }
5061
5062 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5063 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5064 FONT_SCALE, 1.0f, userId);
5065
5066 synchronized (this) {
5067 if (getGlobalConfiguration().fontScale == scaleFactor) {
5068 return;
5069 }
5070
5071 final Configuration configuration
5072 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5073 configuration.fontScale = scaleFactor;
5074 updatePersistentConfiguration(configuration, userId);
5075 }
5076 }
5077
5078 // Actually is sleeping or shutting down or whatever else in the future
5079 // is an inactive state.
5080 boolean isSleepingOrShuttingDownLocked() {
5081 return isSleepingLocked() || mShuttingDown;
5082 }
5083
5084 boolean isSleepingLocked() {
5085 return mSleeping;
5086 }
5087
Riddle Hsu16567132018-08-16 21:37:47 +08005088 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005089 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
5090 final TaskRecord task = r.getTask();
5091 if (task.isActivityTypeStandard()) {
5092 if (mCurAppTimeTracker != r.appTimeTracker) {
5093 // We are switching app tracking. Complete the current one.
5094 if (mCurAppTimeTracker != null) {
5095 mCurAppTimeTracker.stop();
5096 mH.obtainMessage(
5097 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
5098 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
5099 mCurAppTimeTracker = null;
5100 }
5101 if (r.appTimeTracker != null) {
5102 mCurAppTimeTracker = r.appTimeTracker;
5103 startTimeTrackingFocusedActivityLocked();
5104 }
5105 } else {
5106 startTimeTrackingFocusedActivityLocked();
5107 }
5108 } else {
5109 r.appTimeTracker = null;
5110 }
5111 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5112 // TODO: Probably not, because we don't want to resume voice on switching
5113 // back to this activity
5114 if (task.voiceInteractor != null) {
5115 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5116 } else {
5117 finishRunningVoiceLocked();
5118
5119 if (mLastResumedActivity != null) {
5120 final IVoiceInteractionSession session;
5121
5122 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5123 if (lastResumedActivityTask != null
5124 && lastResumedActivityTask.voiceSession != null) {
5125 session = lastResumedActivityTask.voiceSession;
5126 } else {
5127 session = mLastResumedActivity.voiceSession;
5128 }
5129
5130 if (session != null) {
5131 // We had been in a voice interaction session, but now focused has
5132 // move to something different. Just finish the session, we can't
5133 // return to it and retain the proper state and synchronization with
5134 // the voice interaction service.
5135 finishVoiceTask(session);
5136 }
5137 }
5138 }
5139
5140 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5141 mAmInternal.sendForegroundProfileChanged(r.userId);
5142 }
5143 updateResumedAppTrace(r);
5144 mLastResumedActivity = r;
5145
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005146 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005147
5148 applyUpdateLockStateLocked(r);
5149 applyUpdateVrModeLocked(r);
5150
5151 EventLogTags.writeAmSetResumedActivity(
5152 r == null ? -1 : r.userId,
5153 r == null ? "NULL" : r.shortComponentName,
5154 reason);
5155 }
5156
5157 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5158 synchronized (mGlobalLock) {
5159 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5160 updateSleepIfNeededLocked();
5161 return token;
5162 }
5163 }
5164
5165 void updateSleepIfNeededLocked() {
5166 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5167 final boolean wasSleeping = mSleeping;
5168 boolean updateOomAdj = false;
5169
5170 if (!shouldSleep) {
5171 // If wasSleeping is true, we need to wake up activity manager state from when
5172 // we started sleeping. In either case, we need to apply the sleep tokens, which
5173 // will wake up stacks or put them to sleep as appropriate.
5174 if (wasSleeping) {
5175 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005176 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5177 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005178 startTimeTrackingFocusedActivityLocked();
5179 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5180 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5181 }
5182 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5183 if (wasSleeping) {
5184 updateOomAdj = true;
5185 }
5186 } else if (!mSleeping && shouldSleep) {
5187 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005188 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5189 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005190 if (mCurAppTimeTracker != null) {
5191 mCurAppTimeTracker.stop();
5192 }
5193 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5194 mStackSupervisor.goingToSleepLocked();
5195 updateResumedAppTrace(null /* resumed */);
5196 updateOomAdj = true;
5197 }
5198 if (updateOomAdj) {
5199 mH.post(mAmInternal::updateOomAdj);
5200 }
5201 }
5202
5203 void updateOomAdj() {
5204 mH.post(mAmInternal::updateOomAdj);
5205 }
5206
Wale Ogunwale53783742018-09-16 10:21:51 -07005207 void updateCpuStats() {
5208 mH.post(mAmInternal::updateCpuStats);
5209 }
5210
5211 void updateUsageStats(ActivityRecord component, boolean resumed) {
5212 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5213 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5214 mH.sendMessage(m);
5215 }
5216
5217 void setBooting(boolean booting) {
5218 mAmInternal.setBooting(booting);
5219 }
5220
5221 boolean isBooting() {
5222 return mAmInternal.isBooting();
5223 }
5224
5225 void setBooted(boolean booted) {
5226 mAmInternal.setBooted(booted);
5227 }
5228
5229 boolean isBooted() {
5230 return mAmInternal.isBooted();
5231 }
5232
5233 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5234 mH.post(() -> {
5235 if (finishBooting) {
5236 mAmInternal.finishBooting();
5237 }
5238 if (enableScreen) {
5239 mInternal.enableScreenAfterBoot(isBooted());
5240 }
5241 });
5242 }
5243
5244 void setHeavyWeightProcess(ActivityRecord root) {
5245 mHeavyWeightProcess = root.app;
5246 final Message m = PooledLambda.obtainMessage(
5247 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5248 root.app, root.intent, root.userId);
5249 mH.sendMessage(m);
5250 }
5251
5252 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5253 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5254 return;
5255 }
5256
5257 mHeavyWeightProcess = null;
5258 final Message m = PooledLambda.obtainMessage(
5259 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5260 proc.mUserId);
5261 mH.sendMessage(m);
5262 }
5263
5264 private void cancelHeavyWeightProcessNotification(int userId) {
5265 final INotificationManager inm = NotificationManager.getService();
5266 if (inm == null) {
5267 return;
5268 }
5269 try {
5270 inm.cancelNotificationWithTag("android", null,
5271 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5272 } catch (RuntimeException e) {
5273 Slog.w(TAG, "Error canceling notification for service", e);
5274 } catch (RemoteException e) {
5275 }
5276
5277 }
5278
5279 private void postHeavyWeightProcessNotification(
5280 WindowProcessController proc, Intent intent, int userId) {
5281 if (proc == null) {
5282 return;
5283 }
5284
5285 final INotificationManager inm = NotificationManager.getService();
5286 if (inm == null) {
5287 return;
5288 }
5289
5290 try {
5291 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5292 String text = mContext.getString(R.string.heavy_weight_notification,
5293 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5294 Notification notification =
5295 new Notification.Builder(context,
5296 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5297 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5298 .setWhen(0)
5299 .setOngoing(true)
5300 .setTicker(text)
5301 .setColor(mContext.getColor(
5302 com.android.internal.R.color.system_notification_accent_color))
5303 .setContentTitle(text)
5304 .setContentText(
5305 mContext.getText(R.string.heavy_weight_notification_detail))
5306 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5307 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5308 new UserHandle(userId)))
5309 .build();
5310 try {
5311 inm.enqueueNotificationWithTag("android", "android", null,
5312 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5313 } catch (RuntimeException e) {
5314 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5315 } catch (RemoteException e) {
5316 }
5317 } catch (PackageManager.NameNotFoundException e) {
5318 Slog.w(TAG, "Unable to create context for heavy notification", e);
5319 }
5320
5321 }
5322
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005323 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5324 IBinder token, String resultWho, int requestCode, Intent[] intents,
5325 String[] resolvedTypes, int flags, Bundle bOptions) {
5326
5327 ActivityRecord activity = null;
5328 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5329 activity = ActivityRecord.isInStackLocked(token);
5330 if (activity == null) {
5331 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5332 return null;
5333 }
5334 if (activity.finishing) {
5335 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5336 return null;
5337 }
5338 }
5339
5340 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5341 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5342 bOptions);
5343 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5344 if (noCreate) {
5345 return rec;
5346 }
5347 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5348 if (activity.pendingResults == null) {
5349 activity.pendingResults = new HashSet<>();
5350 }
5351 activity.pendingResults.add(rec.ref);
5352 }
5353 return rec;
5354 }
5355
Andrii Kulian52d255c2018-07-13 11:32:19 -07005356 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005357 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005358 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005359 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5360 mCurAppTimeTracker.start(resumedActivity.packageName);
5361 }
5362 }
5363
5364 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5365 if (mTracedResumedActivity != null) {
5366 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5367 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5368 }
5369 if (resumed != null) {
5370 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5371 constructResumedTraceName(resumed.packageName), 0);
5372 }
5373 mTracedResumedActivity = resumed;
5374 }
5375
5376 private String constructResumedTraceName(String packageName) {
5377 return "focused app: " + packageName;
5378 }
5379
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005380 /** Applies latest configuration and/or visibility updates if needed. */
5381 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5382 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005383 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005384 // mainStack is null during startup.
5385 if (mainStack != null) {
5386 if (changes != 0 && starting == null) {
5387 // If the configuration changed, and the caller is not already
5388 // in the process of starting an activity, then find the top
5389 // activity to check if its configuration needs to change.
5390 starting = mainStack.topRunningActivityLocked();
5391 }
5392
5393 if (starting != null) {
5394 kept = starting.ensureActivityConfiguration(changes,
5395 false /* preserveWindow */);
5396 // And we need to make sure at this point that all other activities
5397 // are made visible with the correct configuration.
5398 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5399 !PRESERVE_WINDOWS);
5400 }
5401 }
5402
5403 return kept;
5404 }
5405
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005406 void scheduleAppGcsLocked() {
5407 mH.post(() -> mAmInternal.scheduleAppGcs());
5408 }
5409
Wale Ogunwale53783742018-09-16 10:21:51 -07005410 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5411 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5412 }
5413
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005414 /**
5415 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5416 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5417 * on demand.
5418 */
5419 IPackageManager getPackageManager() {
5420 return AppGlobals.getPackageManager();
5421 }
5422
5423 PackageManagerInternal getPackageManagerInternalLocked() {
5424 if (mPmInternal == null) {
5425 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5426 }
5427 return mPmInternal;
5428 }
5429
Wale Ogunwale008163e2018-07-23 23:11:08 -07005430 AppWarnings getAppWarningsLocked() {
5431 return mAppWarnings;
5432 }
5433
Wale Ogunwale214f3482018-10-04 11:00:47 -07005434 Intent getHomeIntent() {
5435 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5436 intent.setComponent(mTopComponent);
5437 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5438 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5439 intent.addCategory(Intent.CATEGORY_HOME);
5440 }
5441 return intent;
5442 }
5443
Wale Ogunwale214f3482018-10-04 11:00:47 -07005444 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5445 if (info == null) return null;
5446 ApplicationInfo newInfo = new ApplicationInfo(info);
5447 newInfo.initForUser(userId);
5448 return newInfo;
5449 }
5450
Wale Ogunwale9c103022018-10-18 07:44:54 -07005451 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005452 if (uid == SYSTEM_UID) {
5453 // The system gets to run in any process. If there are multiple processes with the same
5454 // uid, just pick the first (this should never happen).
5455 final SparseArray<WindowProcessController> procs =
5456 mProcessNames.getMap().get(processName);
5457 if (procs == null) return null;
5458 final int procCount = procs.size();
5459 for (int i = 0; i < procCount; i++) {
5460 final int procUid = procs.keyAt(i);
5461 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5462 // Don't use an app process or different user process for system component.
5463 continue;
5464 }
5465 return procs.valueAt(i);
5466 }
5467 }
5468
5469 return mProcessNames.get(processName, uid);
5470 }
5471
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005472 WindowProcessController getProcessController(IApplicationThread thread) {
5473 if (thread == null) {
5474 return null;
5475 }
5476
5477 final IBinder threadBinder = thread.asBinder();
5478 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5479 for (int i = pmap.size()-1; i >= 0; i--) {
5480 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5481 for (int j = procs.size() - 1; j >= 0; j--) {
5482 final WindowProcessController proc = procs.valueAt(j);
5483 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5484 return proc;
5485 }
5486 }
5487 }
5488
5489 return null;
5490 }
5491
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005492 int getUidStateLocked(int uid) {
5493 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5494 }
5495
Wale Ogunwale9de19442018-10-18 19:05:03 -07005496 /**
5497 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5498 * the whitelist
5499 */
5500 String getPendingTempWhitelistTagForUidLocked(int uid) {
5501 return mPendingTempWhitelist.get(uid);
5502 }
5503
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005504 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5505 if (true || Build.IS_USER) {
5506 return;
5507 }
5508
5509 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5510 StrictMode.allowThreadDiskWrites();
5511 try {
5512 File tracesDir = new File("/data/anr");
5513 File tracesFile = null;
5514 try {
5515 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5516
5517 StringBuilder sb = new StringBuilder();
5518 Time tobj = new Time();
5519 tobj.set(System.currentTimeMillis());
5520 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5521 sb.append(": ");
5522 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5523 sb.append(" since ");
5524 sb.append(msg);
5525 FileOutputStream fos = new FileOutputStream(tracesFile);
5526 fos.write(sb.toString().getBytes());
5527 if (app == null) {
5528 fos.write("\n*** No application process!".getBytes());
5529 }
5530 fos.close();
5531 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5532 } catch (IOException e) {
5533 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5534 return;
5535 }
5536
5537 if (app != null && app.getPid() > 0) {
5538 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5539 firstPids.add(app.getPid());
5540 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5541 }
5542
5543 File lastTracesFile = null;
5544 File curTracesFile = null;
5545 for (int i=9; i>=0; i--) {
5546 String name = String.format(Locale.US, "slow%02d.txt", i);
5547 curTracesFile = new File(tracesDir, name);
5548 if (curTracesFile.exists()) {
5549 if (lastTracesFile != null) {
5550 curTracesFile.renameTo(lastTracesFile);
5551 } else {
5552 curTracesFile.delete();
5553 }
5554 }
5555 lastTracesFile = curTracesFile;
5556 }
5557 tracesFile.renameTo(curTracesFile);
5558 } finally {
5559 StrictMode.setThreadPolicy(oldPolicy);
5560 }
5561 }
5562
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005563 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005564 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005565
5566
Wale Ogunwale98875612018-10-12 07:53:02 -07005567 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5568 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005569
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005570 public H() {
5571 super(DisplayThread.get().getLooper());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005572 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005573
5574 @Override
5575 public void handleMessage(Message msg) {
5576 switch (msg.what) {
5577 case REPORT_TIME_TRACKER_MSG: {
5578 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5579 tracker.deliverResult(mContext);
5580 } break;
5581 }
5582 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005583 }
5584
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005585 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005586 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005587
5588 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005589 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005590 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005591
5592 @Override
5593 public void handleMessage(Message msg) {
5594 switch (msg.what) {
5595 case DISMISS_DIALOG_UI_MSG: {
5596 final Dialog d = (Dialog) msg.obj;
5597 d.dismiss();
5598 break;
5599 }
5600 }
5601 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005602 }
5603
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005604 final class LocalService extends ActivityTaskManagerInternal {
5605 @Override
5606 public SleepToken acquireSleepToken(String tag, int displayId) {
5607 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005608 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005609 }
5610
5611 @Override
5612 public ComponentName getHomeActivityForUser(int userId) {
5613 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005614 ActivityRecord homeActivity =
5615 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005616 return homeActivity == null ? null : homeActivity.realActivity;
5617 }
5618 }
5619
5620 @Override
5621 public void onLocalVoiceInteractionStarted(IBinder activity,
5622 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5623 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005624 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005625 }
5626 }
5627
5628 @Override
5629 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5630 synchronized (mGlobalLock) {
5631 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5632 reasons, timestamp);
5633 }
5634 }
5635
5636 @Override
5637 public void notifyAppTransitionFinished() {
5638 synchronized (mGlobalLock) {
5639 mStackSupervisor.notifyAppTransitionDone();
5640 }
5641 }
5642
5643 @Override
5644 public void notifyAppTransitionCancelled() {
5645 synchronized (mGlobalLock) {
5646 mStackSupervisor.notifyAppTransitionDone();
5647 }
5648 }
5649
5650 @Override
5651 public List<IBinder> getTopVisibleActivities() {
5652 synchronized (mGlobalLock) {
5653 return mStackSupervisor.getTopVisibleActivities();
5654 }
5655 }
5656
5657 @Override
5658 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5659 synchronized (mGlobalLock) {
5660 mStackSupervisor.setDockedStackMinimized(minimized);
5661 }
5662 }
5663
5664 @Override
5665 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5666 Bundle bOptions) {
5667 Preconditions.checkNotNull(intents, "intents");
5668 final String[] resolvedTypes = new String[intents.length];
5669
5670 // UID of the package on user userId.
5671 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5672 // packageUid may not be initialized.
5673 int packageUid = 0;
5674 final long ident = Binder.clearCallingIdentity();
5675
5676 try {
5677 for (int i = 0; i < intents.length; i++) {
5678 resolvedTypes[i] =
5679 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5680 }
5681
5682 packageUid = AppGlobals.getPackageManager().getPackageUid(
5683 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5684 } catch (RemoteException e) {
5685 // Shouldn't happen.
5686 } finally {
5687 Binder.restoreCallingIdentity(ident);
5688 }
5689
5690 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005691 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005692 packageUid, packageName,
5693 intents, resolvedTypes, null /* resultTo */,
5694 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005695 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005696 }
5697 }
5698
5699 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005700 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5701 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5702 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5703 synchronized (mGlobalLock) {
5704 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5705 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5706 originatingPendingIntent);
5707 }
5708 }
5709
5710 @Override
5711 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5712 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5713 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5714 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5715 PendingIntentRecord originatingPendingIntent) {
5716 synchronized (mGlobalLock) {
5717 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5718 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5719 requestCode, startFlags, options, userId, inTask, reason,
5720 validateIncomingUser, originatingPendingIntent);
5721 }
5722 }
5723
5724 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005725 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5726 Intent intent, Bundle options, int userId) {
5727 return ActivityTaskManagerService.this.startActivityAsUser(
5728 caller, callerPacakge, intent,
5729 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5730 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5731 false /*validateIncomingUser*/);
5732 }
5733
5734 @Override
lumark588a3e82018-07-20 18:53:54 +08005735 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005736 synchronized (mGlobalLock) {
5737
5738 // We might change the visibilities here, so prepare an empty app transition which
5739 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005740 final ActivityDisplay activityDisplay =
5741 mStackSupervisor.getActivityDisplay(displayId);
5742 if (activityDisplay == null) {
5743 return;
5744 }
5745 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005746 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005747 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005748 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005749 }
5750 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5751
5752 // If there was a transition set already we don't want to interfere with it as we
5753 // might be starting it too early.
5754 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005755 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005756 }
5757 }
5758 if (callback != null) {
5759 callback.run();
5760 }
5761 }
5762
5763 @Override
5764 public void notifyKeyguardTrustedChanged() {
5765 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005766 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005767 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5768 }
5769 }
5770 }
5771
5772 /**
5773 * Called after virtual display Id is updated by
5774 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5775 * {@param vrVr2dDisplayId}.
5776 */
5777 @Override
5778 public void setVr2dDisplayId(int vr2dDisplayId) {
5779 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5780 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005781 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005782 }
5783 }
5784
5785 @Override
5786 public void setFocusedActivity(IBinder token) {
5787 synchronized (mGlobalLock) {
5788 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5789 if (r == null) {
5790 throw new IllegalArgumentException(
5791 "setFocusedActivity: No activity record matching token=" + token);
5792 }
Louis Chang19443452018-10-09 12:10:21 +08005793 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005794 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005795 }
5796 }
5797 }
5798
5799 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005800 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005801 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005802 }
5803
5804 @Override
5805 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005806 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005807 }
5808
5809 @Override
5810 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005811 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005812 }
5813
5814 @Override
5815 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5816 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5817 }
5818
5819 @Override
5820 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005821 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005822 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005823
5824 @Override
5825 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5826 synchronized (mGlobalLock) {
5827 mActiveVoiceInteractionServiceComponent = component;
5828 }
5829 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005830
5831 @Override
5832 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5833 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5834 return;
5835 }
5836 synchronized (mGlobalLock) {
5837 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5838 if (types == null) {
5839 if (uid < 0) {
5840 return;
5841 }
5842 types = new ArrayMap<>();
5843 mAllowAppSwitchUids.put(userId, types);
5844 }
5845 if (uid < 0) {
5846 types.remove(type);
5847 } else {
5848 types.put(type, uid);
5849 }
5850 }
5851 }
5852
5853 @Override
5854 public void onUserStopped(int userId) {
5855 synchronized (mGlobalLock) {
5856 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5857 mAllowAppSwitchUids.remove(userId);
5858 }
5859 }
5860
5861 @Override
5862 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5863 synchronized (mGlobalLock) {
5864 return ActivityTaskManagerService.this.isGetTasksAllowed(
5865 caller, callingPid, callingUid);
5866 }
5867 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005868
5869 @Override
5870 public void onProcessAdded(WindowProcessController proc) {
5871 synchronized (mGlobalLock) {
5872 mProcessNames.put(proc.mName, proc.mUid, proc);
5873 }
5874 }
5875
5876 @Override
5877 public void onProcessRemoved(String name, int uid) {
5878 synchronized (mGlobalLock) {
5879 mProcessNames.remove(name, uid);
5880 }
5881 }
5882
5883 @Override
5884 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5885 synchronized (mGlobalLock) {
5886 if (proc == mHomeProcess) {
5887 mHomeProcess = null;
5888 }
5889 if (proc == mPreviousProcess) {
5890 mPreviousProcess = null;
5891 }
5892 }
5893 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005894
5895 @Override
5896 public int getTopProcessState() {
5897 synchronized (mGlobalLock) {
5898 return mTopProcessState;
5899 }
5900 }
5901
5902 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005903 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5904 synchronized (mGlobalLock) {
5905 return proc == mHeavyWeightProcess;
5906 }
5907 }
5908
5909 @Override
5910 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5911 synchronized (mGlobalLock) {
5912 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5913 }
5914 }
5915
5916 @Override
5917 public void finishHeavyWeightApp() {
5918 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005919 if (mHeavyWeightProcess != null) {
5920 mHeavyWeightProcess.finishActivities();
5921 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005922 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5923 mHeavyWeightProcess);
5924 }
5925 }
5926
5927 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005928 public boolean isSleeping() {
5929 synchronized (mGlobalLock) {
5930 return isSleepingLocked();
5931 }
5932 }
5933
5934 @Override
5935 public boolean isShuttingDown() {
5936 synchronized (mGlobalLock) {
5937 return mShuttingDown;
5938 }
5939 }
5940
5941 @Override
5942 public boolean shuttingDown(boolean booted, int timeout) {
5943 synchronized (mGlobalLock) {
5944 mShuttingDown = true;
5945 mStackSupervisor.prepareForShutdownLocked();
5946 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005947 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005948 return mStackSupervisor.shutdownLocked(timeout);
5949 }
5950 }
5951
5952 @Override
5953 public void enableScreenAfterBoot(boolean booted) {
5954 synchronized (mGlobalLock) {
5955 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5956 SystemClock.uptimeMillis());
5957 mWindowManager.enableScreenAfterBoot();
5958 updateEventDispatchingLocked(booted);
5959 }
5960 }
5961
5962 @Override
5963 public boolean showStrictModeViolationDialog() {
5964 synchronized (mGlobalLock) {
5965 return mShowDialogs && !mSleeping && !mShuttingDown;
5966 }
5967 }
5968
5969 @Override
5970 public void showSystemReadyErrorDialogsIfNeeded() {
5971 synchronized (mGlobalLock) {
5972 try {
5973 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5974 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5975 + " data partition or your device will be unstable.");
5976 mUiHandler.post(() -> {
5977 if (mShowDialogs) {
5978 AlertDialog d = new BaseErrorDialog(mUiContext);
5979 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5980 d.setCancelable(false);
5981 d.setTitle(mUiContext.getText(R.string.android_system_label));
5982 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5983 d.setButton(DialogInterface.BUTTON_POSITIVE,
5984 mUiContext.getText(R.string.ok),
5985 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5986 d.show();
5987 }
5988 });
5989 }
5990 } catch (RemoteException e) {
5991 }
5992
5993 if (!Build.isBuildConsistent()) {
5994 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5995 mUiHandler.post(() -> {
5996 if (mShowDialogs) {
5997 AlertDialog d = new BaseErrorDialog(mUiContext);
5998 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5999 d.setCancelable(false);
6000 d.setTitle(mUiContext.getText(R.string.android_system_label));
6001 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6002 d.setButton(DialogInterface.BUTTON_POSITIVE,
6003 mUiContext.getText(R.string.ok),
6004 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6005 d.show();
6006 }
6007 });
6008 }
6009 }
6010 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006011
6012 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006013 public void onProcessMapped(int pid, WindowProcessController proc) {
6014 synchronized (mGlobalLock) {
6015 mPidMap.put(pid, proc);
6016 }
6017 }
6018
6019 @Override
6020 public void onProcessUnMapped(int pid) {
6021 synchronized (mGlobalLock) {
6022 mPidMap.remove(pid);
6023 }
6024 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006025
6026 @Override
6027 public void onPackageDataCleared(String name) {
6028 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006029 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006030 mAppWarnings.onPackageDataCleared(name);
6031 }
6032 }
6033
6034 @Override
6035 public void onPackageUninstalled(String name) {
6036 synchronized (mGlobalLock) {
6037 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006038 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006039 }
6040 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006041
6042 @Override
6043 public void onPackageAdded(String name, boolean replacing) {
6044 synchronized (mGlobalLock) {
6045 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6046 }
6047 }
6048
6049 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006050 public void onPackageReplaced(ApplicationInfo aInfo) {
6051 synchronized (mGlobalLock) {
6052 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
6053 }
6054 }
6055
6056 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006057 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6058 synchronized (mGlobalLock) {
6059 return compatibilityInfoForPackageLocked(ai);
6060 }
6061 }
6062
Yunfan Chen75157d72018-07-27 14:47:21 +09006063 /**
6064 * Set the corresponding display information for the process global configuration. To be
6065 * called when we need to show IME on a different display.
6066 *
6067 * @param pid The process id associated with the IME window.
6068 * @param displayId The ID of the display showing the IME.
6069 */
6070 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006071 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006072 if (pid == MY_PID || pid < 0) {
6073 if (DEBUG_CONFIGURATION) {
6074 Slog.w(TAG,
6075 "Trying to update display configuration for system/invalid process.");
6076 }
6077 return;
6078 }
6079 mH.post(() -> {
6080 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006081 final ActivityDisplay activityDisplay =
6082 mStackSupervisor.getActivityDisplay(displayId);
6083 if (activityDisplay == null) {
6084 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006085 if (DEBUG_CONFIGURATION) {
6086 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006087 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006088 }
6089 return;
6090 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006091 final WindowProcessController process = mPidMap.get(pid);
6092 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006093 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006094 Slog.w(TAG, "Trying to update display configuration for invalid "
6095 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006096 }
6097 return;
6098 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006099 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006100 }
6101 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006102
Yunfan Chen75157d72018-07-27 14:47:21 +09006103 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006104
6105 @Override
6106 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6107 int requestCode, int resultCode, Intent data) {
6108 synchronized (mGlobalLock) {
6109 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6110 if (r != null && r.getStack() != null) {
6111 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6112 resultCode, data);
6113 }
6114 }
6115 }
6116
6117 @Override
6118 public void clearPendingResultForActivity(IBinder activityToken,
6119 WeakReference<PendingIntentRecord> pir) {
6120 synchronized (mGlobalLock) {
6121 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6122 if (r != null && r.pendingResults != null) {
6123 r.pendingResults.remove(pir);
6124 }
6125 }
6126 }
6127
6128 @Override
6129 public IIntentSender getIntentSender(int type, String packageName,
6130 int callingUid, int userId, IBinder token, String resultWho,
6131 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6132 Bundle bOptions) {
6133 synchronized (mGlobalLock) {
6134 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6135 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6136 }
6137 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006138
6139 @Override
6140 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6141 synchronized (mGlobalLock) {
6142 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6143 if (r == null) {
6144 return null;
6145 }
6146 if (r.mServiceConnectionsHolder == null) {
6147 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6148 ActivityTaskManagerService.this, r);
6149 }
6150
6151 return r.mServiceConnectionsHolder;
6152 }
6153 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006154
6155 @Override
6156 public Intent getHomeIntent() {
6157 synchronized (mGlobalLock) {
6158 return ActivityTaskManagerService.this.getHomeIntent();
6159 }
6160 }
6161
6162 @Override
6163 public boolean startHomeActivity(int userId, String reason) {
6164 synchronized (mGlobalLock) {
Louis Chang89f43fc2018-10-05 10:59:14 +08006165 return mStackSupervisor.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6166 }
6167 }
6168
6169 @Override
6170 public boolean startHomeOnAllDisplays(int userId, String reason) {
6171 synchronized (mGlobalLock) {
6172 return mStackSupervisor.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006173 }
6174 }
6175
6176 @Override
6177 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6178 synchronized (mGlobalLock) {
6179 if (mFactoryTest == FACTORY_TEST_OFF) {
6180 return false;
6181 }
6182 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6183 && wpc.mName.equals(mTopComponent.getPackageName())) {
6184 return true;
6185 }
6186 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6187 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6188 }
6189 }
6190
6191 @Override
6192 public void updateTopComponentForFactoryTest() {
6193 synchronized (mGlobalLock) {
6194 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6195 return;
6196 }
6197 final ResolveInfo ri = mContext.getPackageManager()
6198 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6199 final CharSequence errorMsg;
6200 if (ri != null) {
6201 final ActivityInfo ai = ri.activityInfo;
6202 final ApplicationInfo app = ai.applicationInfo;
6203 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6204 mTopAction = Intent.ACTION_FACTORY_TEST;
6205 mTopData = null;
6206 mTopComponent = new ComponentName(app.packageName, ai.name);
6207 errorMsg = null;
6208 } else {
6209 errorMsg = mContext.getResources().getText(
6210 com.android.internal.R.string.factorytest_not_system);
6211 }
6212 } else {
6213 errorMsg = mContext.getResources().getText(
6214 com.android.internal.R.string.factorytest_no_action);
6215 }
6216 if (errorMsg == null) {
6217 return;
6218 }
6219
6220 mTopAction = null;
6221 mTopData = null;
6222 mTopComponent = null;
6223 mUiHandler.post(() -> {
6224 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6225 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006226 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006227 });
6228 }
6229 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006230
6231 @Override
6232 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6233 Runnable finishInstrumentationCallback) {
6234 synchronized (mGlobalLock) {
6235 // Remove this application's activities from active lists.
6236 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6237
6238 wpc.clearRecentTasks();
6239 wpc.clearActivities();
6240
6241 if (wpc.isInstrumenting()) {
6242 finishInstrumentationCallback.run();
6243 }
6244
6245 mWindowManager.deferSurfaceLayout();
6246 try {
6247 if (!restarting && hasVisibleActivities
6248 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6249 // If there was nothing to resume, and we are not already restarting this
6250 // process, but there is a visible activity that is hosted by the process...
6251 // then make sure all visible activities are running, taking care of
6252 // restarting this process.
6253 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6254 }
6255 } finally {
6256 mWindowManager.continueSurfaceLayout();
6257 }
6258 }
6259 }
6260
6261 @Override
6262 public void closeSystemDialogs(String reason) {
6263 enforceNotIsolatedCaller("closeSystemDialogs");
6264
6265 final int pid = Binder.getCallingPid();
6266 final int uid = Binder.getCallingUid();
6267 final long origId = Binder.clearCallingIdentity();
6268 try {
6269 synchronized (mGlobalLock) {
6270 // Only allow this from foreground processes, so that background
6271 // applications can't abuse it to prevent system UI from being shown.
6272 if (uid >= FIRST_APPLICATION_UID) {
6273 final WindowProcessController proc = mPidMap.get(pid);
6274 if (!proc.isPerceptible()) {
6275 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6276 + " from background process " + proc);
6277 return;
6278 }
6279 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006280 mWindowManager.closeSystemDialogs(reason);
6281
6282 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006283 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006284 // Call into AM outside the synchronized block.
6285 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006286 } finally {
6287 Binder.restoreCallingIdentity(origId);
6288 }
6289 }
6290
6291 @Override
6292 public void cleanupDisabledPackageComponents(
6293 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6294 synchronized (mGlobalLock) {
6295 // Clean-up disabled activities.
6296 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6297 packageName, disabledClasses, true, false, userId) && booted) {
6298 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6299 mStackSupervisor.scheduleIdleLocked();
6300 }
6301
6302 // Clean-up disabled tasks
6303 getRecentTasks().cleanupDisabledPackageTasksLocked(
6304 packageName, disabledClasses, userId);
6305 }
6306 }
6307
6308 @Override
6309 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6310 int userId) {
6311 synchronized (mGlobalLock) {
6312
6313 boolean didSomething =
6314 getActivityStartController().clearPendingActivityLaunches(packageName);
6315 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6316 null, doit, evenPersistent, userId);
6317 return didSomething;
6318 }
6319 }
6320
6321 @Override
6322 public void resumeTopActivities(boolean scheduleIdle) {
6323 synchronized (mGlobalLock) {
6324 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6325 if (scheduleIdle) {
6326 mStackSupervisor.scheduleIdleLocked();
6327 }
6328 }
6329 }
6330
6331 @Override
6332 public void preBindApplication(WindowProcessController wpc) {
6333 synchronized (mGlobalLock) {
6334 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6335 }
6336 }
6337
6338 @Override
6339 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6340 synchronized (mGlobalLock) {
6341 return mStackSupervisor.attachApplicationLocked(wpc);
6342 }
6343 }
6344
6345 @Override
6346 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6347 try {
6348 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6349 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6350 }
6351 } catch (RemoteException ex) {
6352 throw new SecurityException("Fail to check is caller a privileged app", ex);
6353 }
6354
6355 synchronized (mGlobalLock) {
6356 final long ident = Binder.clearCallingIdentity();
6357 try {
6358 if (mAmInternal.shouldConfirmCredentials(userId)) {
6359 if (mKeyguardController.isKeyguardLocked()) {
6360 // Showing launcher to avoid user entering credential twice.
6361 startHomeActivity(currentUserId, "notifyLockedProfile");
6362 }
6363 mStackSupervisor.lockAllProfileTasks(userId);
6364 }
6365 } finally {
6366 Binder.restoreCallingIdentity(ident);
6367 }
6368 }
6369 }
6370
6371 @Override
6372 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6373 mAmInternal.enforceCallingPermission(
6374 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6375
6376 synchronized (mGlobalLock) {
6377 final long ident = Binder.clearCallingIdentity();
6378 try {
6379 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6380 FLAG_ACTIVITY_TASK_ON_HOME);
6381 ActivityOptions activityOptions = options != null
6382 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006383 final ActivityRecord homeActivity =
6384 mStackSupervisor.getDefaultDisplayHomeActivity();
6385 if (homeActivity != null) {
6386 activityOptions.setLaunchTaskId(homeActivity.getTask().taskId);
6387 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006388 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6389 UserHandle.CURRENT);
6390 } finally {
6391 Binder.restoreCallingIdentity(ident);
6392 }
6393 }
6394 }
6395
6396 @Override
6397 public void writeActivitiesToProto(ProtoOutputStream proto) {
6398 synchronized (mGlobalLock) {
6399 // The output proto of "activity --proto activities"
6400 // is ActivityManagerServiceDumpActivitiesProto
6401 mStackSupervisor.writeToProto(proto,
6402 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6403 }
6404 }
6405
6406 @Override
6407 public void saveANRState(String reason) {
6408 synchronized (mGlobalLock) {
6409 final StringWriter sw = new StringWriter();
6410 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6411 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6412 if (reason != null) {
6413 pw.println(" Reason: " + reason);
6414 }
6415 pw.println();
6416 getActivityStartController().dump(pw, " ", null);
6417 pw.println();
6418 pw.println("-------------------------------------------------------------------------------");
6419 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6420 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6421 "" /* header */);
6422 pw.println();
6423 pw.close();
6424
6425 mLastANRState = sw.toString();
6426 }
6427 }
6428
6429 @Override
6430 public void clearSavedANRState() {
6431 synchronized (mGlobalLock) {
6432 mLastANRState = null;
6433 }
6434 }
6435
6436 @Override
6437 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6438 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6439 synchronized (mGlobalLock) {
6440 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6441 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6442 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6443 dumpLastANRLocked(pw);
6444 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6445 dumpLastANRTracesLocked(pw);
6446 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6447 dumpActivityStarterLocked(pw, dumpPackage);
6448 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6449 dumpActivityContainersLocked(pw);
6450 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6451 if (getRecentTasks() != null) {
6452 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6453 }
6454 }
6455 }
6456 }
6457
6458 @Override
6459 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6460 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6461 int wakefulness) {
6462 synchronized (mGlobalLock) {
6463 if (mHomeProcess != null && (dumpPackage == null
6464 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6465 if (needSep) {
6466 pw.println();
6467 needSep = false;
6468 }
6469 pw.println(" mHomeProcess: " + mHomeProcess);
6470 }
6471 if (mPreviousProcess != null && (dumpPackage == null
6472 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6473 if (needSep) {
6474 pw.println();
6475 needSep = false;
6476 }
6477 pw.println(" mPreviousProcess: " + mPreviousProcess);
6478 }
6479 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6480 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6481 StringBuilder sb = new StringBuilder(128);
6482 sb.append(" mPreviousProcessVisibleTime: ");
6483 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6484 pw.println(sb);
6485 }
6486 if (mHeavyWeightProcess != null && (dumpPackage == null
6487 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6488 if (needSep) {
6489 pw.println();
6490 needSep = false;
6491 }
6492 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6493 }
6494 if (dumpPackage == null) {
6495 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6496 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6497 }
6498 if (dumpAll) {
6499 if (dumpPackage == null) {
6500 pw.println(" mConfigWillChange: "
6501 + getTopDisplayFocusedStack().mConfigWillChange);
6502 }
6503 if (mCompatModePackages.getPackages().size() > 0) {
6504 boolean printed = false;
6505 for (Map.Entry<String, Integer> entry
6506 : mCompatModePackages.getPackages().entrySet()) {
6507 String pkg = entry.getKey();
6508 int mode = entry.getValue();
6509 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6510 continue;
6511 }
6512 if (!printed) {
6513 pw.println(" mScreenCompatPackages:");
6514 printed = true;
6515 }
6516 pw.println(" " + pkg + ": " + mode);
6517 }
6518 }
6519 }
6520
6521 if (dumpPackage == null) {
6522 pw.println(" mWakefulness="
6523 + PowerManagerInternal.wakefulnessToString(wakefulness));
6524 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6525 if (mRunningVoice != null) {
6526 pw.println(" mRunningVoice=" + mRunningVoice);
6527 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6528 }
6529 pw.println(" mSleeping=" + mSleeping);
6530 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6531 pw.println(" mVrController=" + mVrController);
6532 }
6533 if (mCurAppTimeTracker != null) {
6534 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6535 }
6536 if (mAllowAppSwitchUids.size() > 0) {
6537 boolean printed = false;
6538 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6539 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6540 for (int j = 0; j < types.size(); j++) {
6541 if (dumpPackage == null ||
6542 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6543 if (needSep) {
6544 pw.println();
6545 needSep = false;
6546 }
6547 if (!printed) {
6548 pw.println(" mAllowAppSwitchUids:");
6549 printed = true;
6550 }
6551 pw.print(" User ");
6552 pw.print(mAllowAppSwitchUids.keyAt(i));
6553 pw.print(": Type ");
6554 pw.print(types.keyAt(j));
6555 pw.print(" = ");
6556 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6557 pw.println();
6558 }
6559 }
6560 }
6561 }
6562 if (dumpPackage == null) {
6563 if (mController != null) {
6564 pw.println(" mController=" + mController
6565 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6566 }
6567 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6568 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6569 }
6570
6571 return needSep;
6572 }
6573 }
6574
6575 @Override
6576 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6577 synchronized (mGlobalLock) {
6578 if (dumpPackage == null) {
6579 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6580 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6581 writeSleepStateToProto(proto);
6582 if (mController != null) {
6583 final long token = proto.start(CONTROLLER);
6584 proto.write(CONTROLLER, mController.toString());
6585 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6586 proto.end(token);
6587 }
6588 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6589 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6590 }
6591
6592 if (mHomeProcess != null && (dumpPackage == null
6593 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006594 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006595 }
6596
6597 if (mPreviousProcess != null && (dumpPackage == null
6598 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006599 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006600 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6601 }
6602
6603 if (mHeavyWeightProcess != null && (dumpPackage == null
6604 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006605 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006606 }
6607
6608 for (Map.Entry<String, Integer> entry
6609 : mCompatModePackages.getPackages().entrySet()) {
6610 String pkg = entry.getKey();
6611 int mode = entry.getValue();
6612 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6613 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6614 proto.write(PACKAGE, pkg);
6615 proto.write(MODE, mode);
6616 proto.end(compatToken);
6617 }
6618 }
6619
6620 if (mCurAppTimeTracker != null) {
6621 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6622 }
6623
6624 }
6625 }
6626
6627 @Override
6628 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6629 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6630 boolean dumpFocusedStackOnly) {
6631 synchronized (mGlobalLock) {
6632 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6633 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6634 }
6635 }
6636
6637 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006638 public void dumpForOom(PrintWriter pw) {
6639 synchronized (mGlobalLock) {
6640 pw.println(" mHomeProcess: " + mHomeProcess);
6641 pw.println(" mPreviousProcess: " + mPreviousProcess);
6642 if (mHeavyWeightProcess != null) {
6643 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6644 }
6645 }
6646 }
6647
6648 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006649 public boolean canGcNow() {
6650 synchronized (mGlobalLock) {
6651 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6652 }
6653 }
6654
6655 @Override
6656 public WindowProcessController getTopApp() {
6657 synchronized (mGlobalLock) {
6658 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6659 return top != null ? top.app : null;
6660 }
6661 }
6662
6663 @Override
6664 public void rankTaskLayersIfNeeded() {
6665 synchronized (mGlobalLock) {
6666 if (mStackSupervisor != null) {
6667 mStackSupervisor.rankTaskLayersIfNeeded();
6668 }
6669 }
6670 }
6671
6672 @Override
6673 public void scheduleDestroyAllActivities(String reason) {
6674 synchronized (mGlobalLock) {
6675 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6676 }
6677 }
6678
6679 @Override
6680 public void removeUser(int userId) {
6681 synchronized (mGlobalLock) {
6682 mStackSupervisor.removeUserLocked(userId);
6683 }
6684 }
6685
6686 @Override
6687 public boolean switchUser(int userId, UserState userState) {
6688 synchronized (mGlobalLock) {
6689 return mStackSupervisor.switchUserLocked(userId, userState);
6690 }
6691 }
6692
6693 @Override
6694 public void onHandleAppCrash(WindowProcessController wpc) {
6695 synchronized (mGlobalLock) {
6696 mStackSupervisor.handleAppCrashLocked(wpc);
6697 }
6698 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006699
6700 @Override
6701 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6702 synchronized (mGlobalLock) {
6703 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6704 }
6705 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006706
6707 @Override
6708 public void onUidActive(int uid, int procState) {
6709 synchronized (mGlobalLock) {
6710 mActiveUids.put(uid, procState);
6711 }
6712 }
6713
6714 @Override
6715 public void onUidInactive(int uid) {
6716 synchronized (mGlobalLock) {
6717 mActiveUids.remove(uid);
6718 }
6719 }
6720
6721 @Override
6722 public void onActiveUidsCleared() {
6723 synchronized (mGlobalLock) {
6724 mActiveUids.clear();
6725 }
6726 }
6727
6728 @Override
6729 public void onUidProcStateChanged(int uid, int procState) {
6730 synchronized (mGlobalLock) {
6731 if (mActiveUids.get(uid) != null) {
6732 mActiveUids.put(uid, procState);
6733 }
6734 }
6735 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006736
6737 @Override
6738 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6739 synchronized (mGlobalLock) {
6740 mPendingTempWhitelist.put(uid, tag);
6741 }
6742 }
6743
6744 @Override
6745 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6746 synchronized (mGlobalLock) {
6747 mPendingTempWhitelist.remove(uid);
6748 }
6749 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006750
6751 @Override
6752 public boolean handleAppCrashInActivityController(String processName, int pid,
6753 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6754 Runnable killCrashingAppCallback) {
6755 synchronized (mGlobalLock) {
6756 if (mController == null) {
6757 return false;
6758 }
6759
6760 try {
6761 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6762 stackTrace)) {
6763 killCrashingAppCallback.run();
6764 return true;
6765 }
6766 } catch (RemoteException e) {
6767 mController = null;
6768 Watchdog.getInstance().setActivityController(null);
6769 }
6770 return false;
6771 }
6772 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006773
6774 @Override
6775 public void removeRecentTasksByPackageName(String packageName, int userId) {
6776 synchronized (mGlobalLock) {
6777 mRecentTasks.removeTasksByPackageName(packageName, userId);
6778 }
6779 }
6780
6781 @Override
6782 public void cleanupRecentTasksForUser(int userId) {
6783 synchronized (mGlobalLock) {
6784 mRecentTasks.cleanupLocked(userId);
6785 }
6786 }
6787
6788 @Override
6789 public void loadRecentTasksForUser(int userId) {
6790 synchronized (mGlobalLock) {
6791 mRecentTasks.loadUserRecentsLocked(userId);
6792 }
6793 }
6794
6795 @Override
6796 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6797 synchronized (mGlobalLock) {
6798 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6799 }
6800 }
6801
6802 @Override
6803 public void flushRecentTasks() {
6804 mRecentTasks.flush();
6805 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006806
6807 @Override
6808 public WindowProcessController getHomeProcess() {
6809 synchronized (mGlobalLock) {
6810 return mHomeProcess;
6811 }
6812 }
6813
6814 @Override
6815 public WindowProcessController getPreviousProcess() {
6816 synchronized (mGlobalLock) {
6817 return mPreviousProcess;
6818 }
6819 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006820
6821 @Override
6822 public void clearLockedTasks(String reason) {
6823 synchronized (mGlobalLock) {
6824 getLockTaskController().clearLockedTasks(reason);
6825 }
6826 }
6827
6828 @Override
6829 public void updateUserConfiguration() {
6830 synchronized (mGlobalLock) {
6831 final Configuration configuration = new Configuration(getGlobalConfiguration());
6832 final int currentUserId = mAmInternal.getCurrentUserId();
6833 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6834 configuration, currentUserId, Settings.System.canWrite(mContext));
6835 updateConfigurationLocked(configuration, null /* starting */,
6836 false /* initLocale */, false /* persistent */, currentUserId,
6837 false /* deferResume */);
6838 }
6839 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006840
6841 @Override
6842 public boolean canShowErrorDialogs() {
6843 synchronized (mGlobalLock) {
6844 return mShowDialogs && !mSleeping && !mShuttingDown
6845 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6846 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6847 mAmInternal.getCurrentUserId())
6848 && !(UserManager.isDeviceInDemoMode(mContext)
6849 && mAmInternal.getCurrentUser().isDemo());
6850 }
6851 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006852
6853 @Override
6854 public void setProfileApp(String profileApp) {
6855 synchronized (mGlobalLock) {
6856 mProfileApp = profileApp;
6857 }
6858 }
6859
6860 @Override
6861 public void setProfileProc(WindowProcessController wpc) {
6862 synchronized (mGlobalLock) {
6863 mProfileProc = wpc;
6864 }
6865 }
6866
6867 @Override
6868 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6869 synchronized (mGlobalLock) {
6870 mProfilerInfo = profilerInfo;
6871 }
6872 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08006873
6874 @Override
6875 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
6876 synchronized (mGlobalLock) {
6877 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
6878 }
6879 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006880 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08006881}