blob: 99e1290628c4d45e9c3e6f1435508efc8c7cf6b3 [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 Ogunwaleb73f3962018-11-20 07:58:22 -0800344 @VisibleForTesting
345 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700346 PowerManagerInternal mPowerManagerInternal;
347 private UsageStatsManagerInternal mUsageStatsInternal;
348
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700349 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700350 IntentFirewall mIntentFirewall;
351
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700352 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800353 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700354 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700355 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700356 private UserManagerService mUserManager;
357 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700358 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700359 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
360 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700361 /** All processes currently running that might have a window organized by name. */
362 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700363 /** All processes we currently have running mapped by pid */
364 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700365 /** This is the process holding what we currently consider to be the "home" activity. */
366 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700367 /** The currently running heavy-weight process, if any. */
368 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700369 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700370 /**
371 * This is the process holding the activity the user last visited that is in a different process
372 * from the one they are currently in.
373 */
374 WindowProcessController mPreviousProcess;
375 /** The time at which the previous process was last visible. */
376 long mPreviousProcessVisibleTime;
377
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700378 /** List of intents that were used to start the most recent tasks. */
379 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700380 /** State of external calls telling us if the device is awake or asleep. */
381 private boolean mKeyguardShown = false;
382
383 // Wrapper around VoiceInteractionServiceManager
384 private AssistUtils mAssistUtils;
385
386 // VoiceInteraction session ID that changes for each new request except when
387 // being called for multi-window assist in a single session.
388 private int mViSessionId = 1000;
389
390 // How long to wait in getAssistContextExtras for the activity and foreground services
391 // to respond with the result.
392 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
393
394 // How long top wait when going through the modern assist (which doesn't need to block
395 // on getting this result before starting to launch its UI).
396 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
397
398 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
399 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
400
Alison Cichowlas3e340502018-08-07 17:15:01 -0400401 // Permission tokens are used to temporarily granted a trusted app the ability to call
402 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
403 // showing any appropriate error messages to the user.
404 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
405 10 * MINUTE_IN_MILLIS;
406
407 // How long before the service actually expires a token. This is slightly longer than
408 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
409 // expiration exception.
410 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
411 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
412
413 // How long the service will remember expired tokens, for the purpose of providing error
414 // messaging when a client uses an expired token.
415 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
416 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
417
418 // Activity tokens of system activities that are delegating their call to
419 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
420 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
421
422 // Permission tokens that have expired, but we remember for error reporting.
423 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
424
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700425 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
426
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700427 // Keeps track of the active voice interaction service component, notified from
428 // VoiceInteractionManagerService
429 ComponentName mActiveVoiceInteractionServiceComponent;
430
Wale Ogunwalee2172292018-10-25 10:11:10 -0700431 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700432 KeyguardController mKeyguardController;
433 private final ClientLifecycleManager mLifecycleManager;
434 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700435 /** The controller for all operations related to locktask. */
436 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700437 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700438
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700439 boolean mSuppressResizeConfigChanges;
440
441 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
442 new UpdateConfigurationResult();
443
444 static final class UpdateConfigurationResult {
445 // Configuration changes that were updated.
446 int changes;
447 // If the activity was relaunched to match the new configuration.
448 boolean activityRelaunched;
449
450 void reset() {
451 changes = 0;
452 activityRelaunched = false;
453 }
454 }
455
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700456 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700457 private int mConfigurationSeq;
458 // To cache the list of supported system locales
459 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700460
461 /**
462 * Temp object used when global and/or display override configuration is updated. It is also
463 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
464 * anyone...
465 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700466 private Configuration mTempConfig = new Configuration();
467
Wale Ogunwalef6733932018-06-27 05:14:34 -0700468 /** Temporary to avoid allocations. */
469 final StringBuilder mStringBuilder = new StringBuilder(256);
470
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700471 // Amount of time after a call to stopAppSwitches() during which we will
472 // prevent further untrusted switches from happening.
473 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
474
475 /**
476 * The time at which we will allow normal application switches again,
477 * after a call to {@link #stopAppSwitches()}.
478 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700479 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700480 /**
481 * This is set to true after the first switch after mAppSwitchesAllowedTime
482 * is set; any switches after that will clear the time.
483 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700484 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700485
486 IActivityController mController = null;
487 boolean mControllerIsAMonkey = false;
488
Wale Ogunwale214f3482018-10-04 11:00:47 -0700489 final int mFactoryTest;
490
491 /** Used to control how we initialize the service. */
492 ComponentName mTopComponent;
493 String mTopAction = Intent.ACTION_MAIN;
494 String mTopData;
495
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800496 /** Profiling app information. */
497 String mProfileApp = null;
498 WindowProcessController mProfileProc = null;
499 ProfilerInfo mProfilerInfo = null;
500
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700501 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700502 * Dump of the activity state at the time of the last ANR. Cleared after
503 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
504 */
505 String mLastANRState;
506
507 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 * Used to retain an update lock when the foreground activity is in
509 * immersive mode.
510 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700511 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700512
513 /**
514 * Packages that are being allowed to perform unrestricted app switches. Mapping is
515 * User -> Type -> uid.
516 */
517 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
518
519 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700520 private int mThumbnailWidth;
521 private int mThumbnailHeight;
522 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700523
524 /**
525 * Flag that indicates if multi-window is enabled.
526 *
527 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
528 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
529 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
530 * At least one of the forms of multi-window must be enabled in order for this flag to be
531 * initialized to 'true'.
532 *
533 * @see #mSupportsSplitScreenMultiWindow
534 * @see #mSupportsFreeformWindowManagement
535 * @see #mSupportsPictureInPicture
536 * @see #mSupportsMultiDisplay
537 */
538 boolean mSupportsMultiWindow;
539 boolean mSupportsSplitScreenMultiWindow;
540 boolean mSupportsFreeformWindowManagement;
541 boolean mSupportsPictureInPicture;
542 boolean mSupportsMultiDisplay;
543 boolean mForceResizableActivities;
544
545 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
546
547 // VR Vr2d Display Id.
548 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700549
Wale Ogunwalef6733932018-06-27 05:14:34 -0700550 /**
551 * Set while we are wanting to sleep, to prevent any
552 * activities from being started/resumed.
553 *
554 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
555 *
556 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
557 * while in the sleep state until there is a pending transition out of sleep, in which case
558 * mSleeping is set to false, and remains false while awake.
559 *
560 * Whether mSleeping can quickly toggled between true/false without the device actually
561 * display changing states is undefined.
562 */
563 private boolean mSleeping = false;
564
565 /**
566 * The process state used for processes that are running the top activities.
567 * This changes between TOP and TOP_SLEEPING to following mSleeping.
568 */
569 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
570
571 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
572 // automatically. Important for devices without direct input devices.
573 private boolean mShowDialogs = true;
574
575 /** Set if we are shutting down the system, similar to sleeping. */
576 boolean mShuttingDown = false;
577
578 /**
579 * We want to hold a wake lock while running a voice interaction session, since
580 * this may happen with the screen off and we need to keep the CPU running to
581 * be able to continue to interact with the user.
582 */
583 PowerManager.WakeLock mVoiceWakeLock;
584
585 /**
586 * Set while we are running a voice interaction. This overrides sleeping while it is active.
587 */
588 IVoiceInteractionSession mRunningVoice;
589
590 /**
591 * The last resumed activity. This is identical to the current resumed activity most
592 * of the time but could be different when we're pausing one activity before we resume
593 * another activity.
594 */
595 ActivityRecord mLastResumedActivity;
596
597 /**
598 * The activity that is currently being traced as the active resumed activity.
599 *
600 * @see #updateResumedAppTrace
601 */
602 private @Nullable ActivityRecord mTracedResumedActivity;
603
604 /** If non-null, we are tracking the time the user spends in the currently focused app. */
605 AppTimeTracker mCurAppTimeTracker;
606
Wale Ogunwale008163e2018-07-23 23:11:08 -0700607 private AppWarnings mAppWarnings;
608
Wale Ogunwale53783742018-09-16 10:21:51 -0700609 /**
610 * Packages that the user has asked to have run in screen size
611 * compatibility mode instead of filling the screen.
612 */
613 CompatModePackages mCompatModePackages;
614
Wale Ogunwalef6733932018-06-27 05:14:34 -0700615 private FontScaleSettingObserver mFontScaleSettingObserver;
616
617 private final class FontScaleSettingObserver extends ContentObserver {
618 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
619 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
620
621 public FontScaleSettingObserver() {
622 super(mH);
623 final ContentResolver resolver = mContext.getContentResolver();
624 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
625 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
626 UserHandle.USER_ALL);
627 }
628
629 @Override
630 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
631 if (mFontScaleUri.equals(uri)) {
632 updateFontScaleIfNeeded(userId);
633 } else if (mHideErrorDialogsUri.equals(uri)) {
634 synchronized (mGlobalLock) {
635 updateShouldShowDialogsLocked(getGlobalConfiguration());
636 }
637 }
638 }
639 }
640
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700641 ActivityTaskManagerService(Context context) {
642 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700643 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700644 mSystemThread = ActivityThread.currentActivityThread();
645 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700646 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800647 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700648 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700649 }
650
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700651 public void onSystemReady() {
652 synchronized (mGlobalLock) {
653 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
654 PackageManager.FEATURE_CANT_SAVE_STATE);
655 mAssistUtils = new AssistUtils(mContext);
656 mVrController.onSystemReady();
657 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700658 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700659 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700660 }
661
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700662 public void onInitPowerManagement() {
663 synchronized (mGlobalLock) {
664 mStackSupervisor.initPowerManagement();
665 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
666 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
667 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
668 mVoiceWakeLock.setReferenceCounted(false);
669 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 mFontScaleSettingObserver = new FontScaleSettingObserver();
674 }
675
Wale Ogunwale59507092018-10-29 09:00:30 -0700676 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700677 final boolean freeformWindowManagement =
678 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
679 || Settings.Global.getInt(
680 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
681
682 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
683 final boolean supportsPictureInPicture = supportsMultiWindow &&
684 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
685 final boolean supportsSplitScreenMultiWindow =
686 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
687 final boolean supportsMultiDisplay = mContext.getPackageManager()
688 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700689 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
690 final boolean forceResizable = Settings.Global.getInt(
691 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700692 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700693
694 // Transfer any global setting for forcing RTL layout, into a System Property
695 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
696
697 final Configuration configuration = new Configuration();
698 Settings.System.getConfiguration(resolver, configuration);
699 if (forceRtl) {
700 // This will take care of setting the correct layout direction flags
701 configuration.setLayoutDirection(configuration.locale);
702 }
703
704 synchronized (mGlobalLock) {
705 mForceResizableActivities = forceResizable;
706 final boolean multiWindowFormEnabled = freeformWindowManagement
707 || supportsSplitScreenMultiWindow
708 || supportsPictureInPicture
709 || supportsMultiDisplay;
710 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
711 mSupportsMultiWindow = true;
712 mSupportsFreeformWindowManagement = freeformWindowManagement;
713 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
714 mSupportsPictureInPicture = supportsPictureInPicture;
715 mSupportsMultiDisplay = supportsMultiDisplay;
716 } else {
717 mSupportsMultiWindow = false;
718 mSupportsFreeformWindowManagement = false;
719 mSupportsSplitScreenMultiWindow = false;
720 mSupportsPictureInPicture = false;
721 mSupportsMultiDisplay = false;
722 }
723 mWindowManager.setForceResizableTasks(mForceResizableActivities);
724 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700725 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
726 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700727 // This happens before any activities are started, so we can change global configuration
728 // in-place.
729 updateConfigurationLocked(configuration, null, true);
730 final Configuration globalConfig = getGlobalConfiguration();
731 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
732
733 // Load resources only after the current configuration has been set.
734 final Resources res = mContext.getResources();
735 mThumbnailWidth = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_width);
737 mThumbnailHeight = res.getDimensionPixelSize(
738 com.android.internal.R.dimen.thumbnail_height);
739
740 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
741 mFullscreenThumbnailScale = (float) res
742 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
743 (float) globalConfig.screenWidthDp;
744 } else {
745 mFullscreenThumbnailScale = res.getFraction(
746 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
747 }
748 }
749 }
750
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800751 public WindowManagerGlobalLock getGlobalLock() {
752 return mGlobalLock;
753 }
754
755 public void setActivityManagerService(IntentFirewall intentFirewall,
756 PendingIntentController intentController) {
757 mH = new H();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700758 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700759 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700760 final File systemDir = SystemServiceManager.ensureSystemDir();
761 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
762 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700763 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700764
765 mTempConfig.setToDefaults();
766 mTempConfig.setLocales(LocaleList.getDefault());
767 mConfigurationSeq = mTempConfig.seq = 1;
768 mStackSupervisor = createStackSupervisor();
769 mStackSupervisor.onConfigurationChanged(mTempConfig);
770
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700771 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700772 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700773 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700775 mRecentTasks = createRecentTasks();
776 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700777 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700778 mKeyguardController = mStackSupervisor.getKeyguardController();
779 }
780
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700781 public void onActivityManagerInternalAdded() {
782 synchronized (mGlobalLock) {
783 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
784 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
785 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700786 }
787
Yunfan Chen75157d72018-07-27 14:47:21 +0900788 int increaseConfigurationSeqLocked() {
789 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
790 return mConfigurationSeq;
791 }
792
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700793 protected ActivityStackSupervisor createStackSupervisor() {
794 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
795 supervisor.initialize();
796 return supervisor;
797 }
798
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700799 public void setWindowManager(WindowManagerService wm) {
800 synchronized (mGlobalLock) {
801 mWindowManager = wm;
802 mLockTaskController.setWindowManager(wm);
803 mStackSupervisor.setWindowManager(wm);
804 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700805 }
806
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700807 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
808 synchronized (mGlobalLock) {
809 mUsageStatsInternal = usageStatsManager;
810 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700811 }
812
Wale Ogunwalef6733932018-06-27 05:14:34 -0700813 UserManagerService getUserManager() {
814 if (mUserManager == null) {
815 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
816 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
817 }
818 return mUserManager;
819 }
820
821 AppOpsService getAppOpsService() {
822 if (mAppOpsService == null) {
823 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
824 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
825 }
826 return mAppOpsService;
827 }
828
829 boolean hasUserRestriction(String restriction, int userId) {
830 return getUserManager().hasUserRestriction(restriction, userId);
831 }
832
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700833 protected RecentTasks createRecentTasks() {
834 return new RecentTasks(this, mStackSupervisor);
835 }
836
837 RecentTasks getRecentTasks() {
838 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700839 }
840
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700841 ClientLifecycleManager getLifecycleManager() {
842 return mLifecycleManager;
843 }
844
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700845 ActivityStartController getActivityStartController() {
846 return mActivityStartController;
847 }
848
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700849 TaskChangeNotificationController getTaskChangeNotificationController() {
850 return mTaskChangeNotificationController;
851 }
852
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700853 LockTaskController getLockTaskController() {
854 return mLockTaskController;
855 }
856
Yunfan Chen75157d72018-07-27 14:47:21 +0900857 /**
858 * Return the global configuration used by the process corresponding to the input pid. This is
859 * usually the global configuration with some overrides specific to that process.
860 */
861 Configuration getGlobalConfigurationForCallingPid() {
862 final int pid = Binder.getCallingPid();
863 if (pid == MY_PID || pid < 0) {
864 return getGlobalConfiguration();
865 }
866 synchronized (mGlobalLock) {
867 final WindowProcessController app = mPidMap.get(pid);
868 return app != null ? app.getConfiguration() : getGlobalConfiguration();
869 }
870 }
871
872 /**
873 * Return the device configuration info used by the process corresponding to the input pid.
874 * The value is consistent with the global configuration for the process.
875 */
876 @Override
877 public ConfigurationInfo getDeviceConfigurationInfo() {
878 ConfigurationInfo config = new ConfigurationInfo();
879 synchronized (mGlobalLock) {
880 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
881 config.reqTouchScreen = globalConfig.touchscreen;
882 config.reqKeyboardType = globalConfig.keyboard;
883 config.reqNavigation = globalConfig.navigation;
884 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
885 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
886 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
887 }
888 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
889 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
890 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
891 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700892 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900893 }
894 return config;
895 }
896
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700897 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700898 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700899 }
900
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700901 public static final class Lifecycle extends SystemService {
902 private final ActivityTaskManagerService mService;
903
904 public Lifecycle(Context context) {
905 super(context);
906 mService = new ActivityTaskManagerService(context);
907 }
908
909 @Override
910 public void onStart() {
911 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700912 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700913 }
914
Garfield Tan891146c2018-10-09 12:14:00 -0700915 @Override
916 public void onUnlockUser(int userId) {
917 synchronized (mService.getGlobalLock()) {
918 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
919 }
920 }
921
922 @Override
923 public void onCleanupUser(int userId) {
924 synchronized (mService.getGlobalLock()) {
925 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
926 }
927 }
928
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700929 public ActivityTaskManagerService getService() {
930 return mService;
931 }
932 }
933
934 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700935 public final int startActivity(IApplicationThread caller, String callingPackage,
936 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
937 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
938 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
939 resultWho, requestCode, startFlags, profilerInfo, bOptions,
940 UserHandle.getCallingUserId());
941 }
942
943 @Override
944 public final int startActivities(IApplicationThread caller, String callingPackage,
945 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
946 int userId) {
947 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700948 enforceNotIsolatedCaller(reason);
949 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700950 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700951 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100952 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
953 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700954 }
955
956 @Override
957 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
958 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
959 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
960 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
961 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
962 true /*validateIncomingUser*/);
963 }
964
965 int startActivityAsUser(IApplicationThread caller, String callingPackage,
966 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
967 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
968 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700969 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700970
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700971 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700972 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
973
974 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700975 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700976 .setCaller(caller)
977 .setCallingPackage(callingPackage)
978 .setResolvedType(resolvedType)
979 .setResultTo(resultTo)
980 .setResultWho(resultWho)
981 .setRequestCode(requestCode)
982 .setStartFlags(startFlags)
983 .setProfilerInfo(profilerInfo)
984 .setActivityOptions(bOptions)
985 .setMayWait(userId)
986 .execute();
987
988 }
989
990 @Override
991 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
992 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700993 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
994 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700995 // Refuse possible leaked file descriptors
996 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
997 throw new IllegalArgumentException("File descriptors passed in Intent");
998 }
999
1000 if (!(target instanceof PendingIntentRecord)) {
1001 throw new IllegalArgumentException("Bad PendingIntent object");
1002 }
1003
1004 PendingIntentRecord pir = (PendingIntentRecord)target;
1005
1006 synchronized (mGlobalLock) {
1007 // If this is coming from the currently resumed activity, it is
1008 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001009 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001010 if (stack.mResumedActivity != null &&
1011 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001012 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001013 }
1014 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001015 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001016 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 }
1018
1019 @Override
1020 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1021 Bundle bOptions) {
1022 // Refuse possible leaked file descriptors
1023 if (intent != null && intent.hasFileDescriptors()) {
1024 throw new IllegalArgumentException("File descriptors passed in Intent");
1025 }
1026 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1027
1028 synchronized (mGlobalLock) {
1029 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1030 if (r == null) {
1031 SafeActivityOptions.abort(options);
1032 return false;
1033 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001034 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001035 // The caller is not running... d'oh!
1036 SafeActivityOptions.abort(options);
1037 return false;
1038 }
1039 intent = new Intent(intent);
1040 // The caller is not allowed to change the data.
1041 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1042 // And we are resetting to find the next component...
1043 intent.setComponent(null);
1044
1045 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1046
1047 ActivityInfo aInfo = null;
1048 try {
1049 List<ResolveInfo> resolves =
1050 AppGlobals.getPackageManager().queryIntentActivities(
1051 intent, r.resolvedType,
1052 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1053 UserHandle.getCallingUserId()).getList();
1054
1055 // Look for the original activity in the list...
1056 final int N = resolves != null ? resolves.size() : 0;
1057 for (int i=0; i<N; i++) {
1058 ResolveInfo rInfo = resolves.get(i);
1059 if (rInfo.activityInfo.packageName.equals(r.packageName)
1060 && rInfo.activityInfo.name.equals(r.info.name)) {
1061 // We found the current one... the next matching is
1062 // after it.
1063 i++;
1064 if (i<N) {
1065 aInfo = resolves.get(i).activityInfo;
1066 }
1067 if (debug) {
1068 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1069 + "/" + r.info.name);
1070 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1071 ? "null" : aInfo.packageName + "/" + aInfo.name));
1072 }
1073 break;
1074 }
1075 }
1076 } catch (RemoteException e) {
1077 }
1078
1079 if (aInfo == null) {
1080 // Nobody who is next!
1081 SafeActivityOptions.abort(options);
1082 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1083 return false;
1084 }
1085
1086 intent.setComponent(new ComponentName(
1087 aInfo.applicationInfo.packageName, aInfo.name));
1088 intent.setFlags(intent.getFlags()&~(
1089 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1090 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1091 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1092 FLAG_ACTIVITY_NEW_TASK));
1093
1094 // Okay now we need to start the new activity, replacing the currently running activity.
1095 // This is a little tricky because we want to start the new one as if the current one is
1096 // finished, but not finish the current one first so that there is no flicker.
1097 // And thus...
1098 final boolean wasFinishing = r.finishing;
1099 r.finishing = true;
1100
1101 // Propagate reply information over to the new activity.
1102 final ActivityRecord resultTo = r.resultTo;
1103 final String resultWho = r.resultWho;
1104 final int requestCode = r.requestCode;
1105 r.resultTo = null;
1106 if (resultTo != null) {
1107 resultTo.removeResultsLocked(r, resultWho, requestCode);
1108 }
1109
1110 final long origId = Binder.clearCallingIdentity();
1111 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001112 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001113 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001114 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001115 .setResolvedType(r.resolvedType)
1116 .setActivityInfo(aInfo)
1117 .setResultTo(resultTo != null ? resultTo.appToken : null)
1118 .setResultWho(resultWho)
1119 .setRequestCode(requestCode)
1120 .setCallingPid(-1)
1121 .setCallingUid(r.launchedFromUid)
1122 .setCallingPackage(r.launchedFromPackage)
1123 .setRealCallingPid(-1)
1124 .setRealCallingUid(r.launchedFromUid)
1125 .setActivityOptions(options)
1126 .execute();
1127 Binder.restoreCallingIdentity(origId);
1128
1129 r.finishing = wasFinishing;
1130 if (res != ActivityManager.START_SUCCESS) {
1131 return false;
1132 }
1133 return true;
1134 }
1135 }
1136
1137 @Override
1138 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1139 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1140 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1141 final WaitResult res = new WaitResult();
1142 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001143 enforceNotIsolatedCaller("startActivityAndWait");
1144 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1145 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001146 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001147 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001148 .setCaller(caller)
1149 .setCallingPackage(callingPackage)
1150 .setResolvedType(resolvedType)
1151 .setResultTo(resultTo)
1152 .setResultWho(resultWho)
1153 .setRequestCode(requestCode)
1154 .setStartFlags(startFlags)
1155 .setActivityOptions(bOptions)
1156 .setMayWait(userId)
1157 .setProfilerInfo(profilerInfo)
1158 .setWaitResult(res)
1159 .execute();
1160 }
1161 return res;
1162 }
1163
1164 @Override
1165 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1166 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1167 int startFlags, Configuration config, Bundle bOptions, int userId) {
1168 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001169 enforceNotIsolatedCaller("startActivityWithConfig");
1170 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1171 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001172 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001173 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001174 .setCaller(caller)
1175 .setCallingPackage(callingPackage)
1176 .setResolvedType(resolvedType)
1177 .setResultTo(resultTo)
1178 .setResultWho(resultWho)
1179 .setRequestCode(requestCode)
1180 .setStartFlags(startFlags)
1181 .setGlobalConfiguration(config)
1182 .setActivityOptions(bOptions)
1183 .setMayWait(userId)
1184 .execute();
1185 }
1186 }
1187
Alison Cichowlas3e340502018-08-07 17:15:01 -04001188
1189 @Override
1190 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1191 int callingUid = Binder.getCallingUid();
1192 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1193 throw new SecurityException("Only the system process can request a permission token, "
1194 + "received request from uid: " + callingUid);
1195 }
1196 IBinder permissionToken = new Binder();
1197 synchronized (mGlobalLock) {
1198 mStartActivitySources.put(permissionToken, delegatorToken);
1199 }
1200
1201 Message expireMsg = PooledLambda.obtainMessage(
1202 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1203 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1204
1205 Message forgetMsg = PooledLambda.obtainMessage(
1206 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1207 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1208
1209 return permissionToken;
1210 }
1211
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001212 @Override
1213 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1214 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001215 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1216 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001217 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001218 // permission grants) as any app that may launch one of your own activities. So we only
1219 // allow this in two cases:
1220 // 1) The caller is an activity that is part of the core framework, and then only when it
1221 // is running as the system.
1222 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1223 // can only be requested by a system activity, which may then delegate this call to
1224 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 final ActivityRecord sourceRecord;
1226 final int targetUid;
1227 final String targetPackage;
1228 final boolean isResolver;
1229 synchronized (mGlobalLock) {
1230 if (resultTo == null) {
1231 throw new SecurityException("Must be called from an activity");
1232 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001233 final IBinder sourceToken;
1234 if (permissionToken != null) {
1235 // To even attempt to use a permissionToken, an app must also have this signature
1236 // permission.
1237 mAmInternal.enforceCallingPermission(
1238 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1239 "startActivityAsCaller");
1240 // If called with a permissionToken, we want the sourceRecord from the delegator
1241 // activity that requested this token.
1242 sourceToken = mStartActivitySources.remove(permissionToken);
1243 if (sourceToken == null) {
1244 // Invalid permissionToken, check if it recently expired.
1245 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1246 throw new SecurityException("Called with expired permission token: "
1247 + permissionToken);
1248 } else {
1249 throw new SecurityException("Called with invalid permission token: "
1250 + permissionToken);
1251 }
1252 }
1253 } else {
1254 // This method was called directly by the source.
1255 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001256 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001257
1258 sourceRecord = mStackSupervisor.isInAnyStackLocked(sourceToken);
1259 if (sourceRecord == null) {
1260 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001261 }
1262 if (sourceRecord.app == null) {
1263 throw new SecurityException("Called without a process attached to activity");
1264 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001265
1266 // Whether called directly or from a delegate, the source activity must be from the
1267 // android package.
1268 if (!sourceRecord.info.packageName.equals("android")) {
1269 throw new SecurityException("Must be called from an activity that is "
1270 + "declared in the android package");
1271 }
1272
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001273 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001274 // This is still okay, as long as this activity is running under the
1275 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001276 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001277 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001278 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001279 + " must be system uid or original calling uid "
1280 + sourceRecord.launchedFromUid);
1281 }
1282 }
1283 if (ignoreTargetSecurity) {
1284 if (intent.getComponent() == null) {
1285 throw new SecurityException(
1286 "Component must be specified with ignoreTargetSecurity");
1287 }
1288 if (intent.getSelector() != null) {
1289 throw new SecurityException(
1290 "Selector not allowed with ignoreTargetSecurity");
1291 }
1292 }
1293 targetUid = sourceRecord.launchedFromUid;
1294 targetPackage = sourceRecord.launchedFromPackage;
1295 isResolver = sourceRecord.isResolverOrChildActivity();
1296 }
1297
1298 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001299 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001300 }
1301
1302 // TODO: Switch to user app stacks here.
1303 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001304 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001305 .setCallingUid(targetUid)
1306 .setCallingPackage(targetPackage)
1307 .setResolvedType(resolvedType)
1308 .setResultTo(resultTo)
1309 .setResultWho(resultWho)
1310 .setRequestCode(requestCode)
1311 .setStartFlags(startFlags)
1312 .setActivityOptions(bOptions)
1313 .setMayWait(userId)
1314 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1315 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1316 .execute();
1317 } catch (SecurityException e) {
1318 // XXX need to figure out how to propagate to original app.
1319 // A SecurityException here is generally actually a fault of the original
1320 // calling activity (such as a fairly granting permissions), so propagate it
1321 // back to them.
1322 /*
1323 StringBuilder msg = new StringBuilder();
1324 msg.append("While launching");
1325 msg.append(intent.toString());
1326 msg.append(": ");
1327 msg.append(e.getMessage());
1328 */
1329 throw e;
1330 }
1331 }
1332
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001333 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1334 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1335 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1336 }
1337
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001338 @Override
1339 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1340 Intent intent, String resolvedType, IVoiceInteractionSession session,
1341 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1342 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001343 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 if (session == null || interactor == null) {
1345 throw new NullPointerException("null session or interactor");
1346 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001347 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001349 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 .setCallingUid(callingUid)
1351 .setCallingPackage(callingPackage)
1352 .setResolvedType(resolvedType)
1353 .setVoiceSession(session)
1354 .setVoiceInteractor(interactor)
1355 .setStartFlags(startFlags)
1356 .setProfilerInfo(profilerInfo)
1357 .setActivityOptions(bOptions)
1358 .setMayWait(userId)
1359 .execute();
1360 }
1361
1362 @Override
1363 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1364 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001365 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1366 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001367
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001368 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001369 .setCallingUid(callingUid)
1370 .setCallingPackage(callingPackage)
1371 .setResolvedType(resolvedType)
1372 .setActivityOptions(bOptions)
1373 .setMayWait(userId)
1374 .execute();
1375 }
1376
1377 @Override
1378 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1379 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001380 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001381 final int callingPid = Binder.getCallingPid();
1382 final long origId = Binder.clearCallingIdentity();
1383 try {
1384 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001385 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1386 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387
1388 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001389 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1390 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1392 recentsUid, assistDataReceiver);
1393 }
1394 } finally {
1395 Binder.restoreCallingIdentity(origId);
1396 }
1397 }
1398
1399 @Override
1400 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001401 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001402 "startActivityFromRecents()");
1403
1404 final int callingPid = Binder.getCallingPid();
1405 final int callingUid = Binder.getCallingUid();
1406 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1407 final long origId = Binder.clearCallingIdentity();
1408 try {
1409 synchronized (mGlobalLock) {
1410 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1411 safeOptions);
1412 }
1413 } finally {
1414 Binder.restoreCallingIdentity(origId);
1415 }
1416 }
1417
1418 /**
1419 * This is the internal entry point for handling Activity.finish().
1420 *
1421 * @param token The Binder token referencing the Activity we want to finish.
1422 * @param resultCode Result code, if any, from this Activity.
1423 * @param resultData Result data (Intent), if any, from this Activity.
1424 * @param finishTask Whether to finish the task associated with this Activity.
1425 *
1426 * @return Returns true if the activity successfully finished, or false if it is still running.
1427 */
1428 @Override
1429 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1430 int finishTask) {
1431 // Refuse possible leaked file descriptors
1432 if (resultData != null && resultData.hasFileDescriptors()) {
1433 throw new IllegalArgumentException("File descriptors passed in Intent");
1434 }
1435
1436 synchronized (mGlobalLock) {
1437 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1438 if (r == null) {
1439 return true;
1440 }
1441 // Keep track of the root activity of the task before we finish it
1442 TaskRecord tr = r.getTask();
1443 ActivityRecord rootR = tr.getRootActivity();
1444 if (rootR == null) {
1445 Slog.w(TAG, "Finishing task with all activities already finished");
1446 }
1447 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1448 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001449 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001450 return false;
1451 }
1452
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1454 // We should consolidate.
1455 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001456 // Find the first activity that is not finishing.
1457 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1458 if (next != null) {
1459 // ask watcher if this is allowed
1460 boolean resumeOK = true;
1461 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001462 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001463 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001464 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 Watchdog.getInstance().setActivityController(null);
1466 }
1467
1468 if (!resumeOK) {
1469 Slog.i(TAG, "Not finishing activity because controller resumed");
1470 return false;
1471 }
1472 }
1473 }
1474 final long origId = Binder.clearCallingIdentity();
1475 try {
1476 boolean res;
1477 final boolean finishWithRootActivity =
1478 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1479 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1480 || (finishWithRootActivity && r == rootR)) {
1481 // If requested, remove the task that is associated to this activity only if it
1482 // was the root activity in the task. The result code and data is ignored
1483 // because we don't support returning them across task boundaries. Also, to
1484 // keep backwards compatibility we remove the task from recents when finishing
1485 // task with root activity.
1486 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1487 finishWithRootActivity, "finish-activity");
1488 if (!res) {
1489 Slog.i(TAG, "Removing task failed to finish activity");
1490 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001491 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001492 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001493 } else {
1494 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1495 resultData, "app-request", true);
1496 if (!res) {
1497 Slog.i(TAG, "Failed to finish by app-request");
1498 }
1499 }
1500 return res;
1501 } finally {
1502 Binder.restoreCallingIdentity(origId);
1503 }
1504 }
1505 }
1506
1507 @Override
1508 public boolean finishActivityAffinity(IBinder token) {
1509 synchronized (mGlobalLock) {
1510 final long origId = Binder.clearCallingIdentity();
1511 try {
1512 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1513 if (r == null) {
1514 return false;
1515 }
1516
1517 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1518 // can finish.
1519 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001520 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 return false;
1522 }
1523 return task.getStack().finishActivityAffinityLocked(r);
1524 } finally {
1525 Binder.restoreCallingIdentity(origId);
1526 }
1527 }
1528 }
1529
1530 @Override
1531 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1532 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001533 try {
1534 WindowProcessController proc = null;
1535 synchronized (mGlobalLock) {
1536 ActivityStack stack = ActivityRecord.getStackLocked(token);
1537 if (stack == null) {
1538 return;
1539 }
1540 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1541 false /* fromTimeout */, false /* processPausingActivities */, config);
1542 if (r != null) {
1543 proc = r.app;
1544 }
1545 if (stopProfiling && proc != null) {
1546 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001547 }
1548 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001549 } finally {
1550 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001552 }
1553
1554 @Override
1555 public final void activityResumed(IBinder token) {
1556 final long origId = Binder.clearCallingIdentity();
1557 synchronized (mGlobalLock) {
1558 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001559 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001560 }
1561 Binder.restoreCallingIdentity(origId);
1562 }
1563
1564 @Override
1565 public final void activityPaused(IBinder token) {
1566 final long origId = Binder.clearCallingIdentity();
1567 synchronized (mGlobalLock) {
1568 ActivityStack stack = ActivityRecord.getStackLocked(token);
1569 if (stack != null) {
1570 stack.activityPausedLocked(token, false);
1571 }
1572 }
1573 Binder.restoreCallingIdentity(origId);
1574 }
1575
1576 @Override
1577 public final void activityStopped(IBinder token, Bundle icicle,
1578 PersistableBundle persistentState, CharSequence description) {
1579 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1580
1581 // Refuse possible leaked file descriptors
1582 if (icicle != null && icicle.hasFileDescriptors()) {
1583 throw new IllegalArgumentException("File descriptors passed in Bundle");
1584 }
1585
1586 final long origId = Binder.clearCallingIdentity();
1587
1588 synchronized (mGlobalLock) {
1589 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1590 if (r != null) {
1591 r.activityStoppedLocked(icicle, persistentState, description);
1592 }
1593 }
1594
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001595 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596
1597 Binder.restoreCallingIdentity(origId);
1598 }
1599
1600 @Override
1601 public final void activityDestroyed(IBinder token) {
1602 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1603 synchronized (mGlobalLock) {
1604 ActivityStack stack = ActivityRecord.getStackLocked(token);
1605 if (stack != null) {
1606 stack.activityDestroyedLocked(token, "activityDestroyed");
1607 }
1608 }
1609 }
1610
1611 @Override
1612 public final void activityRelaunched(IBinder token) {
1613 final long origId = Binder.clearCallingIdentity();
1614 synchronized (mGlobalLock) {
1615 mStackSupervisor.activityRelaunchedLocked(token);
1616 }
1617 Binder.restoreCallingIdentity(origId);
1618 }
1619
1620 public final void activitySlept(IBinder token) {
1621 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1622
1623 final long origId = Binder.clearCallingIdentity();
1624
1625 synchronized (mGlobalLock) {
1626 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1627 if (r != null) {
1628 mStackSupervisor.activitySleptLocked(r);
1629 }
1630 }
1631
1632 Binder.restoreCallingIdentity(origId);
1633 }
1634
1635 @Override
1636 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1637 synchronized (mGlobalLock) {
1638 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1639 if (r == null) {
1640 return;
1641 }
1642 final long origId = Binder.clearCallingIdentity();
1643 try {
1644 r.setRequestedOrientation(requestedOrientation);
1645 } finally {
1646 Binder.restoreCallingIdentity(origId);
1647 }
1648 }
1649 }
1650
1651 @Override
1652 public int getRequestedOrientation(IBinder token) {
1653 synchronized (mGlobalLock) {
1654 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1655 if (r == null) {
1656 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1657 }
1658 return r.getRequestedOrientation();
1659 }
1660 }
1661
1662 @Override
1663 public void setImmersive(IBinder token, boolean immersive) {
1664 synchronized (mGlobalLock) {
1665 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1666 if (r == null) {
1667 throw new IllegalArgumentException();
1668 }
1669 r.immersive = immersive;
1670
1671 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001672 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001673 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001674 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001675 }
1676 }
1677 }
1678
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001679 void applyUpdateLockStateLocked(ActivityRecord r) {
1680 // Modifications to the UpdateLock state are done on our handler, outside
1681 // the activity manager's locks. The new state is determined based on the
1682 // state *now* of the relevant activity record. The object is passed to
1683 // the handler solely for logging detail, not to be consulted/modified.
1684 final boolean nextState = r != null && r.immersive;
1685 mH.post(() -> {
1686 if (mUpdateLock.isHeld() != nextState) {
1687 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1688 "Applying new update lock state '" + nextState + "' for " + r);
1689 if (nextState) {
1690 mUpdateLock.acquire();
1691 } else {
1692 mUpdateLock.release();
1693 }
1694 }
1695 });
1696 }
1697
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001698 @Override
1699 public boolean isImmersive(IBinder token) {
1700 synchronized (mGlobalLock) {
1701 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1702 if (r == null) {
1703 throw new IllegalArgumentException();
1704 }
1705 return r.immersive;
1706 }
1707 }
1708
1709 @Override
1710 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001711 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001712 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001713 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001714 return (r != null) ? r.immersive : false;
1715 }
1716 }
1717
1718 @Override
1719 public void overridePendingTransition(IBinder token, String packageName,
1720 int enterAnim, int exitAnim) {
1721 synchronized (mGlobalLock) {
1722 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1723 if (self == null) {
1724 return;
1725 }
1726
1727 final long origId = Binder.clearCallingIdentity();
1728
1729 if (self.isState(
1730 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001731 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1732 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 }
1734
1735 Binder.restoreCallingIdentity(origId);
1736 }
1737 }
1738
1739 @Override
1740 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001741 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001743 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001744 if (r == null) {
1745 return ActivityManager.COMPAT_MODE_UNKNOWN;
1746 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001747 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001748 }
1749 }
1750
1751 @Override
1752 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001753 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001754 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001755 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001757 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001758 if (r == null) {
1759 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1760 return;
1761 }
1762 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001763 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001764 }
1765 }
1766
1767 @Override
1768 public int getLaunchedFromUid(IBinder activityToken) {
1769 ActivityRecord srec;
1770 synchronized (mGlobalLock) {
1771 srec = ActivityRecord.forTokenLocked(activityToken);
1772 }
1773 if (srec == null) {
1774 return -1;
1775 }
1776 return srec.launchedFromUid;
1777 }
1778
1779 @Override
1780 public String getLaunchedFromPackage(IBinder activityToken) {
1781 ActivityRecord srec;
1782 synchronized (mGlobalLock) {
1783 srec = ActivityRecord.forTokenLocked(activityToken);
1784 }
1785 if (srec == null) {
1786 return null;
1787 }
1788 return srec.launchedFromPackage;
1789 }
1790
1791 @Override
1792 public boolean convertFromTranslucent(IBinder token) {
1793 final long origId = Binder.clearCallingIdentity();
1794 try {
1795 synchronized (mGlobalLock) {
1796 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1797 if (r == null) {
1798 return false;
1799 }
1800 final boolean translucentChanged = r.changeWindowTranslucency(true);
1801 if (translucentChanged) {
1802 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1803 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001804 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001805 return translucentChanged;
1806 }
1807 } finally {
1808 Binder.restoreCallingIdentity(origId);
1809 }
1810 }
1811
1812 @Override
1813 public boolean convertToTranslucent(IBinder token, Bundle options) {
1814 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1815 final long origId = Binder.clearCallingIdentity();
1816 try {
1817 synchronized (mGlobalLock) {
1818 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1819 if (r == null) {
1820 return false;
1821 }
1822 final TaskRecord task = r.getTask();
1823 int index = task.mActivities.lastIndexOf(r);
1824 if (index > 0) {
1825 ActivityRecord under = task.mActivities.get(index - 1);
1826 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1827 }
1828 final boolean translucentChanged = r.changeWindowTranslucency(false);
1829 if (translucentChanged) {
1830 r.getStack().convertActivityToTranslucent(r);
1831 }
1832 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001833 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001834 return translucentChanged;
1835 }
1836 } finally {
1837 Binder.restoreCallingIdentity(origId);
1838 }
1839 }
1840
1841 @Override
1842 public void notifyActivityDrawn(IBinder token) {
1843 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1844 synchronized (mGlobalLock) {
1845 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1846 if (r != null) {
1847 r.getStack().notifyActivityDrawnLocked(r);
1848 }
1849 }
1850 }
1851
1852 @Override
1853 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1854 synchronized (mGlobalLock) {
1855 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1856 if (r == null) {
1857 return;
1858 }
1859 r.reportFullyDrawnLocked(restoredFromBundle);
1860 }
1861 }
1862
1863 @Override
1864 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1865 synchronized (mGlobalLock) {
1866 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1867 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1868 return stack.mDisplayId;
1869 }
1870 return DEFAULT_DISPLAY;
1871 }
1872 }
1873
1874 @Override
1875 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001876 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 long ident = Binder.clearCallingIdentity();
1878 try {
1879 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001880 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 if (focusedStack != null) {
1882 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1883 }
1884 return null;
1885 }
1886 } finally {
1887 Binder.restoreCallingIdentity(ident);
1888 }
1889 }
1890
1891 @Override
1892 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001893 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1895 final long callingId = Binder.clearCallingIdentity();
1896 try {
1897 synchronized (mGlobalLock) {
1898 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1899 if (stack == null) {
1900 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1901 return;
1902 }
1903 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001904 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001905 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908 } finally {
1909 Binder.restoreCallingIdentity(callingId);
1910 }
1911 }
1912
1913 @Override
1914 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001915 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001916 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1917 final long callingId = Binder.clearCallingIdentity();
1918 try {
1919 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001920 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1921 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 if (task == null) {
1923 return;
1924 }
1925 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001926 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001927 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 }
1930 } finally {
1931 Binder.restoreCallingIdentity(callingId);
1932 }
1933 }
1934
1935 @Override
1936 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001937 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001938 synchronized (mGlobalLock) {
1939 final long ident = Binder.clearCallingIdentity();
1940 try {
1941 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1942 "remove-task");
1943 } finally {
1944 Binder.restoreCallingIdentity(ident);
1945 }
1946 }
1947 }
1948
1949 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001950 public void removeAllVisibleRecentTasks() {
1951 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1952 synchronized (mGlobalLock) {
1953 final long ident = Binder.clearCallingIdentity();
1954 try {
1955 getRecentTasks().removeAllVisibleTasks();
1956 } finally {
1957 Binder.restoreCallingIdentity(ident);
1958 }
1959 }
1960 }
1961
1962 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001963 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1964 synchronized (mGlobalLock) {
1965 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1966 if (srec != null) {
1967 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1968 }
1969 }
1970 return false;
1971 }
1972
1973 @Override
1974 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1975 Intent resultData) {
1976
1977 synchronized (mGlobalLock) {
1978 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1979 if (r != null) {
1980 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1981 }
1982 return false;
1983 }
1984 }
1985
1986 /**
1987 * Attempts to move a task backwards in z-order (the order of activities within the task is
1988 * unchanged).
1989 *
1990 * There are several possible results of this call:
1991 * - if the task is locked, then we will show the lock toast
1992 * - if there is a task behind the provided task, then that task is made visible and resumed as
1993 * this task is moved to the back
1994 * - otherwise, if there are no other tasks in the stack:
1995 * - if this task is in the pinned stack, then we remove the stack completely, which will
1996 * have the effect of moving the task to the top or bottom of the fullscreen stack
1997 * (depending on whether it is visible)
1998 * - otherwise, we simply return home and hide this task
1999 *
2000 * @param token A reference to the activity we wish to move
2001 * @param nonRoot If false then this only works if the activity is the root
2002 * of a task; if true it will work for any activity in a task.
2003 * @return Returns true if the move completed, false if not.
2004 */
2005 @Override
2006 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002007 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 synchronized (mGlobalLock) {
2009 final long origId = Binder.clearCallingIdentity();
2010 try {
2011 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
2012 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2013 if (task != null) {
2014 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2015 }
2016 } finally {
2017 Binder.restoreCallingIdentity(origId);
2018 }
2019 }
2020 return false;
2021 }
2022
2023 @Override
2024 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002025 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 long ident = Binder.clearCallingIdentity();
2027 Rect rect = new Rect();
2028 try {
2029 synchronized (mGlobalLock) {
2030 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2031 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2032 if (task == null) {
2033 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2034 return rect;
2035 }
2036 if (task.getStack() != null) {
2037 // Return the bounds from window manager since it will be adjusted for various
2038 // things like the presense of a docked stack for tasks that aren't resizeable.
2039 task.getWindowContainerBounds(rect);
2040 } else {
2041 // Task isn't in window manager yet since it isn't associated with a stack.
2042 // Return the persist value from activity manager
2043 if (!task.matchParentBounds()) {
2044 rect.set(task.getBounds());
2045 } else if (task.mLastNonFullscreenBounds != null) {
2046 rect.set(task.mLastNonFullscreenBounds);
2047 }
2048 }
2049 }
2050 } finally {
2051 Binder.restoreCallingIdentity(ident);
2052 }
2053 return rect;
2054 }
2055
2056 @Override
2057 public ActivityManager.TaskDescription getTaskDescription(int id) {
2058 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002059 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
2061 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
2062 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2063 if (tr != null) {
2064 return tr.lastTaskDescription;
2065 }
2066 }
2067 return null;
2068 }
2069
2070 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002071 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2072 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2073 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2074 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2075 return;
2076 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002077 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002078 synchronized (mGlobalLock) {
2079 final long ident = Binder.clearCallingIdentity();
2080 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002081 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2082 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002083 if (task == null) {
2084 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2085 return;
2086 }
2087
2088 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2089 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2090
2091 if (!task.isActivityTypeStandardOrUndefined()) {
2092 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2093 + " non-standard task " + taskId + " to windowing mode="
2094 + windowingMode);
2095 }
2096
2097 final ActivityStack stack = task.getStack();
2098 if (toTop) {
2099 stack.moveToFront("setTaskWindowingMode", task);
2100 }
2101 stack.setWindowingMode(windowingMode);
2102 } finally {
2103 Binder.restoreCallingIdentity(ident);
2104 }
2105 }
2106 }
2107
2108 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002110 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002111 ActivityRecord r = getCallingRecordLocked(token);
2112 return r != null ? r.info.packageName : null;
2113 }
2114 }
2115
2116 @Override
2117 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002118 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 ActivityRecord r = getCallingRecordLocked(token);
2120 return r != null ? r.intent.getComponent() : null;
2121 }
2122 }
2123
2124 private ActivityRecord getCallingRecordLocked(IBinder token) {
2125 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2126 if (r == null) {
2127 return null;
2128 }
2129 return r.resultTo;
2130 }
2131
2132 @Override
2133 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002134 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002135
2136 synchronized (mGlobalLock) {
2137 final long origId = Binder.clearCallingIdentity();
2138 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002139 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002140 } finally {
2141 Binder.restoreCallingIdentity(origId);
2142 }
2143 }
2144 }
2145
2146 /**
2147 * TODO: Add mController hook
2148 */
2149 @Override
2150 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002151 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002152
2153 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2154 synchronized (mGlobalLock) {
2155 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2156 false /* fromRecents */);
2157 }
2158 }
2159
2160 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2161 boolean fromRecents) {
2162
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002163 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002164 Binder.getCallingUid(), -1, -1, "Task to front")) {
2165 SafeActivityOptions.abort(options);
2166 return;
2167 }
2168 final long origId = Binder.clearCallingIdentity();
2169 try {
2170 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2171 if (task == null) {
2172 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002173 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002174 return;
2175 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002176 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002178 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 return;
2180 }
2181 ActivityOptions realOptions = options != null
2182 ? options.getOptions(mStackSupervisor)
2183 : null;
2184 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2185 false /* forceNonResizable */);
2186
2187 final ActivityRecord topActivity = task.getTopActivity();
2188 if (topActivity != null) {
2189
2190 // We are reshowing a task, use a starting window to hide the initial draw delay
2191 // so the transition can start earlier.
2192 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2193 true /* taskSwitch */, fromRecents);
2194 }
2195 } finally {
2196 Binder.restoreCallingIdentity(origId);
2197 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198 }
2199
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002200 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2201 int callingPid, int callingUid, String name) {
2202 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2203 return true;
2204 }
2205
2206 if (getRecentTasks().isCallerRecents(sourceUid)) {
2207 return true;
2208 }
2209
2210 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2211 if (perm == PackageManager.PERMISSION_GRANTED) {
2212 return true;
2213 }
2214 if (checkAllowAppSwitchUid(sourceUid)) {
2215 return true;
2216 }
2217
2218 // If the actual IPC caller is different from the logical source, then
2219 // also see if they are allowed to control app switches.
2220 if (callingUid != -1 && callingUid != sourceUid) {
2221 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2222 if (perm == PackageManager.PERMISSION_GRANTED) {
2223 return true;
2224 }
2225 if (checkAllowAppSwitchUid(callingUid)) {
2226 return true;
2227 }
2228 }
2229
2230 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2231 return false;
2232 }
2233
2234 private boolean checkAllowAppSwitchUid(int uid) {
2235 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2236 if (types != null) {
2237 for (int i = types.size() - 1; i >= 0; i--) {
2238 if (types.valueAt(i).intValue() == uid) {
2239 return true;
2240 }
2241 }
2242 }
2243 return false;
2244 }
2245
2246 @Override
2247 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2248 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2249 "setActivityController()");
2250 synchronized (mGlobalLock) {
2251 mController = controller;
2252 mControllerIsAMonkey = imAMonkey;
2253 Watchdog.getInstance().setActivityController(controller);
2254 }
2255 }
2256
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002257 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002258 synchronized (mGlobalLock) {
2259 return mController != null && mControllerIsAMonkey;
2260 }
2261 }
2262
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002263 @Override
2264 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2265 synchronized (mGlobalLock) {
2266 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2267 }
2268 }
2269
2270 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002271 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2272 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2273 }
2274
2275 @Override
2276 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2277 @WindowConfiguration.ActivityType int ignoreActivityType,
2278 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2279 final int callingUid = Binder.getCallingUid();
2280 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2281
2282 synchronized (mGlobalLock) {
2283 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2284
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002285 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002286 callingUid);
2287 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2288 ignoreWindowingMode, callingUid, allowed);
2289 }
2290
2291 return list;
2292 }
2293
2294 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002295 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2296 synchronized (mGlobalLock) {
2297 final long origId = Binder.clearCallingIdentity();
2298 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2299 if (r != null) {
2300 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2301 }
2302 Binder.restoreCallingIdentity(origId);
2303 }
2304 }
2305
2306 @Override
2307 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002308 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002309 ActivityStack stack = ActivityRecord.getStackLocked(token);
2310 if (stack != null) {
2311 return stack.willActivityBeVisibleLocked(token);
2312 }
2313 return false;
2314 }
2315 }
2316
2317 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002318 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002319 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002320 synchronized (mGlobalLock) {
2321 final long ident = Binder.clearCallingIdentity();
2322 try {
2323 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2324 if (task == null) {
2325 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2326 return;
2327 }
2328
2329 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2330 + " to stackId=" + stackId + " toTop=" + toTop);
2331
2332 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2333 if (stack == null) {
2334 throw new IllegalStateException(
2335 "moveTaskToStack: No stack for stackId=" + stackId);
2336 }
2337 if (!stack.isActivityTypeStandardOrUndefined()) {
2338 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2339 + taskId + " to stack " + stackId);
2340 }
2341 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002342 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002343 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2344 }
2345 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2346 "moveTaskToStack");
2347 } finally {
2348 Binder.restoreCallingIdentity(ident);
2349 }
2350 }
2351 }
2352
2353 @Override
2354 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2355 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002356 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002357
2358 final long ident = Binder.clearCallingIdentity();
2359 try {
2360 synchronized (mGlobalLock) {
2361 if (animate) {
2362 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2363 if (stack == null) {
2364 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2365 return;
2366 }
2367 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2368 throw new IllegalArgumentException("Stack: " + stackId
2369 + " doesn't support animated resize.");
2370 }
2371 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2372 animationDuration, false /* fromFullscreen */);
2373 } else {
2374 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2375 if (stack == null) {
2376 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2377 return;
2378 }
2379 mStackSupervisor.resizeStackLocked(stack, destBounds,
2380 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2381 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2382 }
2383 }
2384 } finally {
2385 Binder.restoreCallingIdentity(ident);
2386 }
2387 }
2388
2389 /**
2390 * Moves the specified task to the primary-split-screen stack.
2391 *
2392 * @param taskId Id of task to move.
2393 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2394 * exist already. See
2395 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2396 * and
2397 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2398 * @param toTop If the task and stack should be moved to the top.
2399 * @param animate Whether we should play an animation for the moving the task.
2400 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2401 * stack. Pass {@code null} to use default bounds.
2402 * @param showRecents If the recents activity should be shown on the other side of the task
2403 * going into split-screen mode.
2404 */
2405 @Override
2406 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2407 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002408 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002409 "setTaskWindowingModeSplitScreenPrimary()");
2410 synchronized (mGlobalLock) {
2411 final long ident = Binder.clearCallingIdentity();
2412 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002413 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2414 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002415 if (task == null) {
2416 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2417 return false;
2418 }
2419 if (DEBUG_STACK) Slog.d(TAG_STACK,
2420 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2421 + " to createMode=" + createMode + " toTop=" + toTop);
2422 if (!task.isActivityTypeStandardOrUndefined()) {
2423 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2424 + " non-standard task " + taskId + " to split-screen windowing mode");
2425 }
2426
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002427 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002428 final int windowingMode = task.getWindowingMode();
2429 final ActivityStack stack = task.getStack();
2430 if (toTop) {
2431 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2432 }
2433 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002434 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2435 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002436 return windowingMode != task.getWindowingMode();
2437 } finally {
2438 Binder.restoreCallingIdentity(ident);
2439 }
2440 }
2441 }
2442
2443 /**
2444 * Removes stacks in the input windowing modes from the system if they are of activity type
2445 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2446 */
2447 @Override
2448 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002449 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002450 "removeStacksInWindowingModes()");
2451
2452 synchronized (mGlobalLock) {
2453 final long ident = Binder.clearCallingIdentity();
2454 try {
2455 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2456 } finally {
2457 Binder.restoreCallingIdentity(ident);
2458 }
2459 }
2460 }
2461
2462 @Override
2463 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002464 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002465 "removeStacksWithActivityTypes()");
2466
2467 synchronized (mGlobalLock) {
2468 final long ident = Binder.clearCallingIdentity();
2469 try {
2470 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2471 } finally {
2472 Binder.restoreCallingIdentity(ident);
2473 }
2474 }
2475 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002476
2477 @Override
2478 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2479 int userId) {
2480 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002481 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2482 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002483 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002484 final boolean detailed = checkGetTasksPermission(
2485 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2486 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002487 == PackageManager.PERMISSION_GRANTED;
2488
2489 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002490 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002491 callingUid);
2492 }
2493 }
2494
2495 @Override
2496 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002497 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002498 long ident = Binder.clearCallingIdentity();
2499 try {
2500 synchronized (mGlobalLock) {
2501 return mStackSupervisor.getAllStackInfosLocked();
2502 }
2503 } finally {
2504 Binder.restoreCallingIdentity(ident);
2505 }
2506 }
2507
2508 @Override
2509 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002510 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002511 long ident = Binder.clearCallingIdentity();
2512 try {
2513 synchronized (mGlobalLock) {
2514 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2515 }
2516 } finally {
2517 Binder.restoreCallingIdentity(ident);
2518 }
2519 }
2520
2521 @Override
2522 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002523 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002524 final long callingUid = Binder.getCallingUid();
2525 final long origId = Binder.clearCallingIdentity();
2526 try {
2527 synchronized (mGlobalLock) {
2528 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2531 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2532 }
2533 } finally {
2534 Binder.restoreCallingIdentity(origId);
2535 }
2536 }
2537
2538 @Override
2539 public void startLockTaskModeByToken(IBinder token) {
2540 synchronized (mGlobalLock) {
2541 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2542 if (r == null) {
2543 return;
2544 }
2545 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2546 }
2547 }
2548
2549 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002550 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002551 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002552 // This makes inner call to look as if it was initiated by system.
2553 long ident = Binder.clearCallingIdentity();
2554 try {
2555 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002556 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2557 MATCH_TASK_IN_STACKS_ONLY);
2558 if (task == null) {
2559 return;
2560 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002561
2562 // When starting lock task mode the stack must be in front and focused
2563 task.getStack().moveToFront("startSystemLockTaskMode");
2564 startLockTaskModeLocked(task, true /* isSystemCaller */);
2565 }
2566 } finally {
2567 Binder.restoreCallingIdentity(ident);
2568 }
2569 }
2570
2571 @Override
2572 public void stopLockTaskModeByToken(IBinder token) {
2573 synchronized (mGlobalLock) {
2574 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2575 if (r == null) {
2576 return;
2577 }
2578 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2579 }
2580 }
2581
2582 /**
2583 * This API should be called by SystemUI only when user perform certain action to dismiss
2584 * lock task mode. We should only dismiss pinned lock task mode in this case.
2585 */
2586 @Override
2587 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002588 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002589 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2590 }
2591
2592 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2593 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2594 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2595 return;
2596 }
2597
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002598 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 if (stack == null || task != stack.topTask()) {
2600 throw new IllegalArgumentException("Invalid task, not in foreground");
2601 }
2602
2603 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2604 // system or a specific app.
2605 // * System-initiated requests will only start the pinned mode (screen pinning)
2606 // * App-initiated requests
2607 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2608 // - will start the pinned mode, otherwise
2609 final int callingUid = Binder.getCallingUid();
2610 long ident = Binder.clearCallingIdentity();
2611 try {
2612 // When a task is locked, dismiss the pinned stack if it exists
2613 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2614
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002615 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002616 } finally {
2617 Binder.restoreCallingIdentity(ident);
2618 }
2619 }
2620
2621 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2622 final int callingUid = Binder.getCallingUid();
2623 long ident = Binder.clearCallingIdentity();
2624 try {
2625 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002626 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002627 }
2628 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2629 // task and jumping straight into a call in the case of emergency call back.
2630 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2631 if (tm != null) {
2632 tm.showInCallScreen(false);
2633 }
2634 } finally {
2635 Binder.restoreCallingIdentity(ident);
2636 }
2637 }
2638
2639 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002640 public void updateLockTaskPackages(int userId, String[] packages) {
2641 final int callingUid = Binder.getCallingUid();
2642 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2643 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2644 "updateLockTaskPackages()");
2645 }
2646 synchronized (this) {
2647 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2648 + Arrays.toString(packages));
2649 getLockTaskController().updateLockTaskPackages(userId, packages);
2650 }
2651 }
2652
2653 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 public boolean isInLockTaskMode() {
2655 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2656 }
2657
2658 @Override
2659 public int getLockTaskModeState() {
2660 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002661 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002662 }
2663 }
2664
2665 @Override
2666 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2667 synchronized (mGlobalLock) {
2668 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2669 if (r != null) {
2670 r.setTaskDescription(td);
2671 final TaskRecord task = r.getTask();
2672 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002673 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 }
2675 }
2676 }
2677
2678 @Override
2679 public Bundle getActivityOptions(IBinder token) {
2680 final long origId = Binder.clearCallingIdentity();
2681 try {
2682 synchronized (mGlobalLock) {
2683 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2684 if (r != null) {
2685 final ActivityOptions activityOptions = r.takeOptionsLocked();
2686 return activityOptions == null ? null : activityOptions.toBundle();
2687 }
2688 return null;
2689 }
2690 } finally {
2691 Binder.restoreCallingIdentity(origId);
2692 }
2693 }
2694
2695 @Override
2696 public List<IBinder> getAppTasks(String callingPackage) {
2697 int callingUid = Binder.getCallingUid();
2698 long ident = Binder.clearCallingIdentity();
2699 try {
2700 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002701 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002702 }
2703 } finally {
2704 Binder.restoreCallingIdentity(ident);
2705 }
2706 }
2707
2708 @Override
2709 public void finishVoiceTask(IVoiceInteractionSession session) {
2710 synchronized (mGlobalLock) {
2711 final long origId = Binder.clearCallingIdentity();
2712 try {
2713 // TODO: VI Consider treating local voice interactions and voice tasks
2714 // differently here
2715 mStackSupervisor.finishVoiceTask(session);
2716 } finally {
2717 Binder.restoreCallingIdentity(origId);
2718 }
2719 }
2720
2721 }
2722
2723 @Override
2724 public boolean isTopOfTask(IBinder token) {
2725 synchronized (mGlobalLock) {
2726 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002727 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002728 }
2729 }
2730
2731 @Override
2732 public void notifyLaunchTaskBehindComplete(IBinder token) {
2733 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2734 }
2735
2736 @Override
2737 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002738 mH.post(() -> {
2739 synchronized (mGlobalLock) {
2740 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002741 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002742 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002743 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002744 } catch (RemoteException e) {
2745 }
2746 }
2747 }
2748
2749 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002750 }
2751
2752 /** Called from an app when assist data is ready. */
2753 @Override
2754 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2755 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002756 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002757 synchronized (pae) {
2758 pae.result = extras;
2759 pae.structure = structure;
2760 pae.content = content;
2761 if (referrer != null) {
2762 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2763 }
2764 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002765 // Pre-fill the task/activity component for all assist data receivers
2766 structure.setTaskId(pae.activity.getTask().taskId);
2767 structure.setActivityComponent(pae.activity.realActivity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002768 structure.setHomeActivity(pae.isHome);
2769 }
2770 pae.haveResult = true;
2771 pae.notifyAll();
2772 if (pae.intent == null && pae.receiver == null) {
2773 // Caller is just waiting for the result.
2774 return;
2775 }
2776 }
2777 // We are now ready to launch the assist activity.
2778 IAssistDataReceiver sendReceiver = null;
2779 Bundle sendBundle = null;
2780 synchronized (mGlobalLock) {
2781 buildAssistBundleLocked(pae, extras);
2782 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002783 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002784 if (!exists) {
2785 // Timed out.
2786 return;
2787 }
2788
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002789 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002790 // Caller wants result sent back to them.
2791 sendBundle = new Bundle();
2792 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2793 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2794 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2795 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2796 }
2797 }
2798 if (sendReceiver != null) {
2799 try {
2800 sendReceiver.onHandleAssistData(sendBundle);
2801 } catch (RemoteException e) {
2802 }
2803 return;
2804 }
2805
2806 final long ident = Binder.clearCallingIdentity();
2807 try {
2808 if (TextUtils.equals(pae.intent.getAction(),
2809 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2810 pae.intent.putExtras(pae.extras);
2811 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2812 } else {
2813 pae.intent.replaceExtras(pae.extras);
2814 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2815 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2816 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002817 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818
2819 try {
2820 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2821 } catch (ActivityNotFoundException e) {
2822 Slog.w(TAG, "No activity to handle assist action.", e);
2823 }
2824 }
2825 } finally {
2826 Binder.restoreCallingIdentity(ident);
2827 }
2828 }
2829
2830 @Override
2831 public int addAppTask(IBinder activityToken, Intent intent,
2832 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2833 final int callingUid = Binder.getCallingUid();
2834 final long callingIdent = Binder.clearCallingIdentity();
2835
2836 try {
2837 synchronized (mGlobalLock) {
2838 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2839 if (r == null) {
2840 throw new IllegalArgumentException("Activity does not exist; token="
2841 + activityToken);
2842 }
2843 ComponentName comp = intent.getComponent();
2844 if (comp == null) {
2845 throw new IllegalArgumentException("Intent " + intent
2846 + " must specify explicit component");
2847 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002848 if (thumbnail.getWidth() != mThumbnailWidth
2849 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 throw new IllegalArgumentException("Bad thumbnail size: got "
2851 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002852 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002853 }
2854 if (intent.getSelector() != null) {
2855 intent.setSelector(null);
2856 }
2857 if (intent.getSourceBounds() != null) {
2858 intent.setSourceBounds(null);
2859 }
2860 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2861 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2862 // The caller has added this as an auto-remove task... that makes no
2863 // sense, so turn off auto-remove.
2864 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2865 }
2866 }
2867 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2868 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2869 if (ainfo.applicationInfo.uid != callingUid) {
2870 throw new SecurityException(
2871 "Can't add task for another application: target uid="
2872 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2873 }
2874
2875 final ActivityStack stack = r.getStack();
2876 final TaskRecord task = stack.createTaskRecord(
2877 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2878 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002879 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002880 // The app has too many tasks already and we can't add any more
2881 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2882 return INVALID_TASK_ID;
2883 }
2884 task.lastTaskDescription.copyFrom(description);
2885
2886 // TODO: Send the thumbnail to WM to store it.
2887
2888 return task.taskId;
2889 }
2890 } finally {
2891 Binder.restoreCallingIdentity(callingIdent);
2892 }
2893 }
2894
2895 @Override
2896 public Point getAppTaskThumbnailSize() {
2897 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002898 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899 }
2900 }
2901
2902 @Override
2903 public void setTaskResizeable(int taskId, int resizeableMode) {
2904 synchronized (mGlobalLock) {
2905 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2906 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2907 if (task == null) {
2908 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2909 return;
2910 }
2911 task.setResizeMode(resizeableMode);
2912 }
2913 }
2914
2915 @Override
2916 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002917 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002918 long ident = Binder.clearCallingIdentity();
2919 try {
2920 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002921 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2922 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 if (task == null) {
2924 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2925 return;
2926 }
2927 // Place the task in the right stack if it isn't there already based on
2928 // the requested bounds.
2929 // The stack transition logic is:
2930 // - a null bounds on a freeform task moves that task to fullscreen
2931 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2932 // that task to freeform
2933 // - otherwise the task is not moved
2934 ActivityStack stack = task.getStack();
2935 if (!task.getWindowConfiguration().canResizeTask()) {
2936 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2937 }
2938 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2939 stack = stack.getDisplay().getOrCreateStack(
2940 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2941 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2942 stack = stack.getDisplay().getOrCreateStack(
2943 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2944 }
2945
2946 // Reparent the task to the right stack if necessary
2947 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2948 if (stack != task.getStack()) {
2949 // Defer resume until the task is resized below
2950 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2951 DEFER_RESUME, "resizeTask");
2952 preserveWindow = false;
2953 }
2954
2955 // After reparenting (which only resizes the task to the stack bounds), resize the
2956 // task to the actual bounds provided
2957 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2958 }
2959 } finally {
2960 Binder.restoreCallingIdentity(ident);
2961 }
2962 }
2963
2964 @Override
2965 public boolean releaseActivityInstance(IBinder token) {
2966 synchronized (mGlobalLock) {
2967 final long origId = Binder.clearCallingIdentity();
2968 try {
2969 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2970 if (r == null) {
2971 return false;
2972 }
2973 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2974 } finally {
2975 Binder.restoreCallingIdentity(origId);
2976 }
2977 }
2978 }
2979
2980 @Override
2981 public void releaseSomeActivities(IApplicationThread appInt) {
2982 synchronized (mGlobalLock) {
2983 final long origId = Binder.clearCallingIdentity();
2984 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002985 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002986 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2987 } finally {
2988 Binder.restoreCallingIdentity(origId);
2989 }
2990 }
2991 }
2992
2993 @Override
2994 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002995 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002996 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 != PackageManager.PERMISSION_GRANTED) {
2998 throw new SecurityException("Requires permission "
2999 + android.Manifest.permission.DEVICE_POWER);
3000 }
3001
3002 synchronized (mGlobalLock) {
3003 long ident = Binder.clearCallingIdentity();
3004 if (mKeyguardShown != keyguardShowing) {
3005 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003006 final Message msg = PooledLambda.obtainMessage(
3007 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3008 keyguardShowing);
3009 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003010 }
3011 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003012 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003013 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003014 } finally {
3015 Binder.restoreCallingIdentity(ident);
3016 }
3017 }
3018
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003019 mH.post(() -> {
3020 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3021 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3022 }
3023 });
3024 }
3025
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003026 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003027 mH.post(() -> {
3028 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3029 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3030 }
3031 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 }
3033
3034 @Override
3035 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003036 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3037 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003038
3039 final File passedIconFile = new File(filePath);
3040 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3041 passedIconFile.getName());
3042 if (!legitIconFile.getPath().equals(filePath)
3043 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3044 throw new IllegalArgumentException("Bad file path: " + filePath
3045 + " passed for userId " + userId);
3046 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003047 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003048 }
3049
3050 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003051 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003052 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3053 final ActivityOptions activityOptions = safeOptions != null
3054 ? safeOptions.getOptions(mStackSupervisor)
3055 : null;
3056 if (activityOptions == null
3057 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3058 || activityOptions.getCustomInPlaceResId() == 0) {
3059 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3060 "with valid animation");
3061 }
lumark588a3e82018-07-20 18:53:54 +08003062 // Get top display of front most application.
3063 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3064 if (focusedStack != null) {
3065 final DisplayWindowController dwc =
3066 focusedStack.getDisplay().getWindowContainerController();
3067 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3068 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
3069 activityOptions.getCustomInPlaceResId());
3070 dwc.executeAppTransition();
3071 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003072 }
3073
3074 @Override
3075 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003076 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003077 synchronized (mGlobalLock) {
3078 final long ident = Binder.clearCallingIdentity();
3079 try {
3080 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3081 if (stack == null) {
3082 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3083 return;
3084 }
3085 if (!stack.isActivityTypeStandardOrUndefined()) {
3086 throw new IllegalArgumentException(
3087 "Removing non-standard stack is not allowed.");
3088 }
3089 mStackSupervisor.removeStack(stack);
3090 } finally {
3091 Binder.restoreCallingIdentity(ident);
3092 }
3093 }
3094 }
3095
3096 @Override
3097 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003098 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099
3100 synchronized (mGlobalLock) {
3101 final long ident = Binder.clearCallingIdentity();
3102 try {
3103 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3104 + " to displayId=" + displayId);
3105 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
3106 } finally {
3107 Binder.restoreCallingIdentity(ident);
3108 }
3109 }
3110 }
3111
3112 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003113 public void exitFreeformMode(IBinder token) {
3114 synchronized (mGlobalLock) {
3115 long ident = Binder.clearCallingIdentity();
3116 try {
3117 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3118 if (r == null) {
3119 throw new IllegalArgumentException(
3120 "exitFreeformMode: No activity record matching token=" + token);
3121 }
3122
3123 final ActivityStack stack = r.getStack();
3124 if (stack == null || !stack.inFreeformWindowingMode()) {
3125 throw new IllegalStateException(
3126 "exitFreeformMode: You can only go fullscreen from freeform.");
3127 }
3128
3129 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3130 } finally {
3131 Binder.restoreCallingIdentity(ident);
3132 }
3133 }
3134 }
3135
3136 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3137 @Override
3138 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003139 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003141 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003142 }
3143
3144 /** Unregister a task stack listener so that it stops receiving callbacks. */
3145 @Override
3146 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003147 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003149 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 }
3151
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 @Override
3153 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3154 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3155 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3156 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3157 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3158 }
3159
3160 @Override
3161 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3162 IBinder activityToken, int flags) {
3163 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3164 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3165 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3166 }
3167
3168 @Override
3169 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3170 Bundle args) {
3171 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3172 true /* focused */, true /* newSessionId */, userHandle, args,
3173 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3174 }
3175
3176 @Override
3177 public Bundle getAssistContextExtras(int requestType) {
3178 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3179 null, null, true /* focused */, true /* newSessionId */,
3180 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3181 if (pae == null) {
3182 return null;
3183 }
3184 synchronized (pae) {
3185 while (!pae.haveResult) {
3186 try {
3187 pae.wait();
3188 } catch (InterruptedException e) {
3189 }
3190 }
3191 }
3192 synchronized (mGlobalLock) {
3193 buildAssistBundleLocked(pae, pae.result);
3194 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003195 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197 return pae.extras;
3198 }
3199
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003200 /**
3201 * Binder IPC calls go through the public entry point.
3202 * This can be called with or without the global lock held.
3203 */
3204 private static int checkCallingPermission(String permission) {
3205 return checkPermission(
3206 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3207 }
3208
3209 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003210 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003211 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3212 mAmInternal.enforceCallingPermission(permission, func);
3213 }
3214 }
3215
3216 @VisibleForTesting
3217 int checkGetTasksPermission(String permission, int pid, int uid) {
3218 return checkPermission(permission, pid, uid);
3219 }
3220
3221 static int checkPermission(String permission, int pid, int uid) {
3222 if (permission == null) {
3223 return PackageManager.PERMISSION_DENIED;
3224 }
3225 return checkComponentPermission(permission, pid, uid, -1, true);
3226 }
3227
Wale Ogunwale214f3482018-10-04 11:00:47 -07003228 public static int checkComponentPermission(String permission, int pid, int uid,
3229 int owningUid, boolean exported) {
3230 return ActivityManagerService.checkComponentPermission(
3231 permission, pid, uid, owningUid, exported);
3232 }
3233
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003234 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3235 if (getRecentTasks().isCallerRecents(callingUid)) {
3236 // Always allow the recents component to get tasks
3237 return true;
3238 }
3239
3240 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3241 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3242 if (!allowed) {
3243 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3244 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3245 // Temporary compatibility: some existing apps on the system image may
3246 // still be requesting the old permission and not switched to the new
3247 // one; if so, we'll still allow them full access. This means we need
3248 // to see if they are holding the old permission and are a system app.
3249 try {
3250 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3251 allowed = true;
3252 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3253 + " is using old GET_TASKS but privileged; allowing");
3254 }
3255 } catch (RemoteException e) {
3256 }
3257 }
3258 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3259 + " does not hold REAL_GET_TASKS; limiting output");
3260 }
3261 return allowed;
3262 }
3263
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003264 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3265 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3266 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3267 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003268 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003269 "enqueueAssistContext()");
3270
3271 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003272 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003273 if (activity == null) {
3274 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3275 return null;
3276 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003277 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003278 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3279 return null;
3280 }
3281 if (focused) {
3282 if (activityToken != null) {
3283 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3284 if (activity != caller) {
3285 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3286 + " is not current top " + activity);
3287 return null;
3288 }
3289 }
3290 } else {
3291 activity = ActivityRecord.forTokenLocked(activityToken);
3292 if (activity == null) {
3293 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3294 + " couldn't be found");
3295 return null;
3296 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003297 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003298 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3299 return null;
3300 }
3301 }
3302
3303 PendingAssistExtras pae;
3304 Bundle extras = new Bundle();
3305 if (args != null) {
3306 extras.putAll(args);
3307 }
3308 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003309 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310
3311 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3312 userHandle);
3313 pae.isHome = activity.isActivityTypeHome();
3314
3315 // Increment the sessionId if necessary
3316 if (newSessionId) {
3317 mViSessionId++;
3318 }
3319 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003320 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3321 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003323 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 } catch (RemoteException e) {
3325 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3326 return null;
3327 }
3328 return pae;
3329 }
3330 }
3331
3332 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3333 if (result != null) {
3334 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3335 }
3336 if (pae.hint != null) {
3337 pae.extras.putBoolean(pae.hint, true);
3338 }
3339 }
3340
3341 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3342 IAssistDataReceiver receiver;
3343 synchronized (mGlobalLock) {
3344 mPendingAssistExtras.remove(pae);
3345 receiver = pae.receiver;
3346 }
3347 if (receiver != null) {
3348 // Caller wants result sent back to them.
3349 Bundle sendBundle = new Bundle();
3350 // At least return the receiver extras
3351 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3352 try {
3353 pae.receiver.onHandleAssistData(sendBundle);
3354 } catch (RemoteException e) {
3355 }
3356 }
3357 }
3358
3359 public class PendingAssistExtras extends Binder implements Runnable {
3360 public final ActivityRecord activity;
3361 public boolean isHome;
3362 public final Bundle extras;
3363 public final Intent intent;
3364 public final String hint;
3365 public final IAssistDataReceiver receiver;
3366 public final int userHandle;
3367 public boolean haveResult = false;
3368 public Bundle result = null;
3369 public AssistStructure structure = null;
3370 public AssistContent content = null;
3371 public Bundle receiverExtras;
3372
3373 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3374 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3375 int _userHandle) {
3376 activity = _activity;
3377 extras = _extras;
3378 intent = _intent;
3379 hint = _hint;
3380 receiver = _receiver;
3381 receiverExtras = _receiverExtras;
3382 userHandle = _userHandle;
3383 }
3384
3385 @Override
3386 public void run() {
3387 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3388 synchronized (this) {
3389 haveResult = true;
3390 notifyAll();
3391 }
3392 pendingAssistExtrasTimedOut(this);
3393 }
3394 }
3395
3396 @Override
3397 public boolean isAssistDataAllowedOnCurrentActivity() {
3398 int userId;
3399 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003400 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3402 return false;
3403 }
3404
3405 final ActivityRecord activity = focusedStack.getTopActivity();
3406 if (activity == null) {
3407 return false;
3408 }
3409 userId = activity.userId;
3410 }
3411 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3412 }
3413
3414 @Override
3415 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3416 long ident = Binder.clearCallingIdentity();
3417 try {
3418 synchronized (mGlobalLock) {
3419 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003420 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003421 if (top != caller) {
3422 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3423 + " is not current top " + top);
3424 return false;
3425 }
3426 if (!top.nowVisible) {
3427 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3428 + " is not visible");
3429 return false;
3430 }
3431 }
3432 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3433 token);
3434 } finally {
3435 Binder.restoreCallingIdentity(ident);
3436 }
3437 }
3438
3439 @Override
3440 public boolean isRootVoiceInteraction(IBinder token) {
3441 synchronized (mGlobalLock) {
3442 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3443 if (r == null) {
3444 return false;
3445 }
3446 return r.rootVoiceInteraction;
3447 }
3448 }
3449
Wale Ogunwalef6733932018-06-27 05:14:34 -07003450 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3451 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3452 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3453 if (activityToCallback == null) return;
3454 activityToCallback.setVoiceSessionLocked(voiceSession);
3455
3456 // Inform the activity
3457 try {
3458 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3459 voiceInteractor);
3460 long token = Binder.clearCallingIdentity();
3461 try {
3462 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3463 } finally {
3464 Binder.restoreCallingIdentity(token);
3465 }
3466 // TODO: VI Should we cache the activity so that it's easier to find later
3467 // rather than scan through all the stacks and activities?
3468 } catch (RemoteException re) {
3469 activityToCallback.clearVoiceSessionLocked();
3470 // TODO: VI Should this terminate the voice session?
3471 }
3472 }
3473
3474 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3475 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3476 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3477 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3478 boolean wasRunningVoice = mRunningVoice != null;
3479 mRunningVoice = session;
3480 if (!wasRunningVoice) {
3481 mVoiceWakeLock.acquire();
3482 updateSleepIfNeededLocked();
3483 }
3484 }
3485 }
3486
3487 void finishRunningVoiceLocked() {
3488 if (mRunningVoice != null) {
3489 mRunningVoice = null;
3490 mVoiceWakeLock.release();
3491 updateSleepIfNeededLocked();
3492 }
3493 }
3494
3495 @Override
3496 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3497 synchronized (mGlobalLock) {
3498 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3499 if (keepAwake) {
3500 mVoiceWakeLock.acquire();
3501 } else {
3502 mVoiceWakeLock.release();
3503 }
3504 }
3505 }
3506 }
3507
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003508 @Override
3509 public ComponentName getActivityClassForToken(IBinder token) {
3510 synchronized (mGlobalLock) {
3511 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3512 if (r == null) {
3513 return null;
3514 }
3515 return r.intent.getComponent();
3516 }
3517 }
3518
3519 @Override
3520 public String getPackageForToken(IBinder token) {
3521 synchronized (mGlobalLock) {
3522 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3523 if (r == null) {
3524 return null;
3525 }
3526 return r.packageName;
3527 }
3528 }
3529
3530 @Override
3531 public void showLockTaskEscapeMessage(IBinder token) {
3532 synchronized (mGlobalLock) {
3533 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3534 if (r == null) {
3535 return;
3536 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003537 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003538 }
3539 }
3540
3541 @Override
3542 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003543 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003544 final long token = Binder.clearCallingIdentity();
3545 try {
3546 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003547 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003548 }
3549 } finally {
3550 Binder.restoreCallingIdentity(token);
3551 }
3552 }
3553
3554 /**
3555 * Try to place task to provided position. The final position might be different depending on
3556 * current user and stacks state. The task will be moved to target stack if it's currently in
3557 * different stack.
3558 */
3559 @Override
3560 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003561 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003562 synchronized (mGlobalLock) {
3563 long ident = Binder.clearCallingIdentity();
3564 try {
3565 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3566 + taskId + " in stackId=" + stackId + " at position=" + position);
3567 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3568 if (task == null) {
3569 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3570 + taskId);
3571 }
3572
3573 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3574
3575 if (stack == null) {
3576 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3577 + stackId);
3578 }
3579 if (!stack.isActivityTypeStandardOrUndefined()) {
3580 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3581 + " the position of task " + taskId + " in/to non-standard stack");
3582 }
3583
3584 // TODO: Have the callers of this API call a separate reparent method if that is
3585 // what they intended to do vs. having this method also do reparenting.
3586 if (task.getStack() == stack) {
3587 // Change position in current stack.
3588 stack.positionChildAt(task, position);
3589 } else {
3590 // Reparent to new stack.
3591 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3592 !DEFER_RESUME, "positionTaskInStack");
3593 }
3594 } finally {
3595 Binder.restoreCallingIdentity(ident);
3596 }
3597 }
3598 }
3599
3600 @Override
3601 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3602 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3603 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3604 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3605 synchronized (mGlobalLock) {
3606 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3607 if (record == null) {
3608 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3609 + "found for: " + token);
3610 }
3611 record.setSizeConfigurations(horizontalSizeConfiguration,
3612 verticalSizeConfigurations, smallestSizeConfigurations);
3613 }
3614 }
3615
3616 /**
3617 * Dismisses split-screen multi-window mode.
3618 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3619 */
3620 @Override
3621 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003622 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003623 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3624 final long ident = Binder.clearCallingIdentity();
3625 try {
3626 synchronized (mGlobalLock) {
3627 final ActivityStack stack =
3628 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3629 if (stack == null) {
3630 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3631 return;
3632 }
3633
3634 if (toTop) {
3635 // Caller wants the current split-screen primary stack to be the top stack after
3636 // it goes fullscreen, so move it to the front.
3637 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003638 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003639 // In this case the current split-screen primary stack shouldn't be the top
3640 // stack after it goes fullscreen, but it current has focus, so we move the
3641 // focus to the top-most split-screen secondary stack next to it.
3642 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3643 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3644 if (otherStack != null) {
3645 otherStack.moveToFront("dismissSplitScreenMode_other");
3646 }
3647 }
3648
Evan Rosky10475742018-09-05 19:02:48 -07003649 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003650 }
3651 } finally {
3652 Binder.restoreCallingIdentity(ident);
3653 }
3654 }
3655
3656 /**
3657 * Dismisses Pip
3658 * @param animate True if the dismissal should be animated.
3659 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3660 * default animation duration should be used.
3661 */
3662 @Override
3663 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003664 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003665 final long ident = Binder.clearCallingIdentity();
3666 try {
3667 synchronized (mGlobalLock) {
3668 final PinnedActivityStack stack =
3669 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3670 if (stack == null) {
3671 Slog.w(TAG, "dismissPip: pinned stack not found.");
3672 return;
3673 }
3674 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3675 throw new IllegalArgumentException("Stack: " + stack
3676 + " doesn't support animated resize.");
3677 }
3678 if (animate) {
3679 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3680 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3681 } else {
3682 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3683 }
3684 }
3685 } finally {
3686 Binder.restoreCallingIdentity(ident);
3687 }
3688 }
3689
3690 @Override
3691 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003692 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003693 synchronized (mGlobalLock) {
3694 mSuppressResizeConfigChanges = suppress;
3695 }
3696 }
3697
3698 /**
3699 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3700 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3701 * activity and clearing the task at the same time.
3702 */
3703 @Override
3704 // TODO: API should just be about changing windowing modes...
3705 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003706 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003707 "moveTasksToFullscreenStack()");
3708 synchronized (mGlobalLock) {
3709 final long origId = Binder.clearCallingIdentity();
3710 try {
3711 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3712 if (stack != null){
3713 if (!stack.isActivityTypeStandardOrUndefined()) {
3714 throw new IllegalArgumentException(
3715 "You can't move tasks from non-standard stacks.");
3716 }
3717 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3718 }
3719 } finally {
3720 Binder.restoreCallingIdentity(origId);
3721 }
3722 }
3723 }
3724
3725 /**
3726 * Moves the top activity in the input stackId to the pinned stack.
3727 *
3728 * @param stackId Id of stack to move the top activity to pinned stack.
3729 * @param bounds Bounds to use for pinned stack.
3730 *
3731 * @return True if the top activity of the input stack was successfully moved to the pinned
3732 * stack.
3733 */
3734 @Override
3735 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003736 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003737 "moveTopActivityToPinnedStack()");
3738 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003739 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3741 + "Device doesn't support picture-in-picture mode");
3742 }
3743
3744 long ident = Binder.clearCallingIdentity();
3745 try {
3746 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3747 } finally {
3748 Binder.restoreCallingIdentity(ident);
3749 }
3750 }
3751 }
3752
3753 @Override
3754 public boolean isInMultiWindowMode(IBinder token) {
3755 final long origId = Binder.clearCallingIdentity();
3756 try {
3757 synchronized (mGlobalLock) {
3758 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3759 if (r == null) {
3760 return false;
3761 }
3762 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3763 return r.inMultiWindowMode();
3764 }
3765 } finally {
3766 Binder.restoreCallingIdentity(origId);
3767 }
3768 }
3769
3770 @Override
3771 public boolean isInPictureInPictureMode(IBinder token) {
3772 final long origId = Binder.clearCallingIdentity();
3773 try {
3774 synchronized (mGlobalLock) {
3775 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3776 }
3777 } finally {
3778 Binder.restoreCallingIdentity(origId);
3779 }
3780 }
3781
3782 private boolean isInPictureInPictureMode(ActivityRecord r) {
3783 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3784 || r.getStack().isInStackLocked(r) == null) {
3785 return false;
3786 }
3787
3788 // If we are animating to fullscreen then we have already dispatched the PIP mode
3789 // changed, so we should reflect that check here as well.
3790 final PinnedActivityStack stack = r.getStack();
3791 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3792 return !windowController.isAnimatingBoundsToFullscreen();
3793 }
3794
3795 @Override
3796 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3797 final long origId = Binder.clearCallingIdentity();
3798 try {
3799 synchronized (mGlobalLock) {
3800 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3801 "enterPictureInPictureMode", token, params);
3802
3803 // If the activity is already in picture in picture mode, then just return early
3804 if (isInPictureInPictureMode(r)) {
3805 return true;
3806 }
3807
3808 // Activity supports picture-in-picture, now check that we can enter PiP at this
3809 // point, if it is
3810 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3811 false /* beforeStopping */)) {
3812 return false;
3813 }
3814
3815 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003816 synchronized (mGlobalLock) {
3817 // Only update the saved args from the args that are set
3818 r.pictureInPictureArgs.copyOnlySet(params);
3819 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3820 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3821 // Adjust the source bounds by the insets for the transition down
3822 final Rect sourceBounds = new Rect(
3823 r.pictureInPictureArgs.getSourceRectHint());
3824 mStackSupervisor.moveActivityToPinnedStackLocked(
3825 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3826 final PinnedActivityStack stack = r.getStack();
3827 stack.setPictureInPictureAspectRatio(aspectRatio);
3828 stack.setPictureInPictureActions(actions);
3829 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3830 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3831 logPictureInPictureArgs(params);
3832 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 };
3834
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003835 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003836 // If the keyguard is showing or occluded, then try and dismiss it before
3837 // entering picture-in-picture (this will prompt the user to authenticate if the
3838 // device is currently locked).
3839 dismissKeyguard(token, new KeyguardDismissCallback() {
3840 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003841 public void onDismissSucceeded() {
3842 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 }
3844 }, null /* message */);
3845 } else {
3846 // Enter picture in picture immediately otherwise
3847 enterPipRunnable.run();
3848 }
3849 return true;
3850 }
3851 } finally {
3852 Binder.restoreCallingIdentity(origId);
3853 }
3854 }
3855
3856 @Override
3857 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3858 final long origId = Binder.clearCallingIdentity();
3859 try {
3860 synchronized (mGlobalLock) {
3861 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3862 "setPictureInPictureParams", token, params);
3863
3864 // Only update the saved args from the args that are set
3865 r.pictureInPictureArgs.copyOnlySet(params);
3866 if (r.inPinnedWindowingMode()) {
3867 // If the activity is already in picture-in-picture, update the pinned stack now
3868 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3869 // be used the next time the activity enters PiP
3870 final PinnedActivityStack stack = r.getStack();
3871 if (!stack.isAnimatingBoundsToFullscreen()) {
3872 stack.setPictureInPictureAspectRatio(
3873 r.pictureInPictureArgs.getAspectRatio());
3874 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3875 }
3876 }
3877 logPictureInPictureArgs(params);
3878 }
3879 } finally {
3880 Binder.restoreCallingIdentity(origId);
3881 }
3882 }
3883
3884 @Override
3885 public int getMaxNumPictureInPictureActions(IBinder token) {
3886 // Currently, this is a static constant, but later, we may change this to be dependent on
3887 // the context of the activity
3888 return 3;
3889 }
3890
3891 private void logPictureInPictureArgs(PictureInPictureParams params) {
3892 if (params.hasSetActions()) {
3893 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3894 params.getActions().size());
3895 }
3896 if (params.hasSetAspectRatio()) {
3897 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3898 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3899 MetricsLogger.action(lm);
3900 }
3901 }
3902
3903 /**
3904 * Checks the state of the system and the activity associated with the given {@param token} to
3905 * verify that picture-in-picture is supported for that activity.
3906 *
3907 * @return the activity record for the given {@param token} if all the checks pass.
3908 */
3909 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3910 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003911 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003912 throw new IllegalStateException(caller
3913 + ": Device doesn't support picture-in-picture mode.");
3914 }
3915
3916 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3917 if (r == null) {
3918 throw new IllegalStateException(caller
3919 + ": Can't find activity for token=" + token);
3920 }
3921
3922 if (!r.supportsPictureInPicture()) {
3923 throw new IllegalStateException(caller
3924 + ": Current activity does not support picture-in-picture.");
3925 }
3926
3927 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003928 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003929 params.getAspectRatio())) {
3930 final float minAspectRatio = mContext.getResources().getFloat(
3931 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3932 final float maxAspectRatio = mContext.getResources().getFloat(
3933 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3934 throw new IllegalArgumentException(String.format(caller
3935 + ": Aspect ratio is too extreme (must be between %f and %f).",
3936 minAspectRatio, maxAspectRatio));
3937 }
3938
3939 // Truncate the number of actions if necessary
3940 params.truncateActions(getMaxNumPictureInPictureActions(token));
3941
3942 return r;
3943 }
3944
3945 @Override
3946 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003947 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003948 synchronized (mGlobalLock) {
3949 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3950 if (r == null) {
3951 throw new IllegalArgumentException("Activity does not exist; token="
3952 + activityToken);
3953 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003954 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003955 }
3956 }
3957
3958 @Override
3959 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3960 Rect tempDockedTaskInsetBounds,
3961 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003962 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003963 long ident = Binder.clearCallingIdentity();
3964 try {
3965 synchronized (mGlobalLock) {
3966 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3967 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3968 PRESERVE_WINDOWS);
3969 }
3970 } finally {
3971 Binder.restoreCallingIdentity(ident);
3972 }
3973 }
3974
3975 @Override
3976 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003977 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003978 final long ident = Binder.clearCallingIdentity();
3979 try {
3980 synchronized (mGlobalLock) {
3981 mStackSupervisor.setSplitScreenResizing(resizing);
3982 }
3983 } finally {
3984 Binder.restoreCallingIdentity(ident);
3985 }
3986 }
3987
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003988 /**
3989 * Check that we have the features required for VR-related API calls, and throw an exception if
3990 * not.
3991 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003992 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003993 if (!mContext.getPackageManager().hasSystemFeature(
3994 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3995 throw new UnsupportedOperationException("VR mode not supported on this device!");
3996 }
3997 }
3998
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003999 @Override
4000 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004001 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004002
4003 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4004
4005 ActivityRecord r;
4006 synchronized (mGlobalLock) {
4007 r = ActivityRecord.isInStackLocked(token);
4008 }
4009
4010 if (r == null) {
4011 throw new IllegalArgumentException();
4012 }
4013
4014 int err;
4015 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
4016 VrManagerInternal.NO_ERROR) {
4017 return err;
4018 }
4019
4020 // Clear the binder calling uid since this path may call moveToTask().
4021 final long callingId = Binder.clearCallingIdentity();
4022 try {
4023 synchronized (mGlobalLock) {
4024 r.requestedVrComponent = (enabled) ? packageName : null;
4025
4026 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004027 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004028 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 }
4030 return 0;
4031 }
4032 } finally {
4033 Binder.restoreCallingIdentity(callingId);
4034 }
4035 }
4036
4037 @Override
4038 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4039 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4040 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004041 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004042 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4043 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4044 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004045 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046 || activity.voiceSession != null) {
4047 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4048 return;
4049 }
4050 if (activity.pendingVoiceInteractionStart) {
4051 Slog.w(TAG, "Pending start of voice interaction already.");
4052 return;
4053 }
4054 activity.pendingVoiceInteractionStart = true;
4055 }
4056 LocalServices.getService(VoiceInteractionManagerInternal.class)
4057 .startLocalVoiceInteraction(callingActivity, options);
4058 }
4059
4060 @Override
4061 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4062 LocalServices.getService(VoiceInteractionManagerInternal.class)
4063 .stopLocalVoiceInteraction(callingActivity);
4064 }
4065
4066 @Override
4067 public boolean supportsLocalVoiceInteraction() {
4068 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4069 .supportsLocalVoiceInteraction();
4070 }
4071
4072 /** Notifies all listeners when the pinned stack animation starts. */
4073 @Override
4074 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004075 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 }
4077
4078 /** Notifies all listeners when the pinned stack animation ends. */
4079 @Override
4080 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004081 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004082 }
4083
4084 @Override
4085 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004086 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004087 final long ident = Binder.clearCallingIdentity();
4088 try {
4089 synchronized (mGlobalLock) {
4090 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4091 }
4092 } finally {
4093 Binder.restoreCallingIdentity(ident);
4094 }
4095 }
4096
4097 @Override
4098 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004099 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004100
4101 synchronized (mGlobalLock) {
4102 // Check if display is initialized in AM.
4103 if (!mStackSupervisor.isDisplayAdded(displayId)) {
4104 // Call might come when display is not yet added or has already been removed.
4105 if (DEBUG_CONFIGURATION) {
4106 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4107 + displayId);
4108 }
4109 return false;
4110 }
4111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004112 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004113 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004114 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004115 }
4116
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004117 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004118 final Message msg = PooledLambda.obtainMessage(
4119 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4120 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 }
4122
4123 final long origId = Binder.clearCallingIdentity();
4124 try {
4125 if (values != null) {
4126 Settings.System.clearConfiguration(values);
4127 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004128 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4130 return mTmpUpdateConfigurationResult.changes != 0;
4131 } finally {
4132 Binder.restoreCallingIdentity(origId);
4133 }
4134 }
4135 }
4136
4137 @Override
4138 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004139 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140
4141 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004142 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004143 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004144 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004145 }
4146
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004148 final Message msg = PooledLambda.obtainMessage(
4149 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4150 DEFAULT_DISPLAY);
4151 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004152 }
4153
4154 final long origId = Binder.clearCallingIdentity();
4155 try {
4156 if (values != null) {
4157 Settings.System.clearConfiguration(values);
4158 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004159 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 UserHandle.USER_NULL, false /* deferResume */,
4161 mTmpUpdateConfigurationResult);
4162 return mTmpUpdateConfigurationResult.changes != 0;
4163 } finally {
4164 Binder.restoreCallingIdentity(origId);
4165 }
4166 }
4167 }
4168
4169 @Override
4170 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4171 CharSequence message) {
4172 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004173 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4175 }
4176 final long callingId = Binder.clearCallingIdentity();
4177 try {
4178 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004179 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 }
4181 } finally {
4182 Binder.restoreCallingIdentity(callingId);
4183 }
4184 }
4185
4186 @Override
4187 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 "cancelTaskWindowTransition()");
4190 final long ident = Binder.clearCallingIdentity();
4191 try {
4192 synchronized (mGlobalLock) {
4193 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4194 MATCH_TASK_IN_STACKS_ONLY);
4195 if (task == null) {
4196 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4197 return;
4198 }
4199 task.cancelWindowTransition();
4200 }
4201 } finally {
4202 Binder.restoreCallingIdentity(ident);
4203 }
4204 }
4205
4206 @Override
4207 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004208 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 final long ident = Binder.clearCallingIdentity();
4210 try {
4211 final TaskRecord task;
4212 synchronized (mGlobalLock) {
4213 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4214 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4215 if (task == null) {
4216 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4217 return null;
4218 }
4219 }
4220 // Don't call this while holding the lock as this operation might hit the disk.
4221 return task.getSnapshot(reducedResolution);
4222 } finally {
4223 Binder.restoreCallingIdentity(ident);
4224 }
4225 }
4226
4227 @Override
4228 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4229 synchronized (mGlobalLock) {
4230 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4231 if (r == null) {
4232 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4233 + token);
4234 return;
4235 }
4236 final long origId = Binder.clearCallingIdentity();
4237 try {
4238 r.setDisablePreviewScreenshots(disable);
4239 } finally {
4240 Binder.restoreCallingIdentity(origId);
4241 }
4242 }
4243 }
4244
4245 /** Return the user id of the last resumed activity. */
4246 @Override
4247 public @UserIdInt
4248 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004249 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4251 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004252 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004255 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004256 }
4257 }
4258
4259 @Override
4260 public void updateLockTaskFeatures(int userId, int flags) {
4261 final int callingUid = Binder.getCallingUid();
4262 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004263 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004264 "updateLockTaskFeatures()");
4265 }
4266 synchronized (mGlobalLock) {
4267 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4268 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004269 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004270 }
4271 }
4272
4273 @Override
4274 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4275 synchronized (mGlobalLock) {
4276 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4277 if (r == null) {
4278 return;
4279 }
4280 final long origId = Binder.clearCallingIdentity();
4281 try {
4282 r.setShowWhenLocked(showWhenLocked);
4283 } finally {
4284 Binder.restoreCallingIdentity(origId);
4285 }
4286 }
4287 }
4288
4289 @Override
4290 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4291 synchronized (mGlobalLock) {
4292 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4293 if (r == null) {
4294 return;
4295 }
4296 final long origId = Binder.clearCallingIdentity();
4297 try {
4298 r.setTurnScreenOn(turnScreenOn);
4299 } finally {
4300 Binder.restoreCallingIdentity(origId);
4301 }
4302 }
4303 }
4304
4305 @Override
4306 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004307 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 "registerRemoteAnimations");
4309 definition.setCallingPid(Binder.getCallingPid());
4310 synchronized (mGlobalLock) {
4311 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4312 if (r == null) {
4313 return;
4314 }
4315 final long origId = Binder.clearCallingIdentity();
4316 try {
4317 r.registerRemoteAnimations(definition);
4318 } finally {
4319 Binder.restoreCallingIdentity(origId);
4320 }
4321 }
4322 }
4323
4324 @Override
4325 public void registerRemoteAnimationForNextActivityStart(String packageName,
4326 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004327 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004328 "registerRemoteAnimationForNextActivityStart");
4329 adapter.setCallingPid(Binder.getCallingPid());
4330 synchronized (mGlobalLock) {
4331 final long origId = Binder.clearCallingIdentity();
4332 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004333 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004334 packageName, adapter);
4335 } finally {
4336 Binder.restoreCallingIdentity(origId);
4337 }
4338 }
4339 }
4340
4341 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4342 @Override
4343 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4344 synchronized (mGlobalLock) {
4345 final long origId = Binder.clearCallingIdentity();
4346 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004347 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004348 } finally {
4349 Binder.restoreCallingIdentity(origId);
4350 }
4351 }
4352 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004353
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004354 @Override
4355 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004356 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004357 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004358 final int pid = Binder.getCallingPid();
4359 final WindowProcessController wpc = mPidMap.get(pid);
4360 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004361 }
4362 }
4363
4364 @Override
4365 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004366 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004367 != PERMISSION_GRANTED) {
4368 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4369 + Binder.getCallingPid()
4370 + ", uid=" + Binder.getCallingUid()
4371 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4372 Slog.w(TAG, msg);
4373 throw new SecurityException(msg);
4374 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004375 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004376 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004377 final int pid = Binder.getCallingPid();
4378 final WindowProcessController proc = mPidMap.get(pid);
4379 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004380 }
4381 }
4382
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004383 @Override
4384 public void stopAppSwitches() {
4385 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4386 synchronized (mGlobalLock) {
4387 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4388 mDidAppSwitch = false;
4389 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4390 }
4391 }
4392
4393 @Override
4394 public void resumeAppSwitches() {
4395 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4396 synchronized (mGlobalLock) {
4397 // Note that we don't execute any pending app switches... we will
4398 // let those wait until either the timeout, or the next start
4399 // activity request.
4400 mAppSwitchesAllowedTime = 0;
4401 }
4402 }
4403
4404 void onStartActivitySetDidAppSwitch() {
4405 if (mDidAppSwitch) {
4406 // This is the second allowed switch since we stopped switches, so now just generally
4407 // allow switches. Use case:
4408 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4409 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4410 // anyone to switch again).
4411 mAppSwitchesAllowedTime = 0;
4412 } else {
4413 mDidAppSwitch = true;
4414 }
4415 }
4416
4417 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004418 boolean shouldDisableNonVrUiLocked() {
4419 return mVrController.shouldDisableNonVrUiLocked();
4420 }
4421
Wale Ogunwale53783742018-09-16 10:21:51 -07004422 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004423 // VR apps are expected to run in a main display. If an app is turning on VR for
4424 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4425 // fullscreen stack before enabling VR Mode.
4426 // TODO: The goal of this code is to keep the VR app on the main display. When the
4427 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4428 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4429 // option would be a better choice here.
4430 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4431 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4432 + " to main stack for VR");
4433 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4434 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4435 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4436 }
4437 mH.post(() -> {
4438 if (!mVrController.onVrModeChanged(r)) {
4439 return;
4440 }
4441 synchronized (mGlobalLock) {
4442 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4443 mWindowManager.disableNonVrUi(disableNonVrUi);
4444 if (disableNonVrUi) {
4445 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4446 // then remove the pinned stack.
4447 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4448 }
4449 }
4450 });
4451 }
4452
Wale Ogunwale53783742018-09-16 10:21:51 -07004453 @Override
4454 public int getPackageScreenCompatMode(String packageName) {
4455 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4456 synchronized (mGlobalLock) {
4457 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4458 }
4459 }
4460
4461 @Override
4462 public void setPackageScreenCompatMode(String packageName, int mode) {
4463 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4464 "setPackageScreenCompatMode");
4465 synchronized (mGlobalLock) {
4466 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4467 }
4468 }
4469
4470 @Override
4471 public boolean getPackageAskScreenCompat(String packageName) {
4472 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4473 synchronized (mGlobalLock) {
4474 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4475 }
4476 }
4477
4478 @Override
4479 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4480 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4481 "setPackageAskScreenCompat");
4482 synchronized (mGlobalLock) {
4483 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4484 }
4485 }
4486
Wale Ogunwale64258362018-10-16 15:13:37 -07004487 public static String relaunchReasonToString(int relaunchReason) {
4488 switch (relaunchReason) {
4489 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4490 return "window_resize";
4491 case RELAUNCH_REASON_FREE_RESIZE:
4492 return "free_resize";
4493 default:
4494 return null;
4495 }
4496 }
4497
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004498 ActivityStack getTopDisplayFocusedStack() {
4499 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004500 }
4501
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004502 /** Pokes the task persister. */
4503 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4504 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4505 }
4506
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004507 boolean isKeyguardLocked() {
4508 return mKeyguardController.isKeyguardLocked();
4509 }
4510
Garfield Tan01548632018-11-27 10:15:48 -08004511 /**
4512 * Clears launch params for the given package.
4513 * @param packageNames the names of the packages of which the launch params are to be cleared
4514 */
4515 @Override
4516 public void clearLaunchParamsForPackages(List<String> packageNames) {
4517 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4518 "clearLaunchParamsForPackages");
4519 synchronized (mGlobalLock) {
4520 for (int i = 0; i < packageNames.size(); ++i) {
4521 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4522 }
4523 }
4524 }
4525
Wale Ogunwale31913b52018-10-13 08:29:31 -07004526 void dumpLastANRLocked(PrintWriter pw) {
4527 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4528 if (mLastANRState == null) {
4529 pw.println(" <no ANR has occurred since boot>");
4530 } else {
4531 pw.println(mLastANRState);
4532 }
4533 }
4534
4535 void dumpLastANRTracesLocked(PrintWriter pw) {
4536 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4537
4538 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4539 if (ArrayUtils.isEmpty(files)) {
4540 pw.println(" <no ANR has occurred since boot>");
4541 return;
4542 }
4543 // Find the latest file.
4544 File latest = null;
4545 for (File f : files) {
4546 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4547 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004548 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004549 }
4550 pw.print("File: ");
4551 pw.print(latest.getName());
4552 pw.println();
4553 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4554 String line;
4555 while ((line = in.readLine()) != null) {
4556 pw.println(line);
4557 }
4558 } catch (IOException e) {
4559 pw.print("Unable to read: ");
4560 pw.print(e);
4561 pw.println();
4562 }
4563 }
4564
4565 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4566 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4567 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4568 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4569 }
4570
4571 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4572 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4573 pw.println(header);
4574
4575 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4576 dumpPackage);
4577 boolean needSep = printedAnything;
4578
4579 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4580 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4581 " ResumedActivity: ");
4582 if (printed) {
4583 printedAnything = true;
4584 needSep = false;
4585 }
4586
4587 if (dumpPackage == null) {
4588 if (needSep) {
4589 pw.println();
4590 }
4591 printedAnything = true;
4592 mStackSupervisor.dump(pw, " ");
4593 }
4594
4595 if (!printedAnything) {
4596 pw.println(" (nothing)");
4597 }
4598 }
4599
4600 void dumpActivityContainersLocked(PrintWriter pw) {
4601 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4602 mStackSupervisor.dumpChildrenNames(pw, " ");
4603 pw.println(" ");
4604 }
4605
4606 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4607 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4608 getActivityStartController().dump(pw, "", dumpPackage);
4609 }
4610
4611 /**
4612 * There are three things that cmd can be:
4613 * - a flattened component name that matches an existing activity
4614 * - the cmd arg isn't the flattened component name of an existing activity:
4615 * dump all activity whose component contains the cmd as a substring
4616 * - A hex number of the ActivityRecord object instance.
4617 *
4618 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4619 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4620 */
4621 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4622 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4623 ArrayList<ActivityRecord> activities;
4624
4625 synchronized (mGlobalLock) {
4626 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4627 dumpFocusedStackOnly);
4628 }
4629
4630 if (activities.size() <= 0) {
4631 return false;
4632 }
4633
4634 String[] newArgs = new String[args.length - opti];
4635 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4636
4637 TaskRecord lastTask = null;
4638 boolean needSep = false;
4639 for (int i = activities.size() - 1; i >= 0; i--) {
4640 ActivityRecord r = activities.get(i);
4641 if (needSep) {
4642 pw.println();
4643 }
4644 needSep = true;
4645 synchronized (mGlobalLock) {
4646 final TaskRecord task = r.getTask();
4647 if (lastTask != task) {
4648 lastTask = task;
4649 pw.print("TASK "); pw.print(lastTask.affinity);
4650 pw.print(" id="); pw.print(lastTask.taskId);
4651 pw.print(" userId="); pw.println(lastTask.userId);
4652 if (dumpAll) {
4653 lastTask.dump(pw, " ");
4654 }
4655 }
4656 }
4657 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4658 }
4659 return true;
4660 }
4661
4662 /**
4663 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4664 * there is a thread associated with the activity.
4665 */
4666 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4667 final ActivityRecord r, String[] args, boolean dumpAll) {
4668 String innerPrefix = prefix + " ";
4669 synchronized (mGlobalLock) {
4670 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4671 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4672 pw.print(" pid=");
4673 if (r.hasProcess()) pw.println(r.app.getPid());
4674 else pw.println("(not running)");
4675 if (dumpAll) {
4676 r.dump(pw, innerPrefix);
4677 }
4678 }
4679 if (r.attachedToProcess()) {
4680 // flush anything that is already in the PrintWriter since the thread is going
4681 // to write to the file descriptor directly
4682 pw.flush();
4683 try {
4684 TransferPipe tp = new TransferPipe();
4685 try {
4686 r.app.getThread().dumpActivity(tp.getWriteFd(),
4687 r.appToken, innerPrefix, args);
4688 tp.go(fd);
4689 } finally {
4690 tp.kill();
4691 }
4692 } catch (IOException e) {
4693 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4694 } catch (RemoteException e) {
4695 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4696 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004697 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004698 }
4699
Wale Ogunwalef6733932018-06-27 05:14:34 -07004700 void writeSleepStateToProto(ProtoOutputStream proto) {
4701 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4702 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4703 st.toString());
4704 }
4705
4706 if (mRunningVoice != null) {
4707 final long vrToken = proto.start(
4708 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4709 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4710 mRunningVoice.toString());
4711 mVoiceWakeLock.writeToProto(
4712 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4713 proto.end(vrToken);
4714 }
4715
4716 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4717 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4718 mShuttingDown);
4719 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004720 }
4721
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004722 int getCurrentUserId() {
4723 return mAmInternal.getCurrentUserId();
4724 }
4725
4726 private void enforceNotIsolatedCaller(String caller) {
4727 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4728 throw new SecurityException("Isolated process not allowed to call " + caller);
4729 }
4730 }
4731
Wale Ogunwalef6733932018-06-27 05:14:34 -07004732 public Configuration getConfiguration() {
4733 Configuration ci;
4734 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004735 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004736 ci.userSetLocale = false;
4737 }
4738 return ci;
4739 }
4740
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004741 /**
4742 * Current global configuration information. Contains general settings for the entire system,
4743 * also corresponds to the merged configuration of the default display.
4744 */
4745 Configuration getGlobalConfiguration() {
4746 return mStackSupervisor.getConfiguration();
4747 }
4748
4749 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4750 boolean initLocale) {
4751 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4752 }
4753
4754 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4755 boolean initLocale, boolean deferResume) {
4756 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4757 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4758 UserHandle.USER_NULL, deferResume);
4759 }
4760
Wale Ogunwale59507092018-10-29 09:00:30 -07004761 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004762 final long origId = Binder.clearCallingIdentity();
4763 try {
4764 synchronized (mGlobalLock) {
4765 updateConfigurationLocked(values, null, false, true, userId,
4766 false /* deferResume */);
4767 }
4768 } finally {
4769 Binder.restoreCallingIdentity(origId);
4770 }
4771 }
4772
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004773 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4774 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4775 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4776 deferResume, null /* result */);
4777 }
4778
4779 /**
4780 * Do either or both things: (1) change the current configuration, and (2)
4781 * make sure the given activity is running with the (now) current
4782 * configuration. Returns true if the activity has been left running, or
4783 * false if <var>starting</var> is being destroyed to match the new
4784 * configuration.
4785 *
4786 * @param userId is only used when persistent parameter is set to true to persist configuration
4787 * for that particular user
4788 */
4789 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4790 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4791 ActivityTaskManagerService.UpdateConfigurationResult result) {
4792 int changes = 0;
4793 boolean kept = true;
4794
4795 if (mWindowManager != null) {
4796 mWindowManager.deferSurfaceLayout();
4797 }
4798 try {
4799 if (values != null) {
4800 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4801 deferResume);
4802 }
4803
4804 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4805 } finally {
4806 if (mWindowManager != null) {
4807 mWindowManager.continueSurfaceLayout();
4808 }
4809 }
4810
4811 if (result != null) {
4812 result.changes = changes;
4813 result.activityRelaunched = !kept;
4814 }
4815 return kept;
4816 }
4817
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004818 /** Update default (global) configuration and notify listeners about changes. */
4819 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4820 boolean persistent, int userId, boolean deferResume) {
4821 mTempConfig.setTo(getGlobalConfiguration());
4822 final int changes = mTempConfig.updateFrom(values);
4823 if (changes == 0) {
4824 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4825 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4826 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4827 // (even if there are no actual changes) to unfreeze the window.
4828 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4829 return 0;
4830 }
4831
4832 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4833 "Updating global configuration to: " + values);
4834
4835 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4836 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4837 values.colorMode,
4838 values.densityDpi,
4839 values.fontScale,
4840 values.hardKeyboardHidden,
4841 values.keyboard,
4842 values.keyboardHidden,
4843 values.mcc,
4844 values.mnc,
4845 values.navigation,
4846 values.navigationHidden,
4847 values.orientation,
4848 values.screenHeightDp,
4849 values.screenLayout,
4850 values.screenWidthDp,
4851 values.smallestScreenWidthDp,
4852 values.touchscreen,
4853 values.uiMode);
4854
4855
4856 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4857 final LocaleList locales = values.getLocales();
4858 int bestLocaleIndex = 0;
4859 if (locales.size() > 1) {
4860 if (mSupportedSystemLocales == null) {
4861 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4862 }
4863 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4864 }
4865 SystemProperties.set("persist.sys.locale",
4866 locales.get(bestLocaleIndex).toLanguageTag());
4867 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004868
4869 final Message m = PooledLambda.obtainMessage(
4870 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4871 locales.get(bestLocaleIndex));
4872 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004873 }
4874
Yunfan Chen75157d72018-07-27 14:47:21 +09004875 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004876
4877 // Update stored global config and notify everyone about the change.
4878 mStackSupervisor.onConfigurationChanged(mTempConfig);
4879
4880 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4881 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004882 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004883
4884 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004885 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004886
4887 AttributeCache ac = AttributeCache.instance();
4888 if (ac != null) {
4889 ac.updateConfiguration(mTempConfig);
4890 }
4891
4892 // Make sure all resources in our process are updated right now, so that anyone who is going
4893 // to retrieve resource values after we return will be sure to get the new ones. This is
4894 // especially important during boot, where the first config change needs to guarantee all
4895 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004896 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897
4898 // We need another copy of global config because we're scheduling some calls instead of
4899 // running them in place. We need to be sure that object we send will be handled unchanged.
4900 final Configuration configCopy = new Configuration(mTempConfig);
4901 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004902 final Message msg = PooledLambda.obtainMessage(
4903 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4904 this, userId, configCopy);
4905 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004906 }
4907
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004908 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004909 final int pid = mPidMap.keyAt(i);
4910 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004911 if (DEBUG_CONFIGURATION) {
4912 Slog.v(TAG_CONFIGURATION, "Update process config of "
4913 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004914 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004915 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004916 }
4917
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004918 final Message msg = PooledLambda.obtainMessage(
4919 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4920 mAmInternal, changes, initLocale);
4921 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004922
4923 // Override configuration of the default display duplicates global config, so we need to
4924 // update it also. This will also notify WindowManager about changes.
4925 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4926 DEFAULT_DISPLAY);
4927
4928 return changes;
4929 }
4930
4931 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4932 boolean deferResume, int displayId) {
4933 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4934 displayId, null /* result */);
4935 }
4936
4937 /**
4938 * Updates override configuration specific for the selected display. If no config is provided,
4939 * new one will be computed in WM based on current display info.
4940 */
4941 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4942 ActivityRecord starting, boolean deferResume, int displayId,
4943 ActivityTaskManagerService.UpdateConfigurationResult result) {
4944 int changes = 0;
4945 boolean kept = true;
4946
4947 if (mWindowManager != null) {
4948 mWindowManager.deferSurfaceLayout();
4949 }
4950 try {
4951 if (values != null) {
4952 if (displayId == DEFAULT_DISPLAY) {
4953 // Override configuration of the default display duplicates global config, so
4954 // we're calling global config update instead for default display. It will also
4955 // apply the correct override config.
4956 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4957 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4958 } else {
4959 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4960 }
4961 }
4962
4963 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4964 } finally {
4965 if (mWindowManager != null) {
4966 mWindowManager.continueSurfaceLayout();
4967 }
4968 }
4969
4970 if (result != null) {
4971 result.changes = changes;
4972 result.activityRelaunched = !kept;
4973 }
4974 return kept;
4975 }
4976
4977 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4978 int displayId) {
4979 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4980 final int changes = mTempConfig.updateFrom(values);
4981 if (changes != 0) {
4982 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4983 + mTempConfig + " for displayId=" + displayId);
4984 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4985
4986 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4987 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004988 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004989
Wale Ogunwale5c918702018-10-18 11:06:33 -07004990 // Post message to start process to avoid possible deadlock of calling into AMS with
4991 // the ATMS lock held.
4992 final Message msg = PooledLambda.obtainMessage(
4993 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4994 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4995 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004996 }
4997 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004998 return changes;
4999 }
5000
Wale Ogunwalef6733932018-06-27 05:14:34 -07005001 private void updateEventDispatchingLocked(boolean booted) {
5002 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5003 }
5004
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005005 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5006 final ContentResolver resolver = mContext.getContentResolver();
5007 Settings.System.putConfigurationForUser(resolver, config, userId);
5008 }
5009
5010 private void sendLocaleToMountDaemonMsg(Locale l) {
5011 try {
5012 IBinder service = ServiceManager.getService("mount");
5013 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5014 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5015 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5016 } catch (RemoteException e) {
5017 Log.e(TAG, "Error storing locale for decryption UI", e);
5018 }
5019 }
5020
Alison Cichowlas3e340502018-08-07 17:15:01 -04005021 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5022 mStartActivitySources.remove(permissionToken);
5023 mExpiredStartAsCallerTokens.add(permissionToken);
5024 }
5025
5026 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5027 mExpiredStartAsCallerTokens.remove(permissionToken);
5028 }
5029
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005030 boolean isActivityStartsLoggingEnabled() {
5031 return mAmInternal.isActivityStartsLoggingEnabled();
5032 }
5033
Wale Ogunwalef6733932018-06-27 05:14:34 -07005034 void enableScreenAfterBoot(boolean booted) {
5035 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5036 SystemClock.uptimeMillis());
5037 mWindowManager.enableScreenAfterBoot();
5038
5039 synchronized (mGlobalLock) {
5040 updateEventDispatchingLocked(booted);
5041 }
5042 }
5043
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005044 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5045 if (r == null || !r.hasProcess()) {
5046 return KEY_DISPATCHING_TIMEOUT_MS;
5047 }
5048 return getInputDispatchingTimeoutLocked(r.app);
5049 }
5050
5051 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005052 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005053 }
5054
Wale Ogunwalef6733932018-06-27 05:14:34 -07005055 /**
5056 * Decide based on the configuration whether we should show the ANR,
5057 * crash, etc dialogs. The idea is that if there is no affordance to
5058 * press the on-screen buttons, or the user experience would be more
5059 * greatly impacted than the crash itself, we shouldn't show the dialog.
5060 *
5061 * A thought: SystemUI might also want to get told about this, the Power
5062 * dialog / global actions also might want different behaviors.
5063 */
5064 private void updateShouldShowDialogsLocked(Configuration config) {
5065 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5066 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5067 && config.navigation == Configuration.NAVIGATION_NONAV);
5068 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5069 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5070 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5071 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5072 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5073 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5074 HIDE_ERROR_DIALOGS, 0) != 0;
5075 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5076 }
5077
5078 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5079 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5080 FONT_SCALE, 1.0f, userId);
5081
5082 synchronized (this) {
5083 if (getGlobalConfiguration().fontScale == scaleFactor) {
5084 return;
5085 }
5086
5087 final Configuration configuration
5088 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5089 configuration.fontScale = scaleFactor;
5090 updatePersistentConfiguration(configuration, userId);
5091 }
5092 }
5093
5094 // Actually is sleeping or shutting down or whatever else in the future
5095 // is an inactive state.
5096 boolean isSleepingOrShuttingDownLocked() {
5097 return isSleepingLocked() || mShuttingDown;
5098 }
5099
5100 boolean isSleepingLocked() {
5101 return mSleeping;
5102 }
5103
Riddle Hsu16567132018-08-16 21:37:47 +08005104 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005105 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
5106 final TaskRecord task = r.getTask();
5107 if (task.isActivityTypeStandard()) {
5108 if (mCurAppTimeTracker != r.appTimeTracker) {
5109 // We are switching app tracking. Complete the current one.
5110 if (mCurAppTimeTracker != null) {
5111 mCurAppTimeTracker.stop();
5112 mH.obtainMessage(
5113 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
5114 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
5115 mCurAppTimeTracker = null;
5116 }
5117 if (r.appTimeTracker != null) {
5118 mCurAppTimeTracker = r.appTimeTracker;
5119 startTimeTrackingFocusedActivityLocked();
5120 }
5121 } else {
5122 startTimeTrackingFocusedActivityLocked();
5123 }
5124 } else {
5125 r.appTimeTracker = null;
5126 }
5127 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5128 // TODO: Probably not, because we don't want to resume voice on switching
5129 // back to this activity
5130 if (task.voiceInteractor != null) {
5131 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5132 } else {
5133 finishRunningVoiceLocked();
5134
5135 if (mLastResumedActivity != null) {
5136 final IVoiceInteractionSession session;
5137
5138 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5139 if (lastResumedActivityTask != null
5140 && lastResumedActivityTask.voiceSession != null) {
5141 session = lastResumedActivityTask.voiceSession;
5142 } else {
5143 session = mLastResumedActivity.voiceSession;
5144 }
5145
5146 if (session != null) {
5147 // We had been in a voice interaction session, but now focused has
5148 // move to something different. Just finish the session, we can't
5149 // return to it and retain the proper state and synchronization with
5150 // the voice interaction service.
5151 finishVoiceTask(session);
5152 }
5153 }
5154 }
5155
5156 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5157 mAmInternal.sendForegroundProfileChanged(r.userId);
5158 }
5159 updateResumedAppTrace(r);
5160 mLastResumedActivity = r;
5161
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005162 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005163
5164 applyUpdateLockStateLocked(r);
5165 applyUpdateVrModeLocked(r);
5166
5167 EventLogTags.writeAmSetResumedActivity(
5168 r == null ? -1 : r.userId,
5169 r == null ? "NULL" : r.shortComponentName,
5170 reason);
5171 }
5172
5173 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5174 synchronized (mGlobalLock) {
5175 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5176 updateSleepIfNeededLocked();
5177 return token;
5178 }
5179 }
5180
5181 void updateSleepIfNeededLocked() {
5182 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5183 final boolean wasSleeping = mSleeping;
5184 boolean updateOomAdj = false;
5185
5186 if (!shouldSleep) {
5187 // If wasSleeping is true, we need to wake up activity manager state from when
5188 // we started sleeping. In either case, we need to apply the sleep tokens, which
5189 // will wake up stacks or put them to sleep as appropriate.
5190 if (wasSleeping) {
5191 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005192 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5193 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005194 startTimeTrackingFocusedActivityLocked();
5195 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5196 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5197 }
5198 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5199 if (wasSleeping) {
5200 updateOomAdj = true;
5201 }
5202 } else if (!mSleeping && shouldSleep) {
5203 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005204 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5205 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005206 if (mCurAppTimeTracker != null) {
5207 mCurAppTimeTracker.stop();
5208 }
5209 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5210 mStackSupervisor.goingToSleepLocked();
5211 updateResumedAppTrace(null /* resumed */);
5212 updateOomAdj = true;
5213 }
5214 if (updateOomAdj) {
5215 mH.post(mAmInternal::updateOomAdj);
5216 }
5217 }
5218
5219 void updateOomAdj() {
5220 mH.post(mAmInternal::updateOomAdj);
5221 }
5222
Wale Ogunwale53783742018-09-16 10:21:51 -07005223 void updateCpuStats() {
5224 mH.post(mAmInternal::updateCpuStats);
5225 }
5226
5227 void updateUsageStats(ActivityRecord component, boolean resumed) {
5228 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5229 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5230 mH.sendMessage(m);
5231 }
5232
5233 void setBooting(boolean booting) {
5234 mAmInternal.setBooting(booting);
5235 }
5236
5237 boolean isBooting() {
5238 return mAmInternal.isBooting();
5239 }
5240
5241 void setBooted(boolean booted) {
5242 mAmInternal.setBooted(booted);
5243 }
5244
5245 boolean isBooted() {
5246 return mAmInternal.isBooted();
5247 }
5248
5249 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5250 mH.post(() -> {
5251 if (finishBooting) {
5252 mAmInternal.finishBooting();
5253 }
5254 if (enableScreen) {
5255 mInternal.enableScreenAfterBoot(isBooted());
5256 }
5257 });
5258 }
5259
5260 void setHeavyWeightProcess(ActivityRecord root) {
5261 mHeavyWeightProcess = root.app;
5262 final Message m = PooledLambda.obtainMessage(
5263 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5264 root.app, root.intent, root.userId);
5265 mH.sendMessage(m);
5266 }
5267
5268 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5269 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5270 return;
5271 }
5272
5273 mHeavyWeightProcess = null;
5274 final Message m = PooledLambda.obtainMessage(
5275 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5276 proc.mUserId);
5277 mH.sendMessage(m);
5278 }
5279
5280 private void cancelHeavyWeightProcessNotification(int userId) {
5281 final INotificationManager inm = NotificationManager.getService();
5282 if (inm == null) {
5283 return;
5284 }
5285 try {
5286 inm.cancelNotificationWithTag("android", null,
5287 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5288 } catch (RuntimeException e) {
5289 Slog.w(TAG, "Error canceling notification for service", e);
5290 } catch (RemoteException e) {
5291 }
5292
5293 }
5294
5295 private void postHeavyWeightProcessNotification(
5296 WindowProcessController proc, Intent intent, int userId) {
5297 if (proc == null) {
5298 return;
5299 }
5300
5301 final INotificationManager inm = NotificationManager.getService();
5302 if (inm == null) {
5303 return;
5304 }
5305
5306 try {
5307 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5308 String text = mContext.getString(R.string.heavy_weight_notification,
5309 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5310 Notification notification =
5311 new Notification.Builder(context,
5312 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5313 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5314 .setWhen(0)
5315 .setOngoing(true)
5316 .setTicker(text)
5317 .setColor(mContext.getColor(
5318 com.android.internal.R.color.system_notification_accent_color))
5319 .setContentTitle(text)
5320 .setContentText(
5321 mContext.getText(R.string.heavy_weight_notification_detail))
5322 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5323 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5324 new UserHandle(userId)))
5325 .build();
5326 try {
5327 inm.enqueueNotificationWithTag("android", "android", null,
5328 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5329 } catch (RuntimeException e) {
5330 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5331 } catch (RemoteException e) {
5332 }
5333 } catch (PackageManager.NameNotFoundException e) {
5334 Slog.w(TAG, "Unable to create context for heavy notification", e);
5335 }
5336
5337 }
5338
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005339 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5340 IBinder token, String resultWho, int requestCode, Intent[] intents,
5341 String[] resolvedTypes, int flags, Bundle bOptions) {
5342
5343 ActivityRecord activity = null;
5344 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5345 activity = ActivityRecord.isInStackLocked(token);
5346 if (activity == null) {
5347 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5348 return null;
5349 }
5350 if (activity.finishing) {
5351 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5352 return null;
5353 }
5354 }
5355
5356 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5357 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5358 bOptions);
5359 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5360 if (noCreate) {
5361 return rec;
5362 }
5363 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5364 if (activity.pendingResults == null) {
5365 activity.pendingResults = new HashSet<>();
5366 }
5367 activity.pendingResults.add(rec.ref);
5368 }
5369 return rec;
5370 }
5371
Andrii Kulian52d255c2018-07-13 11:32:19 -07005372 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005373 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005374 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005375 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5376 mCurAppTimeTracker.start(resumedActivity.packageName);
5377 }
5378 }
5379
5380 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5381 if (mTracedResumedActivity != null) {
5382 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5383 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5384 }
5385 if (resumed != null) {
5386 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5387 constructResumedTraceName(resumed.packageName), 0);
5388 }
5389 mTracedResumedActivity = resumed;
5390 }
5391
5392 private String constructResumedTraceName(String packageName) {
5393 return "focused app: " + packageName;
5394 }
5395
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005396 /** Applies latest configuration and/or visibility updates if needed. */
5397 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5398 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005399 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005400 // mainStack is null during startup.
5401 if (mainStack != null) {
5402 if (changes != 0 && starting == null) {
5403 // If the configuration changed, and the caller is not already
5404 // in the process of starting an activity, then find the top
5405 // activity to check if its configuration needs to change.
5406 starting = mainStack.topRunningActivityLocked();
5407 }
5408
5409 if (starting != null) {
5410 kept = starting.ensureActivityConfiguration(changes,
5411 false /* preserveWindow */);
5412 // And we need to make sure at this point that all other activities
5413 // are made visible with the correct configuration.
5414 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5415 !PRESERVE_WINDOWS);
5416 }
5417 }
5418
5419 return kept;
5420 }
5421
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005422 void scheduleAppGcsLocked() {
5423 mH.post(() -> mAmInternal.scheduleAppGcs());
5424 }
5425
Wale Ogunwale53783742018-09-16 10:21:51 -07005426 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5427 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5428 }
5429
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005430 /**
5431 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5432 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5433 * on demand.
5434 */
5435 IPackageManager getPackageManager() {
5436 return AppGlobals.getPackageManager();
5437 }
5438
5439 PackageManagerInternal getPackageManagerInternalLocked() {
5440 if (mPmInternal == null) {
5441 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5442 }
5443 return mPmInternal;
5444 }
5445
Wale Ogunwale008163e2018-07-23 23:11:08 -07005446 AppWarnings getAppWarningsLocked() {
5447 return mAppWarnings;
5448 }
5449
Wale Ogunwale214f3482018-10-04 11:00:47 -07005450 Intent getHomeIntent() {
5451 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5452 intent.setComponent(mTopComponent);
5453 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5454 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5455 intent.addCategory(Intent.CATEGORY_HOME);
5456 }
5457 return intent;
5458 }
5459
Wale Ogunwale214f3482018-10-04 11:00:47 -07005460 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5461 if (info == null) return null;
5462 ApplicationInfo newInfo = new ApplicationInfo(info);
5463 newInfo.initForUser(userId);
5464 return newInfo;
5465 }
5466
Wale Ogunwale9c103022018-10-18 07:44:54 -07005467 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005468 if (uid == SYSTEM_UID) {
5469 // The system gets to run in any process. If there are multiple processes with the same
5470 // uid, just pick the first (this should never happen).
5471 final SparseArray<WindowProcessController> procs =
5472 mProcessNames.getMap().get(processName);
5473 if (procs == null) return null;
5474 final int procCount = procs.size();
5475 for (int i = 0; i < procCount; i++) {
5476 final int procUid = procs.keyAt(i);
5477 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5478 // Don't use an app process or different user process for system component.
5479 continue;
5480 }
5481 return procs.valueAt(i);
5482 }
5483 }
5484
5485 return mProcessNames.get(processName, uid);
5486 }
5487
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005488 WindowProcessController getProcessController(IApplicationThread thread) {
5489 if (thread == null) {
5490 return null;
5491 }
5492
5493 final IBinder threadBinder = thread.asBinder();
5494 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5495 for (int i = pmap.size()-1; i >= 0; i--) {
5496 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5497 for (int j = procs.size() - 1; j >= 0; j--) {
5498 final WindowProcessController proc = procs.valueAt(j);
5499 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5500 return proc;
5501 }
5502 }
5503 }
5504
5505 return null;
5506 }
5507
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005508 int getUidStateLocked(int uid) {
5509 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5510 }
5511
Wale Ogunwale9de19442018-10-18 19:05:03 -07005512 /**
5513 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5514 * the whitelist
5515 */
5516 String getPendingTempWhitelistTagForUidLocked(int uid) {
5517 return mPendingTempWhitelist.get(uid);
5518 }
5519
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005520 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5521 if (true || Build.IS_USER) {
5522 return;
5523 }
5524
5525 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5526 StrictMode.allowThreadDiskWrites();
5527 try {
5528 File tracesDir = new File("/data/anr");
5529 File tracesFile = null;
5530 try {
5531 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5532
5533 StringBuilder sb = new StringBuilder();
5534 Time tobj = new Time();
5535 tobj.set(System.currentTimeMillis());
5536 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5537 sb.append(": ");
5538 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5539 sb.append(" since ");
5540 sb.append(msg);
5541 FileOutputStream fos = new FileOutputStream(tracesFile);
5542 fos.write(sb.toString().getBytes());
5543 if (app == null) {
5544 fos.write("\n*** No application process!".getBytes());
5545 }
5546 fos.close();
5547 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5548 } catch (IOException e) {
5549 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5550 return;
5551 }
5552
5553 if (app != null && app.getPid() > 0) {
5554 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5555 firstPids.add(app.getPid());
5556 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5557 }
5558
5559 File lastTracesFile = null;
5560 File curTracesFile = null;
5561 for (int i=9; i>=0; i--) {
5562 String name = String.format(Locale.US, "slow%02d.txt", i);
5563 curTracesFile = new File(tracesDir, name);
5564 if (curTracesFile.exists()) {
5565 if (lastTracesFile != null) {
5566 curTracesFile.renameTo(lastTracesFile);
5567 } else {
5568 curTracesFile.delete();
5569 }
5570 }
5571 lastTracesFile = curTracesFile;
5572 }
5573 tracesFile.renameTo(curTracesFile);
5574 } finally {
5575 StrictMode.setThreadPolicy(oldPolicy);
5576 }
5577 }
5578
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005579 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005580 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005581
5582
Wale Ogunwale98875612018-10-12 07:53:02 -07005583 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5584 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005586 public H() {
5587 super(DisplayThread.get().getLooper());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005588 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005589
5590 @Override
5591 public void handleMessage(Message msg) {
5592 switch (msg.what) {
5593 case REPORT_TIME_TRACKER_MSG: {
5594 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5595 tracker.deliverResult(mContext);
5596 } break;
5597 }
5598 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005599 }
5600
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005601 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005602 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005603
5604 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005605 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005606 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005607
5608 @Override
5609 public void handleMessage(Message msg) {
5610 switch (msg.what) {
5611 case DISMISS_DIALOG_UI_MSG: {
5612 final Dialog d = (Dialog) msg.obj;
5613 d.dismiss();
5614 break;
5615 }
5616 }
5617 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005618 }
5619
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005620 final class LocalService extends ActivityTaskManagerInternal {
5621 @Override
5622 public SleepToken acquireSleepToken(String tag, int displayId) {
5623 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005624 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005625 }
5626
5627 @Override
5628 public ComponentName getHomeActivityForUser(int userId) {
5629 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005630 ActivityRecord homeActivity =
5631 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005632 return homeActivity == null ? null : homeActivity.realActivity;
5633 }
5634 }
5635
5636 @Override
5637 public void onLocalVoiceInteractionStarted(IBinder activity,
5638 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5639 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005640 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005641 }
5642 }
5643
5644 @Override
5645 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5646 synchronized (mGlobalLock) {
5647 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5648 reasons, timestamp);
5649 }
5650 }
5651
5652 @Override
5653 public void notifyAppTransitionFinished() {
5654 synchronized (mGlobalLock) {
5655 mStackSupervisor.notifyAppTransitionDone();
5656 }
5657 }
5658
5659 @Override
5660 public void notifyAppTransitionCancelled() {
5661 synchronized (mGlobalLock) {
5662 mStackSupervisor.notifyAppTransitionDone();
5663 }
5664 }
5665
5666 @Override
5667 public List<IBinder> getTopVisibleActivities() {
5668 synchronized (mGlobalLock) {
5669 return mStackSupervisor.getTopVisibleActivities();
5670 }
5671 }
5672
5673 @Override
5674 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5675 synchronized (mGlobalLock) {
5676 mStackSupervisor.setDockedStackMinimized(minimized);
5677 }
5678 }
5679
5680 @Override
5681 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5682 Bundle bOptions) {
5683 Preconditions.checkNotNull(intents, "intents");
5684 final String[] resolvedTypes = new String[intents.length];
5685
5686 // UID of the package on user userId.
5687 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5688 // packageUid may not be initialized.
5689 int packageUid = 0;
5690 final long ident = Binder.clearCallingIdentity();
5691
5692 try {
5693 for (int i = 0; i < intents.length; i++) {
5694 resolvedTypes[i] =
5695 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5696 }
5697
5698 packageUid = AppGlobals.getPackageManager().getPackageUid(
5699 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5700 } catch (RemoteException e) {
5701 // Shouldn't happen.
5702 } finally {
5703 Binder.restoreCallingIdentity(ident);
5704 }
5705
5706 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005707 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005708 packageUid, packageName,
5709 intents, resolvedTypes, null /* resultTo */,
5710 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005711 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005712 }
5713 }
5714
5715 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005716 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5717 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5718 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5719 synchronized (mGlobalLock) {
5720 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5721 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5722 originatingPendingIntent);
5723 }
5724 }
5725
5726 @Override
5727 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5728 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5729 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5730 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5731 PendingIntentRecord originatingPendingIntent) {
5732 synchronized (mGlobalLock) {
5733 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5734 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5735 requestCode, startFlags, options, userId, inTask, reason,
5736 validateIncomingUser, originatingPendingIntent);
5737 }
5738 }
5739
5740 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005741 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5742 Intent intent, Bundle options, int userId) {
5743 return ActivityTaskManagerService.this.startActivityAsUser(
5744 caller, callerPacakge, intent,
5745 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5746 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5747 false /*validateIncomingUser*/);
5748 }
5749
5750 @Override
lumark588a3e82018-07-20 18:53:54 +08005751 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005752 synchronized (mGlobalLock) {
5753
5754 // We might change the visibilities here, so prepare an empty app transition which
5755 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005756 final ActivityDisplay activityDisplay =
5757 mStackSupervisor.getActivityDisplay(displayId);
5758 if (activityDisplay == null) {
5759 return;
5760 }
5761 final DisplayWindowController dwc = activityDisplay.getWindowContainerController();
lumark588a3e82018-07-20 18:53:54 +08005762 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005763 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005764 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005765 }
5766 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5767
5768 // If there was a transition set already we don't want to interfere with it as we
5769 // might be starting it too early.
5770 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005771 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005772 }
5773 }
5774 if (callback != null) {
5775 callback.run();
5776 }
5777 }
5778
5779 @Override
5780 public void notifyKeyguardTrustedChanged() {
5781 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005782 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005783 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5784 }
5785 }
5786 }
5787
5788 /**
5789 * Called after virtual display Id is updated by
5790 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5791 * {@param vrVr2dDisplayId}.
5792 */
5793 @Override
5794 public void setVr2dDisplayId(int vr2dDisplayId) {
5795 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5796 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005797 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005798 }
5799 }
5800
5801 @Override
5802 public void setFocusedActivity(IBinder token) {
5803 synchronized (mGlobalLock) {
5804 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5805 if (r == null) {
5806 throw new IllegalArgumentException(
5807 "setFocusedActivity: No activity record matching token=" + token);
5808 }
Louis Chang19443452018-10-09 12:10:21 +08005809 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005810 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005811 }
5812 }
5813 }
5814
5815 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005816 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005817 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005818 }
5819
5820 @Override
5821 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005822 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005823 }
5824
5825 @Override
5826 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005827 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005828 }
5829
5830 @Override
5831 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5832 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5833 }
5834
5835 @Override
5836 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005837 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005838 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005839
5840 @Override
5841 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5842 synchronized (mGlobalLock) {
5843 mActiveVoiceInteractionServiceComponent = component;
5844 }
5845 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005846
5847 @Override
5848 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5849 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5850 return;
5851 }
5852 synchronized (mGlobalLock) {
5853 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5854 if (types == null) {
5855 if (uid < 0) {
5856 return;
5857 }
5858 types = new ArrayMap<>();
5859 mAllowAppSwitchUids.put(userId, types);
5860 }
5861 if (uid < 0) {
5862 types.remove(type);
5863 } else {
5864 types.put(type, uid);
5865 }
5866 }
5867 }
5868
5869 @Override
5870 public void onUserStopped(int userId) {
5871 synchronized (mGlobalLock) {
5872 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5873 mAllowAppSwitchUids.remove(userId);
5874 }
5875 }
5876
5877 @Override
5878 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5879 synchronized (mGlobalLock) {
5880 return ActivityTaskManagerService.this.isGetTasksAllowed(
5881 caller, callingPid, callingUid);
5882 }
5883 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005884
5885 @Override
5886 public void onProcessAdded(WindowProcessController proc) {
5887 synchronized (mGlobalLock) {
5888 mProcessNames.put(proc.mName, proc.mUid, proc);
5889 }
5890 }
5891
5892 @Override
5893 public void onProcessRemoved(String name, int uid) {
5894 synchronized (mGlobalLock) {
5895 mProcessNames.remove(name, uid);
5896 }
5897 }
5898
5899 @Override
5900 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5901 synchronized (mGlobalLock) {
5902 if (proc == mHomeProcess) {
5903 mHomeProcess = null;
5904 }
5905 if (proc == mPreviousProcess) {
5906 mPreviousProcess = null;
5907 }
5908 }
5909 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005910
5911 @Override
5912 public int getTopProcessState() {
5913 synchronized (mGlobalLock) {
5914 return mTopProcessState;
5915 }
5916 }
5917
5918 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005919 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5920 synchronized (mGlobalLock) {
5921 return proc == mHeavyWeightProcess;
5922 }
5923 }
5924
5925 @Override
5926 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5927 synchronized (mGlobalLock) {
5928 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5929 }
5930 }
5931
5932 @Override
5933 public void finishHeavyWeightApp() {
5934 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005935 if (mHeavyWeightProcess != null) {
5936 mHeavyWeightProcess.finishActivities();
5937 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005938 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5939 mHeavyWeightProcess);
5940 }
5941 }
5942
5943 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005944 public boolean isSleeping() {
5945 synchronized (mGlobalLock) {
5946 return isSleepingLocked();
5947 }
5948 }
5949
5950 @Override
5951 public boolean isShuttingDown() {
5952 synchronized (mGlobalLock) {
5953 return mShuttingDown;
5954 }
5955 }
5956
5957 @Override
5958 public boolean shuttingDown(boolean booted, int timeout) {
5959 synchronized (mGlobalLock) {
5960 mShuttingDown = true;
5961 mStackSupervisor.prepareForShutdownLocked();
5962 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005963 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005964 return mStackSupervisor.shutdownLocked(timeout);
5965 }
5966 }
5967
5968 @Override
5969 public void enableScreenAfterBoot(boolean booted) {
5970 synchronized (mGlobalLock) {
5971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5972 SystemClock.uptimeMillis());
5973 mWindowManager.enableScreenAfterBoot();
5974 updateEventDispatchingLocked(booted);
5975 }
5976 }
5977
5978 @Override
5979 public boolean showStrictModeViolationDialog() {
5980 synchronized (mGlobalLock) {
5981 return mShowDialogs && !mSleeping && !mShuttingDown;
5982 }
5983 }
5984
5985 @Override
5986 public void showSystemReadyErrorDialogsIfNeeded() {
5987 synchronized (mGlobalLock) {
5988 try {
5989 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5990 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5991 + " data partition or your device will be unstable.");
5992 mUiHandler.post(() -> {
5993 if (mShowDialogs) {
5994 AlertDialog d = new BaseErrorDialog(mUiContext);
5995 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5996 d.setCancelable(false);
5997 d.setTitle(mUiContext.getText(R.string.android_system_label));
5998 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5999 d.setButton(DialogInterface.BUTTON_POSITIVE,
6000 mUiContext.getText(R.string.ok),
6001 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6002 d.show();
6003 }
6004 });
6005 }
6006 } catch (RemoteException e) {
6007 }
6008
6009 if (!Build.isBuildConsistent()) {
6010 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6011 mUiHandler.post(() -> {
6012 if (mShowDialogs) {
6013 AlertDialog d = new BaseErrorDialog(mUiContext);
6014 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6015 d.setCancelable(false);
6016 d.setTitle(mUiContext.getText(R.string.android_system_label));
6017 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6018 d.setButton(DialogInterface.BUTTON_POSITIVE,
6019 mUiContext.getText(R.string.ok),
6020 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6021 d.show();
6022 }
6023 });
6024 }
6025 }
6026 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006027
6028 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006029 public void onProcessMapped(int pid, WindowProcessController proc) {
6030 synchronized (mGlobalLock) {
6031 mPidMap.put(pid, proc);
6032 }
6033 }
6034
6035 @Override
6036 public void onProcessUnMapped(int pid) {
6037 synchronized (mGlobalLock) {
6038 mPidMap.remove(pid);
6039 }
6040 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006041
6042 @Override
6043 public void onPackageDataCleared(String name) {
6044 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006045 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006046 mAppWarnings.onPackageDataCleared(name);
6047 }
6048 }
6049
6050 @Override
6051 public void onPackageUninstalled(String name) {
6052 synchronized (mGlobalLock) {
6053 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006054 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006055 }
6056 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006057
6058 @Override
6059 public void onPackageAdded(String name, boolean replacing) {
6060 synchronized (mGlobalLock) {
6061 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6062 }
6063 }
6064
6065 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006066 public void onPackageReplaced(ApplicationInfo aInfo) {
6067 synchronized (mGlobalLock) {
6068 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
6069 }
6070 }
6071
6072 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006073 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6074 synchronized (mGlobalLock) {
6075 return compatibilityInfoForPackageLocked(ai);
6076 }
6077 }
6078
Yunfan Chen75157d72018-07-27 14:47:21 +09006079 /**
6080 * Set the corresponding display information for the process global configuration. To be
6081 * called when we need to show IME on a different display.
6082 *
6083 * @param pid The process id associated with the IME window.
6084 * @param displayId The ID of the display showing the IME.
6085 */
6086 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006087 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006088 if (pid == MY_PID || pid < 0) {
6089 if (DEBUG_CONFIGURATION) {
6090 Slog.w(TAG,
6091 "Trying to update display configuration for system/invalid process.");
6092 }
6093 return;
6094 }
6095 mH.post(() -> {
6096 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006097 final ActivityDisplay activityDisplay =
6098 mStackSupervisor.getActivityDisplay(displayId);
6099 if (activityDisplay == null) {
6100 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006101 if (DEBUG_CONFIGURATION) {
6102 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006103 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006104 }
6105 return;
6106 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006107 final WindowProcessController process = mPidMap.get(pid);
6108 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006109 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006110 Slog.w(TAG, "Trying to update display configuration for invalid "
6111 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006112 }
6113 return;
6114 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006115 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006116 }
6117 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006118
Yunfan Chen75157d72018-07-27 14:47:21 +09006119 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006120
6121 @Override
6122 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6123 int requestCode, int resultCode, Intent data) {
6124 synchronized (mGlobalLock) {
6125 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6126 if (r != null && r.getStack() != null) {
6127 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6128 resultCode, data);
6129 }
6130 }
6131 }
6132
6133 @Override
6134 public void clearPendingResultForActivity(IBinder activityToken,
6135 WeakReference<PendingIntentRecord> pir) {
6136 synchronized (mGlobalLock) {
6137 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6138 if (r != null && r.pendingResults != null) {
6139 r.pendingResults.remove(pir);
6140 }
6141 }
6142 }
6143
6144 @Override
6145 public IIntentSender getIntentSender(int type, String packageName,
6146 int callingUid, int userId, IBinder token, String resultWho,
6147 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6148 Bundle bOptions) {
6149 synchronized (mGlobalLock) {
6150 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6151 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6152 }
6153 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006154
6155 @Override
6156 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6157 synchronized (mGlobalLock) {
6158 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6159 if (r == null) {
6160 return null;
6161 }
6162 if (r.mServiceConnectionsHolder == null) {
6163 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6164 ActivityTaskManagerService.this, r);
6165 }
6166
6167 return r.mServiceConnectionsHolder;
6168 }
6169 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006170
6171 @Override
6172 public Intent getHomeIntent() {
6173 synchronized (mGlobalLock) {
6174 return ActivityTaskManagerService.this.getHomeIntent();
6175 }
6176 }
6177
6178 @Override
6179 public boolean startHomeActivity(int userId, String reason) {
6180 synchronized (mGlobalLock) {
Louis Chang89f43fc2018-10-05 10:59:14 +08006181 return mStackSupervisor.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6182 }
6183 }
6184
6185 @Override
6186 public boolean startHomeOnAllDisplays(int userId, String reason) {
6187 synchronized (mGlobalLock) {
6188 return mStackSupervisor.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006189 }
6190 }
6191
6192 @Override
6193 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6194 synchronized (mGlobalLock) {
6195 if (mFactoryTest == FACTORY_TEST_OFF) {
6196 return false;
6197 }
6198 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6199 && wpc.mName.equals(mTopComponent.getPackageName())) {
6200 return true;
6201 }
6202 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6203 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6204 }
6205 }
6206
6207 @Override
6208 public void updateTopComponentForFactoryTest() {
6209 synchronized (mGlobalLock) {
6210 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6211 return;
6212 }
6213 final ResolveInfo ri = mContext.getPackageManager()
6214 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6215 final CharSequence errorMsg;
6216 if (ri != null) {
6217 final ActivityInfo ai = ri.activityInfo;
6218 final ApplicationInfo app = ai.applicationInfo;
6219 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6220 mTopAction = Intent.ACTION_FACTORY_TEST;
6221 mTopData = null;
6222 mTopComponent = new ComponentName(app.packageName, ai.name);
6223 errorMsg = null;
6224 } else {
6225 errorMsg = mContext.getResources().getText(
6226 com.android.internal.R.string.factorytest_not_system);
6227 }
6228 } else {
6229 errorMsg = mContext.getResources().getText(
6230 com.android.internal.R.string.factorytest_no_action);
6231 }
6232 if (errorMsg == null) {
6233 return;
6234 }
6235
6236 mTopAction = null;
6237 mTopData = null;
6238 mTopComponent = null;
6239 mUiHandler.post(() -> {
6240 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6241 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006242 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006243 });
6244 }
6245 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006246
6247 @Override
6248 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6249 Runnable finishInstrumentationCallback) {
6250 synchronized (mGlobalLock) {
6251 // Remove this application's activities from active lists.
6252 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6253
6254 wpc.clearRecentTasks();
6255 wpc.clearActivities();
6256
6257 if (wpc.isInstrumenting()) {
6258 finishInstrumentationCallback.run();
6259 }
6260
6261 mWindowManager.deferSurfaceLayout();
6262 try {
6263 if (!restarting && hasVisibleActivities
6264 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6265 // If there was nothing to resume, and we are not already restarting this
6266 // process, but there is a visible activity that is hosted by the process...
6267 // then make sure all visible activities are running, taking care of
6268 // restarting this process.
6269 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6270 }
6271 } finally {
6272 mWindowManager.continueSurfaceLayout();
6273 }
6274 }
6275 }
6276
6277 @Override
6278 public void closeSystemDialogs(String reason) {
6279 enforceNotIsolatedCaller("closeSystemDialogs");
6280
6281 final int pid = Binder.getCallingPid();
6282 final int uid = Binder.getCallingUid();
6283 final long origId = Binder.clearCallingIdentity();
6284 try {
6285 synchronized (mGlobalLock) {
6286 // Only allow this from foreground processes, so that background
6287 // applications can't abuse it to prevent system UI from being shown.
6288 if (uid >= FIRST_APPLICATION_UID) {
6289 final WindowProcessController proc = mPidMap.get(pid);
6290 if (!proc.isPerceptible()) {
6291 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6292 + " from background process " + proc);
6293 return;
6294 }
6295 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006296 mWindowManager.closeSystemDialogs(reason);
6297
6298 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006299 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006300 // Call into AM outside the synchronized block.
6301 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006302 } finally {
6303 Binder.restoreCallingIdentity(origId);
6304 }
6305 }
6306
6307 @Override
6308 public void cleanupDisabledPackageComponents(
6309 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6310 synchronized (mGlobalLock) {
6311 // Clean-up disabled activities.
6312 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6313 packageName, disabledClasses, true, false, userId) && booted) {
6314 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6315 mStackSupervisor.scheduleIdleLocked();
6316 }
6317
6318 // Clean-up disabled tasks
6319 getRecentTasks().cleanupDisabledPackageTasksLocked(
6320 packageName, disabledClasses, userId);
6321 }
6322 }
6323
6324 @Override
6325 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6326 int userId) {
6327 synchronized (mGlobalLock) {
6328
6329 boolean didSomething =
6330 getActivityStartController().clearPendingActivityLaunches(packageName);
6331 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6332 null, doit, evenPersistent, userId);
6333 return didSomething;
6334 }
6335 }
6336
6337 @Override
6338 public void resumeTopActivities(boolean scheduleIdle) {
6339 synchronized (mGlobalLock) {
6340 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6341 if (scheduleIdle) {
6342 mStackSupervisor.scheduleIdleLocked();
6343 }
6344 }
6345 }
6346
6347 @Override
6348 public void preBindApplication(WindowProcessController wpc) {
6349 synchronized (mGlobalLock) {
6350 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6351 }
6352 }
6353
6354 @Override
6355 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6356 synchronized (mGlobalLock) {
6357 return mStackSupervisor.attachApplicationLocked(wpc);
6358 }
6359 }
6360
6361 @Override
6362 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6363 try {
6364 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6365 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6366 }
6367 } catch (RemoteException ex) {
6368 throw new SecurityException("Fail to check is caller a privileged app", ex);
6369 }
6370
6371 synchronized (mGlobalLock) {
6372 final long ident = Binder.clearCallingIdentity();
6373 try {
6374 if (mAmInternal.shouldConfirmCredentials(userId)) {
6375 if (mKeyguardController.isKeyguardLocked()) {
6376 // Showing launcher to avoid user entering credential twice.
6377 startHomeActivity(currentUserId, "notifyLockedProfile");
6378 }
6379 mStackSupervisor.lockAllProfileTasks(userId);
6380 }
6381 } finally {
6382 Binder.restoreCallingIdentity(ident);
6383 }
6384 }
6385 }
6386
6387 @Override
6388 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6389 mAmInternal.enforceCallingPermission(
6390 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6391
6392 synchronized (mGlobalLock) {
6393 final long ident = Binder.clearCallingIdentity();
6394 try {
6395 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6396 FLAG_ACTIVITY_TASK_ON_HOME);
6397 ActivityOptions activityOptions = options != null
6398 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006399 final ActivityRecord homeActivity =
6400 mStackSupervisor.getDefaultDisplayHomeActivity();
6401 if (homeActivity != null) {
6402 activityOptions.setLaunchTaskId(homeActivity.getTask().taskId);
6403 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006404 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6405 UserHandle.CURRENT);
6406 } finally {
6407 Binder.restoreCallingIdentity(ident);
6408 }
6409 }
6410 }
6411
6412 @Override
6413 public void writeActivitiesToProto(ProtoOutputStream proto) {
6414 synchronized (mGlobalLock) {
6415 // The output proto of "activity --proto activities"
6416 // is ActivityManagerServiceDumpActivitiesProto
6417 mStackSupervisor.writeToProto(proto,
6418 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6419 }
6420 }
6421
6422 @Override
6423 public void saveANRState(String reason) {
6424 synchronized (mGlobalLock) {
6425 final StringWriter sw = new StringWriter();
6426 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6427 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6428 if (reason != null) {
6429 pw.println(" Reason: " + reason);
6430 }
6431 pw.println();
6432 getActivityStartController().dump(pw, " ", null);
6433 pw.println();
6434 pw.println("-------------------------------------------------------------------------------");
6435 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6436 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6437 "" /* header */);
6438 pw.println();
6439 pw.close();
6440
6441 mLastANRState = sw.toString();
6442 }
6443 }
6444
6445 @Override
6446 public void clearSavedANRState() {
6447 synchronized (mGlobalLock) {
6448 mLastANRState = null;
6449 }
6450 }
6451
6452 @Override
6453 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6454 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6455 synchronized (mGlobalLock) {
6456 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6457 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6458 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6459 dumpLastANRLocked(pw);
6460 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6461 dumpLastANRTracesLocked(pw);
6462 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6463 dumpActivityStarterLocked(pw, dumpPackage);
6464 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6465 dumpActivityContainersLocked(pw);
6466 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6467 if (getRecentTasks() != null) {
6468 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6469 }
6470 }
6471 }
6472 }
6473
6474 @Override
6475 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6476 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6477 int wakefulness) {
6478 synchronized (mGlobalLock) {
6479 if (mHomeProcess != null && (dumpPackage == null
6480 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6481 if (needSep) {
6482 pw.println();
6483 needSep = false;
6484 }
6485 pw.println(" mHomeProcess: " + mHomeProcess);
6486 }
6487 if (mPreviousProcess != null && (dumpPackage == null
6488 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6489 if (needSep) {
6490 pw.println();
6491 needSep = false;
6492 }
6493 pw.println(" mPreviousProcess: " + mPreviousProcess);
6494 }
6495 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6496 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6497 StringBuilder sb = new StringBuilder(128);
6498 sb.append(" mPreviousProcessVisibleTime: ");
6499 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6500 pw.println(sb);
6501 }
6502 if (mHeavyWeightProcess != null && (dumpPackage == null
6503 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6504 if (needSep) {
6505 pw.println();
6506 needSep = false;
6507 }
6508 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6509 }
6510 if (dumpPackage == null) {
6511 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6512 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6513 }
6514 if (dumpAll) {
6515 if (dumpPackage == null) {
6516 pw.println(" mConfigWillChange: "
6517 + getTopDisplayFocusedStack().mConfigWillChange);
6518 }
6519 if (mCompatModePackages.getPackages().size() > 0) {
6520 boolean printed = false;
6521 for (Map.Entry<String, Integer> entry
6522 : mCompatModePackages.getPackages().entrySet()) {
6523 String pkg = entry.getKey();
6524 int mode = entry.getValue();
6525 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6526 continue;
6527 }
6528 if (!printed) {
6529 pw.println(" mScreenCompatPackages:");
6530 printed = true;
6531 }
6532 pw.println(" " + pkg + ": " + mode);
6533 }
6534 }
6535 }
6536
6537 if (dumpPackage == null) {
6538 pw.println(" mWakefulness="
6539 + PowerManagerInternal.wakefulnessToString(wakefulness));
6540 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6541 if (mRunningVoice != null) {
6542 pw.println(" mRunningVoice=" + mRunningVoice);
6543 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6544 }
6545 pw.println(" mSleeping=" + mSleeping);
6546 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6547 pw.println(" mVrController=" + mVrController);
6548 }
6549 if (mCurAppTimeTracker != null) {
6550 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6551 }
6552 if (mAllowAppSwitchUids.size() > 0) {
6553 boolean printed = false;
6554 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6555 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6556 for (int j = 0; j < types.size(); j++) {
6557 if (dumpPackage == null ||
6558 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6559 if (needSep) {
6560 pw.println();
6561 needSep = false;
6562 }
6563 if (!printed) {
6564 pw.println(" mAllowAppSwitchUids:");
6565 printed = true;
6566 }
6567 pw.print(" User ");
6568 pw.print(mAllowAppSwitchUids.keyAt(i));
6569 pw.print(": Type ");
6570 pw.print(types.keyAt(j));
6571 pw.print(" = ");
6572 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6573 pw.println();
6574 }
6575 }
6576 }
6577 }
6578 if (dumpPackage == null) {
6579 if (mController != null) {
6580 pw.println(" mController=" + mController
6581 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6582 }
6583 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6584 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6585 }
6586
6587 return needSep;
6588 }
6589 }
6590
6591 @Override
6592 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6593 synchronized (mGlobalLock) {
6594 if (dumpPackage == null) {
6595 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6596 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6597 writeSleepStateToProto(proto);
6598 if (mController != null) {
6599 final long token = proto.start(CONTROLLER);
6600 proto.write(CONTROLLER, mController.toString());
6601 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6602 proto.end(token);
6603 }
6604 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6605 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6606 }
6607
6608 if (mHomeProcess != null && (dumpPackage == null
6609 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006610 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006611 }
6612
6613 if (mPreviousProcess != null && (dumpPackage == null
6614 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006615 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006616 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6617 }
6618
6619 if (mHeavyWeightProcess != null && (dumpPackage == null
6620 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006621 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006622 }
6623
6624 for (Map.Entry<String, Integer> entry
6625 : mCompatModePackages.getPackages().entrySet()) {
6626 String pkg = entry.getKey();
6627 int mode = entry.getValue();
6628 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6629 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6630 proto.write(PACKAGE, pkg);
6631 proto.write(MODE, mode);
6632 proto.end(compatToken);
6633 }
6634 }
6635
6636 if (mCurAppTimeTracker != null) {
6637 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6638 }
6639
6640 }
6641 }
6642
6643 @Override
6644 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6645 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6646 boolean dumpFocusedStackOnly) {
6647 synchronized (mGlobalLock) {
6648 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6649 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6650 }
6651 }
6652
6653 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006654 public void dumpForOom(PrintWriter pw) {
6655 synchronized (mGlobalLock) {
6656 pw.println(" mHomeProcess: " + mHomeProcess);
6657 pw.println(" mPreviousProcess: " + mPreviousProcess);
6658 if (mHeavyWeightProcess != null) {
6659 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6660 }
6661 }
6662 }
6663
6664 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006665 public boolean canGcNow() {
6666 synchronized (mGlobalLock) {
6667 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6668 }
6669 }
6670
6671 @Override
6672 public WindowProcessController getTopApp() {
6673 synchronized (mGlobalLock) {
6674 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6675 return top != null ? top.app : null;
6676 }
6677 }
6678
6679 @Override
6680 public void rankTaskLayersIfNeeded() {
6681 synchronized (mGlobalLock) {
6682 if (mStackSupervisor != null) {
6683 mStackSupervisor.rankTaskLayersIfNeeded();
6684 }
6685 }
6686 }
6687
6688 @Override
6689 public void scheduleDestroyAllActivities(String reason) {
6690 synchronized (mGlobalLock) {
6691 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6692 }
6693 }
6694
6695 @Override
6696 public void removeUser(int userId) {
6697 synchronized (mGlobalLock) {
6698 mStackSupervisor.removeUserLocked(userId);
6699 }
6700 }
6701
6702 @Override
6703 public boolean switchUser(int userId, UserState userState) {
6704 synchronized (mGlobalLock) {
6705 return mStackSupervisor.switchUserLocked(userId, userState);
6706 }
6707 }
6708
6709 @Override
6710 public void onHandleAppCrash(WindowProcessController wpc) {
6711 synchronized (mGlobalLock) {
6712 mStackSupervisor.handleAppCrashLocked(wpc);
6713 }
6714 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006715
6716 @Override
6717 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6718 synchronized (mGlobalLock) {
6719 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6720 }
6721 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006722
6723 @Override
6724 public void onUidActive(int uid, int procState) {
6725 synchronized (mGlobalLock) {
6726 mActiveUids.put(uid, procState);
6727 }
6728 }
6729
6730 @Override
6731 public void onUidInactive(int uid) {
6732 synchronized (mGlobalLock) {
6733 mActiveUids.remove(uid);
6734 }
6735 }
6736
6737 @Override
6738 public void onActiveUidsCleared() {
6739 synchronized (mGlobalLock) {
6740 mActiveUids.clear();
6741 }
6742 }
6743
6744 @Override
6745 public void onUidProcStateChanged(int uid, int procState) {
6746 synchronized (mGlobalLock) {
6747 if (mActiveUids.get(uid) != null) {
6748 mActiveUids.put(uid, procState);
6749 }
6750 }
6751 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006752
6753 @Override
6754 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6755 synchronized (mGlobalLock) {
6756 mPendingTempWhitelist.put(uid, tag);
6757 }
6758 }
6759
6760 @Override
6761 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6762 synchronized (mGlobalLock) {
6763 mPendingTempWhitelist.remove(uid);
6764 }
6765 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006766
6767 @Override
6768 public boolean handleAppCrashInActivityController(String processName, int pid,
6769 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6770 Runnable killCrashingAppCallback) {
6771 synchronized (mGlobalLock) {
6772 if (mController == null) {
6773 return false;
6774 }
6775
6776 try {
6777 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6778 stackTrace)) {
6779 killCrashingAppCallback.run();
6780 return true;
6781 }
6782 } catch (RemoteException e) {
6783 mController = null;
6784 Watchdog.getInstance().setActivityController(null);
6785 }
6786 return false;
6787 }
6788 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006789
6790 @Override
6791 public void removeRecentTasksByPackageName(String packageName, int userId) {
6792 synchronized (mGlobalLock) {
6793 mRecentTasks.removeTasksByPackageName(packageName, userId);
6794 }
6795 }
6796
6797 @Override
6798 public void cleanupRecentTasksForUser(int userId) {
6799 synchronized (mGlobalLock) {
6800 mRecentTasks.cleanupLocked(userId);
6801 }
6802 }
6803
6804 @Override
6805 public void loadRecentTasksForUser(int userId) {
6806 synchronized (mGlobalLock) {
6807 mRecentTasks.loadUserRecentsLocked(userId);
6808 }
6809 }
6810
6811 @Override
6812 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6813 synchronized (mGlobalLock) {
6814 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6815 }
6816 }
6817
6818 @Override
6819 public void flushRecentTasks() {
6820 mRecentTasks.flush();
6821 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006822
6823 @Override
6824 public WindowProcessController getHomeProcess() {
6825 synchronized (mGlobalLock) {
6826 return mHomeProcess;
6827 }
6828 }
6829
6830 @Override
6831 public WindowProcessController getPreviousProcess() {
6832 synchronized (mGlobalLock) {
6833 return mPreviousProcess;
6834 }
6835 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006836
6837 @Override
6838 public void clearLockedTasks(String reason) {
6839 synchronized (mGlobalLock) {
6840 getLockTaskController().clearLockedTasks(reason);
6841 }
6842 }
6843
6844 @Override
6845 public void updateUserConfiguration() {
6846 synchronized (mGlobalLock) {
6847 final Configuration configuration = new Configuration(getGlobalConfiguration());
6848 final int currentUserId = mAmInternal.getCurrentUserId();
6849 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6850 configuration, currentUserId, Settings.System.canWrite(mContext));
6851 updateConfigurationLocked(configuration, null /* starting */,
6852 false /* initLocale */, false /* persistent */, currentUserId,
6853 false /* deferResume */);
6854 }
6855 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006856
6857 @Override
6858 public boolean canShowErrorDialogs() {
6859 synchronized (mGlobalLock) {
6860 return mShowDialogs && !mSleeping && !mShuttingDown
6861 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6862 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6863 mAmInternal.getCurrentUserId())
6864 && !(UserManager.isDeviceInDemoMode(mContext)
6865 && mAmInternal.getCurrentUser().isDemo());
6866 }
6867 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006868
6869 @Override
6870 public void setProfileApp(String profileApp) {
6871 synchronized (mGlobalLock) {
6872 mProfileApp = profileApp;
6873 }
6874 }
6875
6876 @Override
6877 public void setProfileProc(WindowProcessController wpc) {
6878 synchronized (mGlobalLock) {
6879 mProfileProc = wpc;
6880 }
6881 }
6882
6883 @Override
6884 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6885 synchronized (mGlobalLock) {
6886 mProfilerInfo = profilerInfo;
6887 }
6888 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006889 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08006890}