blob: 1d3b336d60e5cbbc893c281209726ec109a6aee9 [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.ALWAYS_FINISH_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
62import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070063import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
64import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
66import 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;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700282import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700284import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700285import java.util.Map;
286import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700287
288/**
289 * System service for managing activities and their containers (task, stacks, displays,... ).
290 *
291 * {@hide}
292 */
293public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700294 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700295 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700296 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
297 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
298 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
299 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
300 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700301 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700302
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700303 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700304 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700305 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700306 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700307
Wale Ogunwale98875612018-10-12 07:53:02 -0700308 /** Used to indicate that an app transition should be animated. */
309 static final boolean ANIMATE = true;
310
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700311 /** Hardware-reported OpenGLES version. */
312 final int GL_ES_VERSION;
313
Wale Ogunwale31913b52018-10-13 08:29:31 -0700314 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
315 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
316 public static final String DUMP_LASTANR_CMD = "lastanr" ;
317 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
318 public static final String DUMP_STARTER_CMD = "starter" ;
319 public static final String DUMP_CONTAINERS_CMD = "containers" ;
320 public static final String DUMP_RECENTS_CMD = "recents" ;
321 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
322
Wale Ogunwale64258362018-10-16 15:13:37 -0700323 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
324 public static final int RELAUNCH_REASON_NONE = 0;
325 /** This activity is being relaunched due to windowing mode change. */
326 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
327 /** This activity is being relaunched due to a free-resize operation. */
328 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
329
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700330 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700331
Wale Ogunwalef6733932018-06-27 05:14:34 -0700332 /**
333 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
334 * change at runtime. Use mContext for non-UI purposes.
335 */
336 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700337 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700338 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700340 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700341 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700342 private PackageManagerInternal mPmInternal;
Wale Ogunwale53783742018-09-16 10:21:51 -0700343 private ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 PowerManagerInternal mPowerManagerInternal;
345 private UsageStatsManagerInternal mUsageStatsInternal;
346
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700347 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 IntentFirewall mIntentFirewall;
349
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700350 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800351 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700352 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700353 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700354 private UserManagerService mUserManager;
355 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700356 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700357 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
358 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700359 /** All processes currently running that might have a window organized by name. */
360 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700361 /** All processes we currently have running mapped by pid */
362 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700363 /** This is the process holding what we currently consider to be the "home" activity. */
364 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700365 /** The currently running heavy-weight process, if any. */
366 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700367 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700368 /**
369 * This is the process holding the activity the user last visited that is in a different process
370 * from the one they are currently in.
371 */
372 WindowProcessController mPreviousProcess;
373 /** The time at which the previous process was last visible. */
374 long mPreviousProcessVisibleTime;
375
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700376 /** List of intents that were used to start the most recent tasks. */
377 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700378 /** State of external calls telling us if the device is awake or asleep. */
379 private boolean mKeyguardShown = false;
380
381 // Wrapper around VoiceInteractionServiceManager
382 private AssistUtils mAssistUtils;
383
384 // VoiceInteraction session ID that changes for each new request except when
385 // being called for multi-window assist in a single session.
386 private int mViSessionId = 1000;
387
388 // How long to wait in getAssistContextExtras for the activity and foreground services
389 // to respond with the result.
390 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
391
392 // How long top wait when going through the modern assist (which doesn't need to block
393 // on getting this result before starting to launch its UI).
394 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
395
396 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
397 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
398
399 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
400
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700401 // Keeps track of the active voice interaction service component, notified from
402 // VoiceInteractionManagerService
403 ComponentName mActiveVoiceInteractionServiceComponent;
404
Wale Ogunwalee2172292018-10-25 10:11:10 -0700405 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700406 KeyguardController mKeyguardController;
407 private final ClientLifecycleManager mLifecycleManager;
408 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700409 /** The controller for all operations related to locktask. */
410 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700411 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700412
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700413 boolean mSuppressResizeConfigChanges;
414
415 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
416 new UpdateConfigurationResult();
417
418 static final class UpdateConfigurationResult {
419 // Configuration changes that were updated.
420 int changes;
421 // If the activity was relaunched to match the new configuration.
422 boolean activityRelaunched;
423
424 void reset() {
425 changes = 0;
426 activityRelaunched = false;
427 }
428 }
429
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700430 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700431 private int mConfigurationSeq;
432 // To cache the list of supported system locales
433 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700434
435 /**
436 * Temp object used when global and/or display override configuration is updated. It is also
437 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
438 * anyone...
439 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700440 private Configuration mTempConfig = new Configuration();
441
Wale Ogunwalef6733932018-06-27 05:14:34 -0700442 /** Temporary to avoid allocations. */
443 final StringBuilder mStringBuilder = new StringBuilder(256);
444
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700445 // Amount of time after a call to stopAppSwitches() during which we will
446 // prevent further untrusted switches from happening.
447 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
448
449 /**
450 * The time at which we will allow normal application switches again,
451 * after a call to {@link #stopAppSwitches()}.
452 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700453 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700454 /**
455 * This is set to true after the first switch after mAppSwitchesAllowedTime
456 * is set; any switches after that will clear the time.
457 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700458 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700459
460 IActivityController mController = null;
461 boolean mControllerIsAMonkey = false;
462
Wale Ogunwale214f3482018-10-04 11:00:47 -0700463 final int mFactoryTest;
464
465 /** Used to control how we initialize the service. */
466 ComponentName mTopComponent;
467 String mTopAction = Intent.ACTION_MAIN;
468 String mTopData;
469
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800470 /** Profiling app information. */
471 String mProfileApp = null;
472 WindowProcessController mProfileProc = null;
473 ProfilerInfo mProfilerInfo = null;
474
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700475 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700476 * Dump of the activity state at the time of the last ANR. Cleared after
477 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
478 */
479 String mLastANRState;
480
481 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700482 * Used to retain an update lock when the foreground activity is in
483 * immersive mode.
484 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700485 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700486
487 /**
488 * Packages that are being allowed to perform unrestricted app switches. Mapping is
489 * User -> Type -> uid.
490 */
491 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
492
493 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700494 private int mThumbnailWidth;
495 private int mThumbnailHeight;
496 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700497
498 /**
499 * Flag that indicates if multi-window is enabled.
500 *
501 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
502 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
503 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
504 * At least one of the forms of multi-window must be enabled in order for this flag to be
505 * initialized to 'true'.
506 *
507 * @see #mSupportsSplitScreenMultiWindow
508 * @see #mSupportsFreeformWindowManagement
509 * @see #mSupportsPictureInPicture
510 * @see #mSupportsMultiDisplay
511 */
512 boolean mSupportsMultiWindow;
513 boolean mSupportsSplitScreenMultiWindow;
514 boolean mSupportsFreeformWindowManagement;
515 boolean mSupportsPictureInPicture;
516 boolean mSupportsMultiDisplay;
517 boolean mForceResizableActivities;
518
519 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
520
521 // VR Vr2d Display Id.
522 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700523
Wale Ogunwalef6733932018-06-27 05:14:34 -0700524 /**
525 * Set while we are wanting to sleep, to prevent any
526 * activities from being started/resumed.
527 *
528 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
529 *
530 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
531 * while in the sleep state until there is a pending transition out of sleep, in which case
532 * mSleeping is set to false, and remains false while awake.
533 *
534 * Whether mSleeping can quickly toggled between true/false without the device actually
535 * display changing states is undefined.
536 */
537 private boolean mSleeping = false;
538
539 /**
540 * The process state used for processes that are running the top activities.
541 * This changes between TOP and TOP_SLEEPING to following mSleeping.
542 */
543 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
544
545 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
546 // automatically. Important for devices without direct input devices.
547 private boolean mShowDialogs = true;
548
549 /** Set if we are shutting down the system, similar to sleeping. */
550 boolean mShuttingDown = false;
551
552 /**
553 * We want to hold a wake lock while running a voice interaction session, since
554 * this may happen with the screen off and we need to keep the CPU running to
555 * be able to continue to interact with the user.
556 */
557 PowerManager.WakeLock mVoiceWakeLock;
558
559 /**
560 * Set while we are running a voice interaction. This overrides sleeping while it is active.
561 */
562 IVoiceInteractionSession mRunningVoice;
563
564 /**
565 * The last resumed activity. This is identical to the current resumed activity most
566 * of the time but could be different when we're pausing one activity before we resume
567 * another activity.
568 */
569 ActivityRecord mLastResumedActivity;
570
571 /**
572 * The activity that is currently being traced as the active resumed activity.
573 *
574 * @see #updateResumedAppTrace
575 */
576 private @Nullable ActivityRecord mTracedResumedActivity;
577
578 /** If non-null, we are tracking the time the user spends in the currently focused app. */
579 AppTimeTracker mCurAppTimeTracker;
580
Wale Ogunwale008163e2018-07-23 23:11:08 -0700581 private AppWarnings mAppWarnings;
582
Wale Ogunwale53783742018-09-16 10:21:51 -0700583 /**
584 * Packages that the user has asked to have run in screen size
585 * compatibility mode instead of filling the screen.
586 */
587 CompatModePackages mCompatModePackages;
588
Wale Ogunwalef6733932018-06-27 05:14:34 -0700589 private FontScaleSettingObserver mFontScaleSettingObserver;
590
591 private final class FontScaleSettingObserver extends ContentObserver {
592 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
593 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
594
595 public FontScaleSettingObserver() {
596 super(mH);
597 final ContentResolver resolver = mContext.getContentResolver();
598 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
599 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
600 UserHandle.USER_ALL);
601 }
602
603 @Override
604 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
605 if (mFontScaleUri.equals(uri)) {
606 updateFontScaleIfNeeded(userId);
607 } else if (mHideErrorDialogsUri.equals(uri)) {
608 synchronized (mGlobalLock) {
609 updateShouldShowDialogsLocked(getGlobalConfiguration());
610 }
611 }
612 }
613 }
614
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700615 ActivityTaskManagerService(Context context) {
616 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700617 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700618 mSystemThread = ActivityThread.currentActivityThread();
619 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700620 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700621 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700622 }
623
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700624 public void onSystemReady() {
625 synchronized (mGlobalLock) {
626 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
627 PackageManager.FEATURE_CANT_SAVE_STATE);
628 mAssistUtils = new AssistUtils(mContext);
629 mVrController.onSystemReady();
630 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700631 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700632 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700633 }
634
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700635 public void onInitPowerManagement() {
636 synchronized (mGlobalLock) {
637 mStackSupervisor.initPowerManagement();
638 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
639 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
640 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
641 mVoiceWakeLock.setReferenceCounted(false);
642 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700643 }
644
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700645 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700646 mFontScaleSettingObserver = new FontScaleSettingObserver();
647 }
648
Wale Ogunwale59507092018-10-29 09:00:30 -0700649 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700650 final boolean freeformWindowManagement =
651 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
652 || Settings.Global.getInt(
653 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
654
655 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
656 final boolean supportsPictureInPicture = supportsMultiWindow &&
657 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
658 final boolean supportsSplitScreenMultiWindow =
659 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
660 final boolean supportsMultiDisplay = mContext.getPackageManager()
661 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
662 final boolean alwaysFinishActivities =
663 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
664 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
665 final boolean forceResizable = Settings.Global.getInt(
666 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700667 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700668
669 // Transfer any global setting for forcing RTL layout, into a System Property
670 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
671
672 final Configuration configuration = new Configuration();
673 Settings.System.getConfiguration(resolver, configuration);
674 if (forceRtl) {
675 // This will take care of setting the correct layout direction flags
676 configuration.setLayoutDirection(configuration.locale);
677 }
678
679 synchronized (mGlobalLock) {
680 mForceResizableActivities = forceResizable;
681 final boolean multiWindowFormEnabled = freeformWindowManagement
682 || supportsSplitScreenMultiWindow
683 || supportsPictureInPicture
684 || supportsMultiDisplay;
685 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
686 mSupportsMultiWindow = true;
687 mSupportsFreeformWindowManagement = freeformWindowManagement;
688 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
689 mSupportsPictureInPicture = supportsPictureInPicture;
690 mSupportsMultiDisplay = supportsMultiDisplay;
691 } else {
692 mSupportsMultiWindow = false;
693 mSupportsFreeformWindowManagement = false;
694 mSupportsSplitScreenMultiWindow = false;
695 mSupportsPictureInPicture = false;
696 mSupportsMultiDisplay = false;
697 }
698 mWindowManager.setForceResizableTasks(mForceResizableActivities);
699 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700700 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
701 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700702 // This happens before any activities are started, so we can change global configuration
703 // in-place.
704 updateConfigurationLocked(configuration, null, true);
705 final Configuration globalConfig = getGlobalConfiguration();
706 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
707
708 // Load resources only after the current configuration has been set.
709 final Resources res = mContext.getResources();
710 mThumbnailWidth = res.getDimensionPixelSize(
711 com.android.internal.R.dimen.thumbnail_width);
712 mThumbnailHeight = res.getDimensionPixelSize(
713 com.android.internal.R.dimen.thumbnail_height);
714
715 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
716 mFullscreenThumbnailScale = (float) res
717 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
718 (float) globalConfig.screenWidthDp;
719 } else {
720 mFullscreenThumbnailScale = res.getFraction(
721 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
722 }
723 }
724 }
725
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800726 public WindowManagerGlobalLock getGlobalLock() {
727 return mGlobalLock;
728 }
729
730 public void setActivityManagerService(IntentFirewall intentFirewall,
731 PendingIntentController intentController) {
732 mH = new H();
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700733 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700734 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700735 final File systemDir = SystemServiceManager.ensureSystemDir();
736 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
737 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700738 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700739
740 mTempConfig.setToDefaults();
741 mTempConfig.setLocales(LocaleList.getDefault());
742 mConfigurationSeq = mTempConfig.seq = 1;
743 mStackSupervisor = createStackSupervisor();
744 mStackSupervisor.onConfigurationChanged(mTempConfig);
745
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700746 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700747 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700748 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700749 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700750 mRecentTasks = createRecentTasks();
751 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700752 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700753 mKeyguardController = mStackSupervisor.getKeyguardController();
754 }
755
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700756 public void onActivityManagerInternalAdded() {
757 synchronized (mGlobalLock) {
758 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
759 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
760 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700761 }
762
Yunfan Chen75157d72018-07-27 14:47:21 +0900763 int increaseConfigurationSeqLocked() {
764 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
765 return mConfigurationSeq;
766 }
767
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700768 protected ActivityStackSupervisor createStackSupervisor() {
769 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
770 supervisor.initialize();
771 return supervisor;
772 }
773
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700774 public void setWindowManager(WindowManagerService wm) {
775 synchronized (mGlobalLock) {
776 mWindowManager = wm;
777 mLockTaskController.setWindowManager(wm);
778 mStackSupervisor.setWindowManager(wm);
779 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700780 }
781
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700782 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
783 synchronized (mGlobalLock) {
784 mUsageStatsInternal = usageStatsManager;
785 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700786 }
787
Wale Ogunwalef6733932018-06-27 05:14:34 -0700788 UserManagerService getUserManager() {
789 if (mUserManager == null) {
790 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
791 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
792 }
793 return mUserManager;
794 }
795
796 AppOpsService getAppOpsService() {
797 if (mAppOpsService == null) {
798 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
799 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
800 }
801 return mAppOpsService;
802 }
803
804 boolean hasUserRestriction(String restriction, int userId) {
805 return getUserManager().hasUserRestriction(restriction, userId);
806 }
807
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700808 protected RecentTasks createRecentTasks() {
809 return new RecentTasks(this, mStackSupervisor);
810 }
811
812 RecentTasks getRecentTasks() {
813 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700814 }
815
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700816 ClientLifecycleManager getLifecycleManager() {
817 return mLifecycleManager;
818 }
819
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700820 ActivityStartController getActivityStartController() {
821 return mActivityStartController;
822 }
823
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700824 TaskChangeNotificationController getTaskChangeNotificationController() {
825 return mTaskChangeNotificationController;
826 }
827
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700828 LockTaskController getLockTaskController() {
829 return mLockTaskController;
830 }
831
Yunfan Chen75157d72018-07-27 14:47:21 +0900832 /**
833 * Return the global configuration used by the process corresponding to the input pid. This is
834 * usually the global configuration with some overrides specific to that process.
835 */
836 Configuration getGlobalConfigurationForCallingPid() {
837 final int pid = Binder.getCallingPid();
838 if (pid == MY_PID || pid < 0) {
839 return getGlobalConfiguration();
840 }
841 synchronized (mGlobalLock) {
842 final WindowProcessController app = mPidMap.get(pid);
843 return app != null ? app.getConfiguration() : getGlobalConfiguration();
844 }
845 }
846
847 /**
848 * Return the device configuration info used by the process corresponding to the input pid.
849 * The value is consistent with the global configuration for the process.
850 */
851 @Override
852 public ConfigurationInfo getDeviceConfigurationInfo() {
853 ConfigurationInfo config = new ConfigurationInfo();
854 synchronized (mGlobalLock) {
855 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
856 config.reqTouchScreen = globalConfig.touchscreen;
857 config.reqKeyboardType = globalConfig.keyboard;
858 config.reqNavigation = globalConfig.navigation;
859 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
860 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
861 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
862 }
863 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
864 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
865 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
866 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700867 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900868 }
869 return config;
870 }
871
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700872 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700873 mInternal = new LocalService();
874 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700875 }
876
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700877 public static final class Lifecycle extends SystemService {
878 private final ActivityTaskManagerService mService;
879
880 public Lifecycle(Context context) {
881 super(context);
882 mService = new ActivityTaskManagerService(context);
883 }
884
885 @Override
886 public void onStart() {
887 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700888 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700889 }
890
Garfield Tan891146c2018-10-09 12:14:00 -0700891 @Override
892 public void onUnlockUser(int userId) {
893 synchronized (mService.getGlobalLock()) {
894 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
895 }
896 }
897
898 @Override
899 public void onCleanupUser(int userId) {
900 synchronized (mService.getGlobalLock()) {
901 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
902 }
903 }
904
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700905 public ActivityTaskManagerService getService() {
906 return mService;
907 }
908 }
909
910 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700911 public final int startActivity(IApplicationThread caller, String callingPackage,
912 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
913 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
914 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
915 resultWho, requestCode, startFlags, profilerInfo, bOptions,
916 UserHandle.getCallingUserId());
917 }
918
919 @Override
920 public final int startActivities(IApplicationThread caller, String callingPackage,
921 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
922 int userId) {
923 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700924 enforceNotIsolatedCaller(reason);
925 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700926 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700927 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100928 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
929 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700930 }
931
932 @Override
933 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
934 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
935 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
936 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
937 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
938 true /*validateIncomingUser*/);
939 }
940
941 int startActivityAsUser(IApplicationThread caller, String callingPackage,
942 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
943 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
944 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700945 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700946
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700947 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700948 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
949
950 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700951 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700952 .setCaller(caller)
953 .setCallingPackage(callingPackage)
954 .setResolvedType(resolvedType)
955 .setResultTo(resultTo)
956 .setResultWho(resultWho)
957 .setRequestCode(requestCode)
958 .setStartFlags(startFlags)
959 .setProfilerInfo(profilerInfo)
960 .setActivityOptions(bOptions)
961 .setMayWait(userId)
962 .execute();
963
964 }
965
966 @Override
967 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
968 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700969 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
970 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700971 // Refuse possible leaked file descriptors
972 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
973 throw new IllegalArgumentException("File descriptors passed in Intent");
974 }
975
976 if (!(target instanceof PendingIntentRecord)) {
977 throw new IllegalArgumentException("Bad PendingIntent object");
978 }
979
980 PendingIntentRecord pir = (PendingIntentRecord)target;
981
982 synchronized (mGlobalLock) {
983 // If this is coming from the currently resumed activity, it is
984 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -0700985 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700986 if (stack.mResumedActivity != null &&
987 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700988 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700989 }
990 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700991 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700992 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700993 }
994
995 @Override
996 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
997 Bundle bOptions) {
998 // Refuse possible leaked file descriptors
999 if (intent != null && intent.hasFileDescriptors()) {
1000 throw new IllegalArgumentException("File descriptors passed in Intent");
1001 }
1002 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1003
1004 synchronized (mGlobalLock) {
1005 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1006 if (r == null) {
1007 SafeActivityOptions.abort(options);
1008 return false;
1009 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001010 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001011 // The caller is not running... d'oh!
1012 SafeActivityOptions.abort(options);
1013 return false;
1014 }
1015 intent = new Intent(intent);
1016 // The caller is not allowed to change the data.
1017 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1018 // And we are resetting to find the next component...
1019 intent.setComponent(null);
1020
1021 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1022
1023 ActivityInfo aInfo = null;
1024 try {
1025 List<ResolveInfo> resolves =
1026 AppGlobals.getPackageManager().queryIntentActivities(
1027 intent, r.resolvedType,
1028 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1029 UserHandle.getCallingUserId()).getList();
1030
1031 // Look for the original activity in the list...
1032 final int N = resolves != null ? resolves.size() : 0;
1033 for (int i=0; i<N; i++) {
1034 ResolveInfo rInfo = resolves.get(i);
1035 if (rInfo.activityInfo.packageName.equals(r.packageName)
1036 && rInfo.activityInfo.name.equals(r.info.name)) {
1037 // We found the current one... the next matching is
1038 // after it.
1039 i++;
1040 if (i<N) {
1041 aInfo = resolves.get(i).activityInfo;
1042 }
1043 if (debug) {
1044 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1045 + "/" + r.info.name);
1046 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1047 ? "null" : aInfo.packageName + "/" + aInfo.name));
1048 }
1049 break;
1050 }
1051 }
1052 } catch (RemoteException e) {
1053 }
1054
1055 if (aInfo == null) {
1056 // Nobody who is next!
1057 SafeActivityOptions.abort(options);
1058 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1059 return false;
1060 }
1061
1062 intent.setComponent(new ComponentName(
1063 aInfo.applicationInfo.packageName, aInfo.name));
1064 intent.setFlags(intent.getFlags()&~(
1065 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1066 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1067 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1068 FLAG_ACTIVITY_NEW_TASK));
1069
1070 // Okay now we need to start the new activity, replacing the currently running activity.
1071 // This is a little tricky because we want to start the new one as if the current one is
1072 // finished, but not finish the current one first so that there is no flicker.
1073 // And thus...
1074 final boolean wasFinishing = r.finishing;
1075 r.finishing = true;
1076
1077 // Propagate reply information over to the new activity.
1078 final ActivityRecord resultTo = r.resultTo;
1079 final String resultWho = r.resultWho;
1080 final int requestCode = r.requestCode;
1081 r.resultTo = null;
1082 if (resultTo != null) {
1083 resultTo.removeResultsLocked(r, resultWho, requestCode);
1084 }
1085
1086 final long origId = Binder.clearCallingIdentity();
1087 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001088 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001089 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001090 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001091 .setResolvedType(r.resolvedType)
1092 .setActivityInfo(aInfo)
1093 .setResultTo(resultTo != null ? resultTo.appToken : null)
1094 .setResultWho(resultWho)
1095 .setRequestCode(requestCode)
1096 .setCallingPid(-1)
1097 .setCallingUid(r.launchedFromUid)
1098 .setCallingPackage(r.launchedFromPackage)
1099 .setRealCallingPid(-1)
1100 .setRealCallingUid(r.launchedFromUid)
1101 .setActivityOptions(options)
1102 .execute();
1103 Binder.restoreCallingIdentity(origId);
1104
1105 r.finishing = wasFinishing;
1106 if (res != ActivityManager.START_SUCCESS) {
1107 return false;
1108 }
1109 return true;
1110 }
1111 }
1112
1113 @Override
1114 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1115 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1116 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1117 final WaitResult res = new WaitResult();
1118 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001119 enforceNotIsolatedCaller("startActivityAndWait");
1120 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1121 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001122 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001123 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001124 .setCaller(caller)
1125 .setCallingPackage(callingPackage)
1126 .setResolvedType(resolvedType)
1127 .setResultTo(resultTo)
1128 .setResultWho(resultWho)
1129 .setRequestCode(requestCode)
1130 .setStartFlags(startFlags)
1131 .setActivityOptions(bOptions)
1132 .setMayWait(userId)
1133 .setProfilerInfo(profilerInfo)
1134 .setWaitResult(res)
1135 .execute();
1136 }
1137 return res;
1138 }
1139
1140 @Override
1141 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1142 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1143 int startFlags, Configuration config, Bundle bOptions, int userId) {
1144 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001145 enforceNotIsolatedCaller("startActivityWithConfig");
1146 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1147 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001148 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001149 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001150 .setCaller(caller)
1151 .setCallingPackage(callingPackage)
1152 .setResolvedType(resolvedType)
1153 .setResultTo(resultTo)
1154 .setResultWho(resultWho)
1155 .setRequestCode(requestCode)
1156 .setStartFlags(startFlags)
1157 .setGlobalConfiguration(config)
1158 .setActivityOptions(bOptions)
1159 .setMayWait(userId)
1160 .execute();
1161 }
1162 }
1163
1164 @Override
1165 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1166 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1167 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
1168 int userId) {
1169
1170 // This is very dangerous -- it allows you to perform a start activity (including
1171 // permission grants) as any app that may launch one of your own activities. So
1172 // we will only allow this to be done from activities that are part of the core framework,
1173 // and then only when they are running as the system.
1174 final ActivityRecord sourceRecord;
1175 final int targetUid;
1176 final String targetPackage;
1177 final boolean isResolver;
1178 synchronized (mGlobalLock) {
1179 if (resultTo == null) {
1180 throw new SecurityException("Must be called from an activity");
1181 }
1182 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
1183 if (sourceRecord == null) {
1184 throw new SecurityException("Called with bad activity token: " + resultTo);
1185 }
1186 if (!sourceRecord.info.packageName.equals("android")) {
1187 throw new SecurityException(
1188 "Must be called from an activity that is declared in the android package");
1189 }
1190 if (sourceRecord.app == null) {
1191 throw new SecurityException("Called without a process attached to activity");
1192 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001193 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 // This is still okay, as long as this activity is running under the
1195 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001196 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001197 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001198 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001199 + " must be system uid or original calling uid "
1200 + sourceRecord.launchedFromUid);
1201 }
1202 }
1203 if (ignoreTargetSecurity) {
1204 if (intent.getComponent() == null) {
1205 throw new SecurityException(
1206 "Component must be specified with ignoreTargetSecurity");
1207 }
1208 if (intent.getSelector() != null) {
1209 throw new SecurityException(
1210 "Selector not allowed with ignoreTargetSecurity");
1211 }
1212 }
1213 targetUid = sourceRecord.launchedFromUid;
1214 targetPackage = sourceRecord.launchedFromPackage;
1215 isResolver = sourceRecord.isResolverOrChildActivity();
1216 }
1217
1218 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001219 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001220 }
1221
1222 // TODO: Switch to user app stacks here.
1223 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001224 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001225 .setCallingUid(targetUid)
1226 .setCallingPackage(targetPackage)
1227 .setResolvedType(resolvedType)
1228 .setResultTo(resultTo)
1229 .setResultWho(resultWho)
1230 .setRequestCode(requestCode)
1231 .setStartFlags(startFlags)
1232 .setActivityOptions(bOptions)
1233 .setMayWait(userId)
1234 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1235 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1236 .execute();
1237 } catch (SecurityException e) {
1238 // XXX need to figure out how to propagate to original app.
1239 // A SecurityException here is generally actually a fault of the original
1240 // calling activity (such as a fairly granting permissions), so propagate it
1241 // back to them.
1242 /*
1243 StringBuilder msg = new StringBuilder();
1244 msg.append("While launching");
1245 msg.append(intent.toString());
1246 msg.append(": ");
1247 msg.append(e.getMessage());
1248 */
1249 throw e;
1250 }
1251 }
1252
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001253 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1254 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1255 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1256 }
1257
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001258 @Override
1259 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1260 Intent intent, String resolvedType, IVoiceInteractionSession session,
1261 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1262 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001263 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001264 if (session == null || interactor == null) {
1265 throw new NullPointerException("null session or interactor");
1266 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001267 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001268 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001269 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001270 .setCallingUid(callingUid)
1271 .setCallingPackage(callingPackage)
1272 .setResolvedType(resolvedType)
1273 .setVoiceSession(session)
1274 .setVoiceInteractor(interactor)
1275 .setStartFlags(startFlags)
1276 .setProfilerInfo(profilerInfo)
1277 .setActivityOptions(bOptions)
1278 .setMayWait(userId)
1279 .execute();
1280 }
1281
1282 @Override
1283 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1284 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001285 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1286 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001288 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 .setCallingUid(callingUid)
1290 .setCallingPackage(callingPackage)
1291 .setResolvedType(resolvedType)
1292 .setActivityOptions(bOptions)
1293 .setMayWait(userId)
1294 .execute();
1295 }
1296
1297 @Override
1298 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1299 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001300 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001301 final int callingPid = Binder.getCallingPid();
1302 final long origId = Binder.clearCallingIdentity();
1303 try {
1304 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001305 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1306 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001307
1308 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001309 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1310 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001311 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1312 recentsUid, assistDataReceiver);
1313 }
1314 } finally {
1315 Binder.restoreCallingIdentity(origId);
1316 }
1317 }
1318
1319 @Override
1320 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001321 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001322 "startActivityFromRecents()");
1323
1324 final int callingPid = Binder.getCallingPid();
1325 final int callingUid = Binder.getCallingUid();
1326 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1327 final long origId = Binder.clearCallingIdentity();
1328 try {
1329 synchronized (mGlobalLock) {
1330 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1331 safeOptions);
1332 }
1333 } finally {
1334 Binder.restoreCallingIdentity(origId);
1335 }
1336 }
1337
1338 /**
1339 * This is the internal entry point for handling Activity.finish().
1340 *
1341 * @param token The Binder token referencing the Activity we want to finish.
1342 * @param resultCode Result code, if any, from this Activity.
1343 * @param resultData Result data (Intent), if any, from this Activity.
1344 * @param finishTask Whether to finish the task associated with this Activity.
1345 *
1346 * @return Returns true if the activity successfully finished, or false if it is still running.
1347 */
1348 @Override
1349 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1350 int finishTask) {
1351 // Refuse possible leaked file descriptors
1352 if (resultData != null && resultData.hasFileDescriptors()) {
1353 throw new IllegalArgumentException("File descriptors passed in Intent");
1354 }
1355
1356 synchronized (mGlobalLock) {
1357 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1358 if (r == null) {
1359 return true;
1360 }
1361 // Keep track of the root activity of the task before we finish it
1362 TaskRecord tr = r.getTask();
1363 ActivityRecord rootR = tr.getRootActivity();
1364 if (rootR == null) {
1365 Slog.w(TAG, "Finishing task with all activities already finished");
1366 }
1367 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1368 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001369 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 return false;
1371 }
1372
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001373 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1374 // We should consolidate.
1375 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001376 // Find the first activity that is not finishing.
1377 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1378 if (next != null) {
1379 // ask watcher if this is allowed
1380 boolean resumeOK = true;
1381 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001382 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001383 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001384 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001385 Watchdog.getInstance().setActivityController(null);
1386 }
1387
1388 if (!resumeOK) {
1389 Slog.i(TAG, "Not finishing activity because controller resumed");
1390 return false;
1391 }
1392 }
1393 }
1394 final long origId = Binder.clearCallingIdentity();
1395 try {
1396 boolean res;
1397 final boolean finishWithRootActivity =
1398 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1399 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1400 || (finishWithRootActivity && r == rootR)) {
1401 // If requested, remove the task that is associated to this activity only if it
1402 // was the root activity in the task. The result code and data is ignored
1403 // because we don't support returning them across task boundaries. Also, to
1404 // keep backwards compatibility we remove the task from recents when finishing
1405 // task with root activity.
1406 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1407 finishWithRootActivity, "finish-activity");
1408 if (!res) {
1409 Slog.i(TAG, "Removing task failed to finish activity");
1410 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001411 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001412 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 } else {
1414 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1415 resultData, "app-request", true);
1416 if (!res) {
1417 Slog.i(TAG, "Failed to finish by app-request");
1418 }
1419 }
1420 return res;
1421 } finally {
1422 Binder.restoreCallingIdentity(origId);
1423 }
1424 }
1425 }
1426
1427 @Override
1428 public boolean finishActivityAffinity(IBinder token) {
1429 synchronized (mGlobalLock) {
1430 final long origId = Binder.clearCallingIdentity();
1431 try {
1432 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1433 if (r == null) {
1434 return false;
1435 }
1436
1437 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1438 // can finish.
1439 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001440 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 return false;
1442 }
1443 return task.getStack().finishActivityAffinityLocked(r);
1444 } finally {
1445 Binder.restoreCallingIdentity(origId);
1446 }
1447 }
1448 }
1449
1450 @Override
1451 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1452 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001453 try {
1454 WindowProcessController proc = null;
1455 synchronized (mGlobalLock) {
1456 ActivityStack stack = ActivityRecord.getStackLocked(token);
1457 if (stack == null) {
1458 return;
1459 }
1460 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1461 false /* fromTimeout */, false /* processPausingActivities */, config);
1462 if (r != null) {
1463 proc = r.app;
1464 }
1465 if (stopProfiling && proc != null) {
1466 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001467 }
1468 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001469 } finally {
1470 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001471 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001472 }
1473
1474 @Override
1475 public final void activityResumed(IBinder token) {
1476 final long origId = Binder.clearCallingIdentity();
1477 synchronized (mGlobalLock) {
1478 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001479 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001480 }
1481 Binder.restoreCallingIdentity(origId);
1482 }
1483
1484 @Override
1485 public final void activityPaused(IBinder token) {
1486 final long origId = Binder.clearCallingIdentity();
1487 synchronized (mGlobalLock) {
1488 ActivityStack stack = ActivityRecord.getStackLocked(token);
1489 if (stack != null) {
1490 stack.activityPausedLocked(token, false);
1491 }
1492 }
1493 Binder.restoreCallingIdentity(origId);
1494 }
1495
1496 @Override
1497 public final void activityStopped(IBinder token, Bundle icicle,
1498 PersistableBundle persistentState, CharSequence description) {
1499 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1500
1501 // Refuse possible leaked file descriptors
1502 if (icicle != null && icicle.hasFileDescriptors()) {
1503 throw new IllegalArgumentException("File descriptors passed in Bundle");
1504 }
1505
1506 final long origId = Binder.clearCallingIdentity();
1507
1508 synchronized (mGlobalLock) {
1509 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1510 if (r != null) {
1511 r.activityStoppedLocked(icicle, persistentState, description);
1512 }
1513 }
1514
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001515 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516
1517 Binder.restoreCallingIdentity(origId);
1518 }
1519
1520 @Override
1521 public final void activityDestroyed(IBinder token) {
1522 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1523 synchronized (mGlobalLock) {
1524 ActivityStack stack = ActivityRecord.getStackLocked(token);
1525 if (stack != null) {
1526 stack.activityDestroyedLocked(token, "activityDestroyed");
1527 }
1528 }
1529 }
1530
1531 @Override
1532 public final void activityRelaunched(IBinder token) {
1533 final long origId = Binder.clearCallingIdentity();
1534 synchronized (mGlobalLock) {
1535 mStackSupervisor.activityRelaunchedLocked(token);
1536 }
1537 Binder.restoreCallingIdentity(origId);
1538 }
1539
1540 public final void activitySlept(IBinder token) {
1541 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1542
1543 final long origId = Binder.clearCallingIdentity();
1544
1545 synchronized (mGlobalLock) {
1546 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1547 if (r != null) {
1548 mStackSupervisor.activitySleptLocked(r);
1549 }
1550 }
1551
1552 Binder.restoreCallingIdentity(origId);
1553 }
1554
1555 @Override
1556 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1557 synchronized (mGlobalLock) {
1558 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1559 if (r == null) {
1560 return;
1561 }
1562 final long origId = Binder.clearCallingIdentity();
1563 try {
1564 r.setRequestedOrientation(requestedOrientation);
1565 } finally {
1566 Binder.restoreCallingIdentity(origId);
1567 }
1568 }
1569 }
1570
1571 @Override
1572 public int getRequestedOrientation(IBinder token) {
1573 synchronized (mGlobalLock) {
1574 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1575 if (r == null) {
1576 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1577 }
1578 return r.getRequestedOrientation();
1579 }
1580 }
1581
1582 @Override
1583 public void setImmersive(IBinder token, boolean immersive) {
1584 synchronized (mGlobalLock) {
1585 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1586 if (r == null) {
1587 throw new IllegalArgumentException();
1588 }
1589 r.immersive = immersive;
1590
1591 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001592 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001594 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001595 }
1596 }
1597 }
1598
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001599 void applyUpdateLockStateLocked(ActivityRecord r) {
1600 // Modifications to the UpdateLock state are done on our handler, outside
1601 // the activity manager's locks. The new state is determined based on the
1602 // state *now* of the relevant activity record. The object is passed to
1603 // the handler solely for logging detail, not to be consulted/modified.
1604 final boolean nextState = r != null && r.immersive;
1605 mH.post(() -> {
1606 if (mUpdateLock.isHeld() != nextState) {
1607 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1608 "Applying new update lock state '" + nextState + "' for " + r);
1609 if (nextState) {
1610 mUpdateLock.acquire();
1611 } else {
1612 mUpdateLock.release();
1613 }
1614 }
1615 });
1616 }
1617
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 @Override
1619 public boolean isImmersive(IBinder token) {
1620 synchronized (mGlobalLock) {
1621 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1622 if (r == null) {
1623 throw new IllegalArgumentException();
1624 }
1625 return r.immersive;
1626 }
1627 }
1628
1629 @Override
1630 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001631 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001632 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001633 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001634 return (r != null) ? r.immersive : false;
1635 }
1636 }
1637
1638 @Override
1639 public void overridePendingTransition(IBinder token, String packageName,
1640 int enterAnim, int exitAnim) {
1641 synchronized (mGlobalLock) {
1642 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1643 if (self == null) {
1644 return;
1645 }
1646
1647 final long origId = Binder.clearCallingIdentity();
1648
1649 if (self.isState(
1650 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
lumark588a3e82018-07-20 18:53:54 +08001651 self.getDisplay().getWindowContainerController().overridePendingAppTransition(
1652 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001653 }
1654
1655 Binder.restoreCallingIdentity(origId);
1656 }
1657 }
1658
1659 @Override
1660 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001661 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001662 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001663 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001664 if (r == null) {
1665 return ActivityManager.COMPAT_MODE_UNKNOWN;
1666 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001667 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001668 }
1669 }
1670
1671 @Override
1672 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001673 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001674 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001675 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001676 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001677 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001678 if (r == null) {
1679 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1680 return;
1681 }
1682 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001683 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001684 }
1685 }
1686
1687 @Override
1688 public int getLaunchedFromUid(IBinder activityToken) {
1689 ActivityRecord srec;
1690 synchronized (mGlobalLock) {
1691 srec = ActivityRecord.forTokenLocked(activityToken);
1692 }
1693 if (srec == null) {
1694 return -1;
1695 }
1696 return srec.launchedFromUid;
1697 }
1698
1699 @Override
1700 public String getLaunchedFromPackage(IBinder activityToken) {
1701 ActivityRecord srec;
1702 synchronized (mGlobalLock) {
1703 srec = ActivityRecord.forTokenLocked(activityToken);
1704 }
1705 if (srec == null) {
1706 return null;
1707 }
1708 return srec.launchedFromPackage;
1709 }
1710
1711 @Override
1712 public boolean convertFromTranslucent(IBinder token) {
1713 final long origId = Binder.clearCallingIdentity();
1714 try {
1715 synchronized (mGlobalLock) {
1716 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1717 if (r == null) {
1718 return false;
1719 }
1720 final boolean translucentChanged = r.changeWindowTranslucency(true);
1721 if (translucentChanged) {
1722 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1723 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001724 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001725 return translucentChanged;
1726 }
1727 } finally {
1728 Binder.restoreCallingIdentity(origId);
1729 }
1730 }
1731
1732 @Override
1733 public boolean convertToTranslucent(IBinder token, Bundle options) {
1734 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1735 final long origId = Binder.clearCallingIdentity();
1736 try {
1737 synchronized (mGlobalLock) {
1738 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1739 if (r == null) {
1740 return false;
1741 }
1742 final TaskRecord task = r.getTask();
1743 int index = task.mActivities.lastIndexOf(r);
1744 if (index > 0) {
1745 ActivityRecord under = task.mActivities.get(index - 1);
1746 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1747 }
1748 final boolean translucentChanged = r.changeWindowTranslucency(false);
1749 if (translucentChanged) {
1750 r.getStack().convertActivityToTranslucent(r);
1751 }
1752 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001753 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001754 return translucentChanged;
1755 }
1756 } finally {
1757 Binder.restoreCallingIdentity(origId);
1758 }
1759 }
1760
1761 @Override
1762 public void notifyActivityDrawn(IBinder token) {
1763 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1764 synchronized (mGlobalLock) {
1765 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1766 if (r != null) {
1767 r.getStack().notifyActivityDrawnLocked(r);
1768 }
1769 }
1770 }
1771
1772 @Override
1773 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1774 synchronized (mGlobalLock) {
1775 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1776 if (r == null) {
1777 return;
1778 }
1779 r.reportFullyDrawnLocked(restoredFromBundle);
1780 }
1781 }
1782
1783 @Override
1784 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1785 synchronized (mGlobalLock) {
1786 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1787 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1788 return stack.mDisplayId;
1789 }
1790 return DEFAULT_DISPLAY;
1791 }
1792 }
1793
1794 @Override
1795 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001796 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001797 long ident = Binder.clearCallingIdentity();
1798 try {
1799 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001800 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 if (focusedStack != null) {
1802 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1803 }
1804 return null;
1805 }
1806 } finally {
1807 Binder.restoreCallingIdentity(ident);
1808 }
1809 }
1810
1811 @Override
1812 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001813 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1815 final long callingId = Binder.clearCallingIdentity();
1816 try {
1817 synchronized (mGlobalLock) {
1818 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1819 if (stack == null) {
1820 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1821 return;
1822 }
1823 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001824 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001825 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001826 }
1827 }
1828 } finally {
1829 Binder.restoreCallingIdentity(callingId);
1830 }
1831 }
1832
1833 @Override
1834 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001835 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001836 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1837 final long callingId = Binder.clearCallingIdentity();
1838 try {
1839 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001840 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1841 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001842 if (task == null) {
1843 return;
1844 }
1845 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001846 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001847 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001848 }
1849 }
1850 } finally {
1851 Binder.restoreCallingIdentity(callingId);
1852 }
1853 }
1854
1855 @Override
1856 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001857 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001858 synchronized (mGlobalLock) {
1859 final long ident = Binder.clearCallingIdentity();
1860 try {
1861 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1862 "remove-task");
1863 } finally {
1864 Binder.restoreCallingIdentity(ident);
1865 }
1866 }
1867 }
1868
1869 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001870 public void removeAllVisibleRecentTasks() {
1871 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1872 synchronized (mGlobalLock) {
1873 final long ident = Binder.clearCallingIdentity();
1874 try {
1875 getRecentTasks().removeAllVisibleTasks();
1876 } finally {
1877 Binder.restoreCallingIdentity(ident);
1878 }
1879 }
1880 }
1881
1882 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001883 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1884 synchronized (mGlobalLock) {
1885 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1886 if (srec != null) {
1887 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1888 }
1889 }
1890 return false;
1891 }
1892
1893 @Override
1894 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1895 Intent resultData) {
1896
1897 synchronized (mGlobalLock) {
1898 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1899 if (r != null) {
1900 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1901 }
1902 return false;
1903 }
1904 }
1905
1906 /**
1907 * Attempts to move a task backwards in z-order (the order of activities within the task is
1908 * unchanged).
1909 *
1910 * There are several possible results of this call:
1911 * - if the task is locked, then we will show the lock toast
1912 * - if there is a task behind the provided task, then that task is made visible and resumed as
1913 * this task is moved to the back
1914 * - otherwise, if there are no other tasks in the stack:
1915 * - if this task is in the pinned stack, then we remove the stack completely, which will
1916 * have the effect of moving the task to the top or bottom of the fullscreen stack
1917 * (depending on whether it is visible)
1918 * - otherwise, we simply return home and hide this task
1919 *
1920 * @param token A reference to the activity we wish to move
1921 * @param nonRoot If false then this only works if the activity is the root
1922 * of a task; if true it will work for any activity in a task.
1923 * @return Returns true if the move completed, false if not.
1924 */
1925 @Override
1926 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001927 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 synchronized (mGlobalLock) {
1929 final long origId = Binder.clearCallingIdentity();
1930 try {
1931 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
1932 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1933 if (task != null) {
1934 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
1935 }
1936 } finally {
1937 Binder.restoreCallingIdentity(origId);
1938 }
1939 }
1940 return false;
1941 }
1942
1943 @Override
1944 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001945 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001946 long ident = Binder.clearCallingIdentity();
1947 Rect rect = new Rect();
1948 try {
1949 synchronized (mGlobalLock) {
1950 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1951 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1952 if (task == null) {
1953 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
1954 return rect;
1955 }
1956 if (task.getStack() != null) {
1957 // Return the bounds from window manager since it will be adjusted for various
1958 // things like the presense of a docked stack for tasks that aren't resizeable.
1959 task.getWindowContainerBounds(rect);
1960 } else {
1961 // Task isn't in window manager yet since it isn't associated with a stack.
1962 // Return the persist value from activity manager
1963 if (!task.matchParentBounds()) {
1964 rect.set(task.getBounds());
1965 } else if (task.mLastNonFullscreenBounds != null) {
1966 rect.set(task.mLastNonFullscreenBounds);
1967 }
1968 }
1969 }
1970 } finally {
1971 Binder.restoreCallingIdentity(ident);
1972 }
1973 return rect;
1974 }
1975
1976 @Override
1977 public ActivityManager.TaskDescription getTaskDescription(int id) {
1978 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001979 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
1981 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
1982 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1983 if (tr != null) {
1984 return tr.lastTaskDescription;
1985 }
1986 }
1987 return null;
1988 }
1989
1990 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001991 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
1992 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
1993 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
1994 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
1995 return;
1996 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001997 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001998 synchronized (mGlobalLock) {
1999 final long ident = Binder.clearCallingIdentity();
2000 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002001 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2002 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002003 if (task == null) {
2004 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2005 return;
2006 }
2007
2008 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2009 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2010
2011 if (!task.isActivityTypeStandardOrUndefined()) {
2012 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2013 + " non-standard task " + taskId + " to windowing mode="
2014 + windowingMode);
2015 }
2016
2017 final ActivityStack stack = task.getStack();
2018 if (toTop) {
2019 stack.moveToFront("setTaskWindowingMode", task);
2020 }
2021 stack.setWindowingMode(windowingMode);
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
2025 }
2026 }
2027
2028 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002030 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002031 ActivityRecord r = getCallingRecordLocked(token);
2032 return r != null ? r.info.packageName : null;
2033 }
2034 }
2035
2036 @Override
2037 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002038 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002039 ActivityRecord r = getCallingRecordLocked(token);
2040 return r != null ? r.intent.getComponent() : null;
2041 }
2042 }
2043
2044 private ActivityRecord getCallingRecordLocked(IBinder token) {
2045 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2046 if (r == null) {
2047 return null;
2048 }
2049 return r.resultTo;
2050 }
2051
2052 @Override
2053 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002054 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055
2056 synchronized (mGlobalLock) {
2057 final long origId = Binder.clearCallingIdentity();
2058 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002059 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 } finally {
2061 Binder.restoreCallingIdentity(origId);
2062 }
2063 }
2064 }
2065
2066 /**
2067 * TODO: Add mController hook
2068 */
2069 @Override
2070 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002071 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072
2073 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2074 synchronized (mGlobalLock) {
2075 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2076 false /* fromRecents */);
2077 }
2078 }
2079
2080 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2081 boolean fromRecents) {
2082
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002083 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002084 Binder.getCallingUid(), -1, -1, "Task to front")) {
2085 SafeActivityOptions.abort(options);
2086 return;
2087 }
2088 final long origId = Binder.clearCallingIdentity();
2089 try {
2090 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2091 if (task == null) {
2092 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002093 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 return;
2095 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002096 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002097 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002098 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 return;
2100 }
2101 ActivityOptions realOptions = options != null
2102 ? options.getOptions(mStackSupervisor)
2103 : null;
2104 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2105 false /* forceNonResizable */);
2106
2107 final ActivityRecord topActivity = task.getTopActivity();
2108 if (topActivity != null) {
2109
2110 // We are reshowing a task, use a starting window to hide the initial draw delay
2111 // so the transition can start earlier.
2112 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2113 true /* taskSwitch */, fromRecents);
2114 }
2115 } finally {
2116 Binder.restoreCallingIdentity(origId);
2117 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002118 }
2119
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002120 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2121 int callingPid, int callingUid, String name) {
2122 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2123 return true;
2124 }
2125
2126 if (getRecentTasks().isCallerRecents(sourceUid)) {
2127 return true;
2128 }
2129
2130 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2131 if (perm == PackageManager.PERMISSION_GRANTED) {
2132 return true;
2133 }
2134 if (checkAllowAppSwitchUid(sourceUid)) {
2135 return true;
2136 }
2137
2138 // If the actual IPC caller is different from the logical source, then
2139 // also see if they are allowed to control app switches.
2140 if (callingUid != -1 && callingUid != sourceUid) {
2141 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2142 if (perm == PackageManager.PERMISSION_GRANTED) {
2143 return true;
2144 }
2145 if (checkAllowAppSwitchUid(callingUid)) {
2146 return true;
2147 }
2148 }
2149
2150 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2151 return false;
2152 }
2153
2154 private boolean checkAllowAppSwitchUid(int uid) {
2155 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2156 if (types != null) {
2157 for (int i = types.size() - 1; i >= 0; i--) {
2158 if (types.valueAt(i).intValue() == uid) {
2159 return true;
2160 }
2161 }
2162 }
2163 return false;
2164 }
2165
2166 @Override
2167 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2168 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2169 "setActivityController()");
2170 synchronized (mGlobalLock) {
2171 mController = controller;
2172 mControllerIsAMonkey = imAMonkey;
2173 Watchdog.getInstance().setActivityController(controller);
2174 }
2175 }
2176
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002177 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002178 synchronized (mGlobalLock) {
2179 return mController != null && mControllerIsAMonkey;
2180 }
2181 }
2182
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002183 @Override
2184 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2185 synchronized (mGlobalLock) {
2186 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2187 }
2188 }
2189
2190 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002191 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2192 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2193 }
2194
2195 @Override
2196 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2197 @WindowConfiguration.ActivityType int ignoreActivityType,
2198 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2199 final int callingUid = Binder.getCallingUid();
2200 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2201
2202 synchronized (mGlobalLock) {
2203 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2204
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002205 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002206 callingUid);
2207 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2208 ignoreWindowingMode, callingUid, allowed);
2209 }
2210
2211 return list;
2212 }
2213
2214 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002215 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2216 synchronized (mGlobalLock) {
2217 final long origId = Binder.clearCallingIdentity();
2218 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2219 if (r != null) {
2220 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2221 }
2222 Binder.restoreCallingIdentity(origId);
2223 }
2224 }
2225
2226 @Override
2227 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002228 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002229 ActivityStack stack = ActivityRecord.getStackLocked(token);
2230 if (stack != null) {
2231 return stack.willActivityBeVisibleLocked(token);
2232 }
2233 return false;
2234 }
2235 }
2236
2237 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002238 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002239 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002240 synchronized (mGlobalLock) {
2241 final long ident = Binder.clearCallingIdentity();
2242 try {
2243 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2244 if (task == null) {
2245 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2246 return;
2247 }
2248
2249 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2250 + " to stackId=" + stackId + " toTop=" + toTop);
2251
2252 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2253 if (stack == null) {
2254 throw new IllegalStateException(
2255 "moveTaskToStack: No stack for stackId=" + stackId);
2256 }
2257 if (!stack.isActivityTypeStandardOrUndefined()) {
2258 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2259 + taskId + " to stack " + stackId);
2260 }
2261 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002262 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002263 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2264 }
2265 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2266 "moveTaskToStack");
2267 } finally {
2268 Binder.restoreCallingIdentity(ident);
2269 }
2270 }
2271 }
2272
2273 @Override
2274 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2275 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002276 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002277
2278 final long ident = Binder.clearCallingIdentity();
2279 try {
2280 synchronized (mGlobalLock) {
2281 if (animate) {
2282 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2283 if (stack == null) {
2284 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2285 return;
2286 }
2287 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2288 throw new IllegalArgumentException("Stack: " + stackId
2289 + " doesn't support animated resize.");
2290 }
2291 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2292 animationDuration, false /* fromFullscreen */);
2293 } else {
2294 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2295 if (stack == null) {
2296 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2297 return;
2298 }
2299 mStackSupervisor.resizeStackLocked(stack, destBounds,
2300 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2301 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2302 }
2303 }
2304 } finally {
2305 Binder.restoreCallingIdentity(ident);
2306 }
2307 }
2308
2309 /**
2310 * Moves the specified task to the primary-split-screen stack.
2311 *
2312 * @param taskId Id of task to move.
2313 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2314 * exist already. See
2315 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2316 * and
2317 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2318 * @param toTop If the task and stack should be moved to the top.
2319 * @param animate Whether we should play an animation for the moving the task.
2320 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2321 * stack. Pass {@code null} to use default bounds.
2322 * @param showRecents If the recents activity should be shown on the other side of the task
2323 * going into split-screen mode.
2324 */
2325 @Override
2326 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2327 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002328 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002329 "setTaskWindowingModeSplitScreenPrimary()");
2330 synchronized (mGlobalLock) {
2331 final long ident = Binder.clearCallingIdentity();
2332 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002333 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2334 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002335 if (task == null) {
2336 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2337 return false;
2338 }
2339 if (DEBUG_STACK) Slog.d(TAG_STACK,
2340 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2341 + " to createMode=" + createMode + " toTop=" + toTop);
2342 if (!task.isActivityTypeStandardOrUndefined()) {
2343 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2344 + " non-standard task " + taskId + " to split-screen windowing mode");
2345 }
2346
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002347 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002348 final int windowingMode = task.getWindowingMode();
2349 final ActivityStack stack = task.getStack();
2350 if (toTop) {
2351 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2352 }
2353 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2354 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2355 return windowingMode != task.getWindowingMode();
2356 } finally {
2357 Binder.restoreCallingIdentity(ident);
2358 }
2359 }
2360 }
2361
2362 /**
2363 * Removes stacks in the input windowing modes from the system if they are of activity type
2364 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2365 */
2366 @Override
2367 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002368 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002369 "removeStacksInWindowingModes()");
2370
2371 synchronized (mGlobalLock) {
2372 final long ident = Binder.clearCallingIdentity();
2373 try {
2374 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2375 } finally {
2376 Binder.restoreCallingIdentity(ident);
2377 }
2378 }
2379 }
2380
2381 @Override
2382 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002383 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002384 "removeStacksWithActivityTypes()");
2385
2386 synchronized (mGlobalLock) {
2387 final long ident = Binder.clearCallingIdentity();
2388 try {
2389 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2390 } finally {
2391 Binder.restoreCallingIdentity(ident);
2392 }
2393 }
2394 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002395
2396 @Override
2397 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2398 int userId) {
2399 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002400 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2401 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002402 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002403 final boolean detailed = checkGetTasksPermission(
2404 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2405 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002406 == PackageManager.PERMISSION_GRANTED;
2407
2408 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002409 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002410 callingUid);
2411 }
2412 }
2413
2414 @Override
2415 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002416 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002417 long ident = Binder.clearCallingIdentity();
2418 try {
2419 synchronized (mGlobalLock) {
2420 return mStackSupervisor.getAllStackInfosLocked();
2421 }
2422 } finally {
2423 Binder.restoreCallingIdentity(ident);
2424 }
2425 }
2426
2427 @Override
2428 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002429 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002430 long ident = Binder.clearCallingIdentity();
2431 try {
2432 synchronized (mGlobalLock) {
2433 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2434 }
2435 } finally {
2436 Binder.restoreCallingIdentity(ident);
2437 }
2438 }
2439
2440 @Override
2441 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002442 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002443 final long callingUid = Binder.getCallingUid();
2444 final long origId = Binder.clearCallingIdentity();
2445 try {
2446 synchronized (mGlobalLock) {
2447 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002448 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002449 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2450 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2451 }
2452 } finally {
2453 Binder.restoreCallingIdentity(origId);
2454 }
2455 }
2456
2457 @Override
2458 public void startLockTaskModeByToken(IBinder token) {
2459 synchronized (mGlobalLock) {
2460 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2461 if (r == null) {
2462 return;
2463 }
2464 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2465 }
2466 }
2467
2468 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002469 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002470 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002471 // This makes inner call to look as if it was initiated by system.
2472 long ident = Binder.clearCallingIdentity();
2473 try {
2474 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002475 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2476 MATCH_TASK_IN_STACKS_ONLY);
2477 if (task == null) {
2478 return;
2479 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002480
2481 // When starting lock task mode the stack must be in front and focused
2482 task.getStack().moveToFront("startSystemLockTaskMode");
2483 startLockTaskModeLocked(task, true /* isSystemCaller */);
2484 }
2485 } finally {
2486 Binder.restoreCallingIdentity(ident);
2487 }
2488 }
2489
2490 @Override
2491 public void stopLockTaskModeByToken(IBinder token) {
2492 synchronized (mGlobalLock) {
2493 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2494 if (r == null) {
2495 return;
2496 }
2497 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2498 }
2499 }
2500
2501 /**
2502 * This API should be called by SystemUI only when user perform certain action to dismiss
2503 * lock task mode. We should only dismiss pinned lock task mode in this case.
2504 */
2505 @Override
2506 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002507 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002508 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2509 }
2510
2511 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2512 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2513 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2514 return;
2515 }
2516
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002517 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002518 if (stack == null || task != stack.topTask()) {
2519 throw new IllegalArgumentException("Invalid task, not in foreground");
2520 }
2521
2522 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2523 // system or a specific app.
2524 // * System-initiated requests will only start the pinned mode (screen pinning)
2525 // * App-initiated requests
2526 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2527 // - will start the pinned mode, otherwise
2528 final int callingUid = Binder.getCallingUid();
2529 long ident = Binder.clearCallingIdentity();
2530 try {
2531 // When a task is locked, dismiss the pinned stack if it exists
2532 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2533
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002534 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535 } finally {
2536 Binder.restoreCallingIdentity(ident);
2537 }
2538 }
2539
2540 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2541 final int callingUid = Binder.getCallingUid();
2542 long ident = Binder.clearCallingIdentity();
2543 try {
2544 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002545 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 }
2547 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2548 // task and jumping straight into a call in the case of emergency call back.
2549 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2550 if (tm != null) {
2551 tm.showInCallScreen(false);
2552 }
2553 } finally {
2554 Binder.restoreCallingIdentity(ident);
2555 }
2556 }
2557
2558 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002559 public void updateLockTaskPackages(int userId, String[] packages) {
2560 final int callingUid = Binder.getCallingUid();
2561 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2562 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2563 "updateLockTaskPackages()");
2564 }
2565 synchronized (this) {
2566 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2567 + Arrays.toString(packages));
2568 getLockTaskController().updateLockTaskPackages(userId, packages);
2569 }
2570 }
2571
2572 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002573 public boolean isInLockTaskMode() {
2574 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2575 }
2576
2577 @Override
2578 public int getLockTaskModeState() {
2579 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002580 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002581 }
2582 }
2583
2584 @Override
2585 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2586 synchronized (mGlobalLock) {
2587 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2588 if (r != null) {
2589 r.setTaskDescription(td);
2590 final TaskRecord task = r.getTask();
2591 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002592 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002593 }
2594 }
2595 }
2596
2597 @Override
2598 public Bundle getActivityOptions(IBinder token) {
2599 final long origId = Binder.clearCallingIdentity();
2600 try {
2601 synchronized (mGlobalLock) {
2602 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2603 if (r != null) {
2604 final ActivityOptions activityOptions = r.takeOptionsLocked();
2605 return activityOptions == null ? null : activityOptions.toBundle();
2606 }
2607 return null;
2608 }
2609 } finally {
2610 Binder.restoreCallingIdentity(origId);
2611 }
2612 }
2613
2614 @Override
2615 public List<IBinder> getAppTasks(String callingPackage) {
2616 int callingUid = Binder.getCallingUid();
2617 long ident = Binder.clearCallingIdentity();
2618 try {
2619 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002620 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002621 }
2622 } finally {
2623 Binder.restoreCallingIdentity(ident);
2624 }
2625 }
2626
2627 @Override
2628 public void finishVoiceTask(IVoiceInteractionSession session) {
2629 synchronized (mGlobalLock) {
2630 final long origId = Binder.clearCallingIdentity();
2631 try {
2632 // TODO: VI Consider treating local voice interactions and voice tasks
2633 // differently here
2634 mStackSupervisor.finishVoiceTask(session);
2635 } finally {
2636 Binder.restoreCallingIdentity(origId);
2637 }
2638 }
2639
2640 }
2641
2642 @Override
2643 public boolean isTopOfTask(IBinder token) {
2644 synchronized (mGlobalLock) {
2645 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002646 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002647 }
2648 }
2649
2650 @Override
2651 public void notifyLaunchTaskBehindComplete(IBinder token) {
2652 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2653 }
2654
2655 @Override
2656 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002657 mH.post(() -> {
2658 synchronized (mGlobalLock) {
2659 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002660 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002661 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002662 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002663 } catch (RemoteException e) {
2664 }
2665 }
2666 }
2667
2668 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002669 }
2670
2671 /** Called from an app when assist data is ready. */
2672 @Override
2673 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2674 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002675 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002676 synchronized (pae) {
2677 pae.result = extras;
2678 pae.structure = structure;
2679 pae.content = content;
2680 if (referrer != null) {
2681 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2682 }
2683 if (structure != null) {
2684 structure.setHomeActivity(pae.isHome);
2685 }
2686 pae.haveResult = true;
2687 pae.notifyAll();
2688 if (pae.intent == null && pae.receiver == null) {
2689 // Caller is just waiting for the result.
2690 return;
2691 }
2692 }
2693 // We are now ready to launch the assist activity.
2694 IAssistDataReceiver sendReceiver = null;
2695 Bundle sendBundle = null;
2696 synchronized (mGlobalLock) {
2697 buildAssistBundleLocked(pae, extras);
2698 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002699 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002700 if (!exists) {
2701 // Timed out.
2702 return;
2703 }
2704
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002705 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002706 // Caller wants result sent back to them.
2707 sendBundle = new Bundle();
2708 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2709 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2710 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2711 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2712 }
2713 }
2714 if (sendReceiver != null) {
2715 try {
2716 sendReceiver.onHandleAssistData(sendBundle);
2717 } catch (RemoteException e) {
2718 }
2719 return;
2720 }
2721
2722 final long ident = Binder.clearCallingIdentity();
2723 try {
2724 if (TextUtils.equals(pae.intent.getAction(),
2725 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2726 pae.intent.putExtras(pae.extras);
2727 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2728 } else {
2729 pae.intent.replaceExtras(pae.extras);
2730 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2731 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2732 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002733 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002734
2735 try {
2736 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2737 } catch (ActivityNotFoundException e) {
2738 Slog.w(TAG, "No activity to handle assist action.", e);
2739 }
2740 }
2741 } finally {
2742 Binder.restoreCallingIdentity(ident);
2743 }
2744 }
2745
2746 @Override
2747 public int addAppTask(IBinder activityToken, Intent intent,
2748 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2749 final int callingUid = Binder.getCallingUid();
2750 final long callingIdent = Binder.clearCallingIdentity();
2751
2752 try {
2753 synchronized (mGlobalLock) {
2754 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2755 if (r == null) {
2756 throw new IllegalArgumentException("Activity does not exist; token="
2757 + activityToken);
2758 }
2759 ComponentName comp = intent.getComponent();
2760 if (comp == null) {
2761 throw new IllegalArgumentException("Intent " + intent
2762 + " must specify explicit component");
2763 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002764 if (thumbnail.getWidth() != mThumbnailWidth
2765 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002766 throw new IllegalArgumentException("Bad thumbnail size: got "
2767 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002768 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002769 }
2770 if (intent.getSelector() != null) {
2771 intent.setSelector(null);
2772 }
2773 if (intent.getSourceBounds() != null) {
2774 intent.setSourceBounds(null);
2775 }
2776 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2777 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2778 // The caller has added this as an auto-remove task... that makes no
2779 // sense, so turn off auto-remove.
2780 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2781 }
2782 }
2783 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2784 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2785 if (ainfo.applicationInfo.uid != callingUid) {
2786 throw new SecurityException(
2787 "Can't add task for another application: target uid="
2788 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2789 }
2790
2791 final ActivityStack stack = r.getStack();
2792 final TaskRecord task = stack.createTaskRecord(
2793 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2794 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002795 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002796 // The app has too many tasks already and we can't add any more
2797 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2798 return INVALID_TASK_ID;
2799 }
2800 task.lastTaskDescription.copyFrom(description);
2801
2802 // TODO: Send the thumbnail to WM to store it.
2803
2804 return task.taskId;
2805 }
2806 } finally {
2807 Binder.restoreCallingIdentity(callingIdent);
2808 }
2809 }
2810
2811 @Override
2812 public Point getAppTaskThumbnailSize() {
2813 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002814 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 }
2816 }
2817
2818 @Override
2819 public void setTaskResizeable(int taskId, int resizeableMode) {
2820 synchronized (mGlobalLock) {
2821 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2822 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2823 if (task == null) {
2824 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2825 return;
2826 }
2827 task.setResizeMode(resizeableMode);
2828 }
2829 }
2830
2831 @Override
2832 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002833 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002834 long ident = Binder.clearCallingIdentity();
2835 try {
2836 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002837 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2838 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002839 if (task == null) {
2840 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2841 return;
2842 }
2843 // Place the task in the right stack if it isn't there already based on
2844 // the requested bounds.
2845 // The stack transition logic is:
2846 // - a null bounds on a freeform task moves that task to fullscreen
2847 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2848 // that task to freeform
2849 // - otherwise the task is not moved
2850 ActivityStack stack = task.getStack();
2851 if (!task.getWindowConfiguration().canResizeTask()) {
2852 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2853 }
2854 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2855 stack = stack.getDisplay().getOrCreateStack(
2856 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2857 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2858 stack = stack.getDisplay().getOrCreateStack(
2859 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2860 }
2861
2862 // Reparent the task to the right stack if necessary
2863 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2864 if (stack != task.getStack()) {
2865 // Defer resume until the task is resized below
2866 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2867 DEFER_RESUME, "resizeTask");
2868 preserveWindow = false;
2869 }
2870
2871 // After reparenting (which only resizes the task to the stack bounds), resize the
2872 // task to the actual bounds provided
2873 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2874 }
2875 } finally {
2876 Binder.restoreCallingIdentity(ident);
2877 }
2878 }
2879
2880 @Override
2881 public boolean releaseActivityInstance(IBinder token) {
2882 synchronized (mGlobalLock) {
2883 final long origId = Binder.clearCallingIdentity();
2884 try {
2885 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2886 if (r == null) {
2887 return false;
2888 }
2889 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2890 } finally {
2891 Binder.restoreCallingIdentity(origId);
2892 }
2893 }
2894 }
2895
2896 @Override
2897 public void releaseSomeActivities(IApplicationThread appInt) {
2898 synchronized (mGlobalLock) {
2899 final long origId = Binder.clearCallingIdentity();
2900 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002901 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002902 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2903 } finally {
2904 Binder.restoreCallingIdentity(origId);
2905 }
2906 }
2907 }
2908
2909 @Override
2910 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002911 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002912 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002913 != PackageManager.PERMISSION_GRANTED) {
2914 throw new SecurityException("Requires permission "
2915 + android.Manifest.permission.DEVICE_POWER);
2916 }
2917
2918 synchronized (mGlobalLock) {
2919 long ident = Binder.clearCallingIdentity();
2920 if (mKeyguardShown != keyguardShowing) {
2921 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002922 final Message msg = PooledLambda.obtainMessage(
2923 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
2924 keyguardShowing);
2925 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 }
2927 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002928 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08002929 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002930 } finally {
2931 Binder.restoreCallingIdentity(ident);
2932 }
2933 }
2934
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002935 mH.post(() -> {
2936 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2937 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
2938 }
2939 });
2940 }
2941
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002942 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002943 mH.post(() -> {
2944 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2945 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
2946 }
2947 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002948 }
2949
2950 @Override
2951 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002952 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
2953 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954
2955 final File passedIconFile = new File(filePath);
2956 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
2957 passedIconFile.getName());
2958 if (!legitIconFile.getPath().equals(filePath)
2959 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
2960 throw new IllegalArgumentException("Bad file path: " + filePath
2961 + " passed for userId " + userId);
2962 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002963 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 }
2965
2966 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002967 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002968 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
2969 final ActivityOptions activityOptions = safeOptions != null
2970 ? safeOptions.getOptions(mStackSupervisor)
2971 : null;
2972 if (activityOptions == null
2973 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
2974 || activityOptions.getCustomInPlaceResId() == 0) {
2975 throw new IllegalArgumentException("Expected in-place ActivityOption " +
2976 "with valid animation");
2977 }
lumark588a3e82018-07-20 18:53:54 +08002978 // Get top display of front most application.
2979 final ActivityStack focusedStack = getTopDisplayFocusedStack();
2980 if (focusedStack != null) {
2981 final DisplayWindowController dwc =
2982 focusedStack.getDisplay().getWindowContainerController();
2983 dwc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
2984 dwc.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
2985 activityOptions.getCustomInPlaceResId());
2986 dwc.executeAppTransition();
2987 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002988 }
2989
2990 @Override
2991 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002992 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002993 synchronized (mGlobalLock) {
2994 final long ident = Binder.clearCallingIdentity();
2995 try {
2996 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2997 if (stack == null) {
2998 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
2999 return;
3000 }
3001 if (!stack.isActivityTypeStandardOrUndefined()) {
3002 throw new IllegalArgumentException(
3003 "Removing non-standard stack is not allowed.");
3004 }
3005 mStackSupervisor.removeStack(stack);
3006 } finally {
3007 Binder.restoreCallingIdentity(ident);
3008 }
3009 }
3010 }
3011
3012 @Override
3013 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003014 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003015
3016 synchronized (mGlobalLock) {
3017 final long ident = Binder.clearCallingIdentity();
3018 try {
3019 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3020 + " to displayId=" + displayId);
3021 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
3022 } finally {
3023 Binder.restoreCallingIdentity(ident);
3024 }
3025 }
3026 }
3027
3028 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003029 public void exitFreeformMode(IBinder token) {
3030 synchronized (mGlobalLock) {
3031 long ident = Binder.clearCallingIdentity();
3032 try {
3033 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3034 if (r == null) {
3035 throw new IllegalArgumentException(
3036 "exitFreeformMode: No activity record matching token=" + token);
3037 }
3038
3039 final ActivityStack stack = r.getStack();
3040 if (stack == null || !stack.inFreeformWindowingMode()) {
3041 throw new IllegalStateException(
3042 "exitFreeformMode: You can only go fullscreen from freeform.");
3043 }
3044
3045 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3046 } finally {
3047 Binder.restoreCallingIdentity(ident);
3048 }
3049 }
3050 }
3051
3052 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3053 @Override
3054 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003055 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003057 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003058 }
3059
3060 /** Unregister a task stack listener so that it stops receiving callbacks. */
3061 @Override
3062 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003063 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003064 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003065 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003066 }
3067
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003068 @Override
3069 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3070 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3071 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3072 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3073 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3074 }
3075
3076 @Override
3077 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3078 IBinder activityToken, int flags) {
3079 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3080 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3081 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3082 }
3083
3084 @Override
3085 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3086 Bundle args) {
3087 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3088 true /* focused */, true /* newSessionId */, userHandle, args,
3089 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3090 }
3091
3092 @Override
3093 public Bundle getAssistContextExtras(int requestType) {
3094 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3095 null, null, true /* focused */, true /* newSessionId */,
3096 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3097 if (pae == null) {
3098 return null;
3099 }
3100 synchronized (pae) {
3101 while (!pae.haveResult) {
3102 try {
3103 pae.wait();
3104 } catch (InterruptedException e) {
3105 }
3106 }
3107 }
3108 synchronized (mGlobalLock) {
3109 buildAssistBundleLocked(pae, pae.result);
3110 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003111 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 }
3113 return pae.extras;
3114 }
3115
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003116 /**
3117 * Binder IPC calls go through the public entry point.
3118 * This can be called with or without the global lock held.
3119 */
3120 private static int checkCallingPermission(String permission) {
3121 return checkPermission(
3122 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3123 }
3124
3125 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003126 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003127 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3128 mAmInternal.enforceCallingPermission(permission, func);
3129 }
3130 }
3131
3132 @VisibleForTesting
3133 int checkGetTasksPermission(String permission, int pid, int uid) {
3134 return checkPermission(permission, pid, uid);
3135 }
3136
3137 static int checkPermission(String permission, int pid, int uid) {
3138 if (permission == null) {
3139 return PackageManager.PERMISSION_DENIED;
3140 }
3141 return checkComponentPermission(permission, pid, uid, -1, true);
3142 }
3143
Wale Ogunwale214f3482018-10-04 11:00:47 -07003144 public static int checkComponentPermission(String permission, int pid, int uid,
3145 int owningUid, boolean exported) {
3146 return ActivityManagerService.checkComponentPermission(
3147 permission, pid, uid, owningUid, exported);
3148 }
3149
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003150 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3151 if (getRecentTasks().isCallerRecents(callingUid)) {
3152 // Always allow the recents component to get tasks
3153 return true;
3154 }
3155
3156 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3157 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3158 if (!allowed) {
3159 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3160 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3161 // Temporary compatibility: some existing apps on the system image may
3162 // still be requesting the old permission and not switched to the new
3163 // one; if so, we'll still allow them full access. This means we need
3164 // to see if they are holding the old permission and are a system app.
3165 try {
3166 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3167 allowed = true;
3168 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3169 + " is using old GET_TASKS but privileged; allowing");
3170 }
3171 } catch (RemoteException e) {
3172 }
3173 }
3174 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3175 + " does not hold REAL_GET_TASKS; limiting output");
3176 }
3177 return allowed;
3178 }
3179
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003180 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3181 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3182 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3183 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003184 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 "enqueueAssistContext()");
3186
3187 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003188 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003189 if (activity == null) {
3190 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3191 return null;
3192 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003193 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3195 return null;
3196 }
3197 if (focused) {
3198 if (activityToken != null) {
3199 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3200 if (activity != caller) {
3201 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3202 + " is not current top " + activity);
3203 return null;
3204 }
3205 }
3206 } else {
3207 activity = ActivityRecord.forTokenLocked(activityToken);
3208 if (activity == null) {
3209 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3210 + " couldn't be found");
3211 return null;
3212 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003213 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3215 return null;
3216 }
3217 }
3218
3219 PendingAssistExtras pae;
3220 Bundle extras = new Bundle();
3221 if (args != null) {
3222 extras.putAll(args);
3223 }
3224 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003225 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003226
3227 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3228 userHandle);
3229 pae.isHome = activity.isActivityTypeHome();
3230
3231 // Increment the sessionId if necessary
3232 if (newSessionId) {
3233 mViSessionId++;
3234 }
3235 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003236 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3237 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003238 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003239 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003240 } catch (RemoteException e) {
3241 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3242 return null;
3243 }
3244 return pae;
3245 }
3246 }
3247
3248 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3249 if (result != null) {
3250 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3251 }
3252 if (pae.hint != null) {
3253 pae.extras.putBoolean(pae.hint, true);
3254 }
3255 }
3256
3257 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3258 IAssistDataReceiver receiver;
3259 synchronized (mGlobalLock) {
3260 mPendingAssistExtras.remove(pae);
3261 receiver = pae.receiver;
3262 }
3263 if (receiver != null) {
3264 // Caller wants result sent back to them.
3265 Bundle sendBundle = new Bundle();
3266 // At least return the receiver extras
3267 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3268 try {
3269 pae.receiver.onHandleAssistData(sendBundle);
3270 } catch (RemoteException e) {
3271 }
3272 }
3273 }
3274
3275 public class PendingAssistExtras extends Binder implements Runnable {
3276 public final ActivityRecord activity;
3277 public boolean isHome;
3278 public final Bundle extras;
3279 public final Intent intent;
3280 public final String hint;
3281 public final IAssistDataReceiver receiver;
3282 public final int userHandle;
3283 public boolean haveResult = false;
3284 public Bundle result = null;
3285 public AssistStructure structure = null;
3286 public AssistContent content = null;
3287 public Bundle receiverExtras;
3288
3289 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3290 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3291 int _userHandle) {
3292 activity = _activity;
3293 extras = _extras;
3294 intent = _intent;
3295 hint = _hint;
3296 receiver = _receiver;
3297 receiverExtras = _receiverExtras;
3298 userHandle = _userHandle;
3299 }
3300
3301 @Override
3302 public void run() {
3303 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3304 synchronized (this) {
3305 haveResult = true;
3306 notifyAll();
3307 }
3308 pendingAssistExtrasTimedOut(this);
3309 }
3310 }
3311
3312 @Override
3313 public boolean isAssistDataAllowedOnCurrentActivity() {
3314 int userId;
3315 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003316 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003317 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3318 return false;
3319 }
3320
3321 final ActivityRecord activity = focusedStack.getTopActivity();
3322 if (activity == null) {
3323 return false;
3324 }
3325 userId = activity.userId;
3326 }
3327 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3328 }
3329
3330 @Override
3331 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3332 long ident = Binder.clearCallingIdentity();
3333 try {
3334 synchronized (mGlobalLock) {
3335 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003336 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003337 if (top != caller) {
3338 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3339 + " is not current top " + top);
3340 return false;
3341 }
3342 if (!top.nowVisible) {
3343 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3344 + " is not visible");
3345 return false;
3346 }
3347 }
3348 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3349 token);
3350 } finally {
3351 Binder.restoreCallingIdentity(ident);
3352 }
3353 }
3354
3355 @Override
3356 public boolean isRootVoiceInteraction(IBinder token) {
3357 synchronized (mGlobalLock) {
3358 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3359 if (r == null) {
3360 return false;
3361 }
3362 return r.rootVoiceInteraction;
3363 }
3364 }
3365
Wale Ogunwalef6733932018-06-27 05:14:34 -07003366 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3367 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3368 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3369 if (activityToCallback == null) return;
3370 activityToCallback.setVoiceSessionLocked(voiceSession);
3371
3372 // Inform the activity
3373 try {
3374 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3375 voiceInteractor);
3376 long token = Binder.clearCallingIdentity();
3377 try {
3378 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3379 } finally {
3380 Binder.restoreCallingIdentity(token);
3381 }
3382 // TODO: VI Should we cache the activity so that it's easier to find later
3383 // rather than scan through all the stacks and activities?
3384 } catch (RemoteException re) {
3385 activityToCallback.clearVoiceSessionLocked();
3386 // TODO: VI Should this terminate the voice session?
3387 }
3388 }
3389
3390 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3391 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3392 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3393 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3394 boolean wasRunningVoice = mRunningVoice != null;
3395 mRunningVoice = session;
3396 if (!wasRunningVoice) {
3397 mVoiceWakeLock.acquire();
3398 updateSleepIfNeededLocked();
3399 }
3400 }
3401 }
3402
3403 void finishRunningVoiceLocked() {
3404 if (mRunningVoice != null) {
3405 mRunningVoice = null;
3406 mVoiceWakeLock.release();
3407 updateSleepIfNeededLocked();
3408 }
3409 }
3410
3411 @Override
3412 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3413 synchronized (mGlobalLock) {
3414 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3415 if (keepAwake) {
3416 mVoiceWakeLock.acquire();
3417 } else {
3418 mVoiceWakeLock.release();
3419 }
3420 }
3421 }
3422 }
3423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003424 @Override
3425 public ComponentName getActivityClassForToken(IBinder token) {
3426 synchronized (mGlobalLock) {
3427 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3428 if (r == null) {
3429 return null;
3430 }
3431 return r.intent.getComponent();
3432 }
3433 }
3434
3435 @Override
3436 public String getPackageForToken(IBinder token) {
3437 synchronized (mGlobalLock) {
3438 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3439 if (r == null) {
3440 return null;
3441 }
3442 return r.packageName;
3443 }
3444 }
3445
3446 @Override
3447 public void showLockTaskEscapeMessage(IBinder token) {
3448 synchronized (mGlobalLock) {
3449 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3450 if (r == null) {
3451 return;
3452 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003453 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003454 }
3455 }
3456
3457 @Override
3458 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003459 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003460 final long token = Binder.clearCallingIdentity();
3461 try {
3462 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003463 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003464 }
3465 } finally {
3466 Binder.restoreCallingIdentity(token);
3467 }
3468 }
3469
3470 /**
3471 * Try to place task to provided position. The final position might be different depending on
3472 * current user and stacks state. The task will be moved to target stack if it's currently in
3473 * different stack.
3474 */
3475 @Override
3476 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003477 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003478 synchronized (mGlobalLock) {
3479 long ident = Binder.clearCallingIdentity();
3480 try {
3481 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3482 + taskId + " in stackId=" + stackId + " at position=" + position);
3483 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3484 if (task == null) {
3485 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3486 + taskId);
3487 }
3488
3489 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3490
3491 if (stack == null) {
3492 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3493 + stackId);
3494 }
3495 if (!stack.isActivityTypeStandardOrUndefined()) {
3496 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3497 + " the position of task " + taskId + " in/to non-standard stack");
3498 }
3499
3500 // TODO: Have the callers of this API call a separate reparent method if that is
3501 // what they intended to do vs. having this method also do reparenting.
3502 if (task.getStack() == stack) {
3503 // Change position in current stack.
3504 stack.positionChildAt(task, position);
3505 } else {
3506 // Reparent to new stack.
3507 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3508 !DEFER_RESUME, "positionTaskInStack");
3509 }
3510 } finally {
3511 Binder.restoreCallingIdentity(ident);
3512 }
3513 }
3514 }
3515
3516 @Override
3517 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3518 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3519 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3520 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3521 synchronized (mGlobalLock) {
3522 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3523 if (record == null) {
3524 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3525 + "found for: " + token);
3526 }
3527 record.setSizeConfigurations(horizontalSizeConfiguration,
3528 verticalSizeConfigurations, smallestSizeConfigurations);
3529 }
3530 }
3531
3532 /**
3533 * Dismisses split-screen multi-window mode.
3534 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3535 */
3536 @Override
3537 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003538 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003539 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3540 final long ident = Binder.clearCallingIdentity();
3541 try {
3542 synchronized (mGlobalLock) {
3543 final ActivityStack stack =
3544 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3545 if (stack == null) {
3546 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3547 return;
3548 }
3549
3550 if (toTop) {
3551 // Caller wants the current split-screen primary stack to be the top stack after
3552 // it goes fullscreen, so move it to the front.
3553 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003554 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003555 // In this case the current split-screen primary stack shouldn't be the top
3556 // stack after it goes fullscreen, but it current has focus, so we move the
3557 // focus to the top-most split-screen secondary stack next to it.
3558 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3559 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3560 if (otherStack != null) {
3561 otherStack.moveToFront("dismissSplitScreenMode_other");
3562 }
3563 }
3564
Evan Rosky10475742018-09-05 19:02:48 -07003565 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 }
3567 } finally {
3568 Binder.restoreCallingIdentity(ident);
3569 }
3570 }
3571
3572 /**
3573 * Dismisses Pip
3574 * @param animate True if the dismissal should be animated.
3575 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3576 * default animation duration should be used.
3577 */
3578 @Override
3579 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003580 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003581 final long ident = Binder.clearCallingIdentity();
3582 try {
3583 synchronized (mGlobalLock) {
3584 final PinnedActivityStack stack =
3585 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3586 if (stack == null) {
3587 Slog.w(TAG, "dismissPip: pinned stack not found.");
3588 return;
3589 }
3590 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3591 throw new IllegalArgumentException("Stack: " + stack
3592 + " doesn't support animated resize.");
3593 }
3594 if (animate) {
3595 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3596 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3597 } else {
3598 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3599 }
3600 }
3601 } finally {
3602 Binder.restoreCallingIdentity(ident);
3603 }
3604 }
3605
3606 @Override
3607 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003608 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 synchronized (mGlobalLock) {
3610 mSuppressResizeConfigChanges = suppress;
3611 }
3612 }
3613
3614 /**
3615 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3616 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3617 * activity and clearing the task at the same time.
3618 */
3619 @Override
3620 // TODO: API should just be about changing windowing modes...
3621 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003622 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003623 "moveTasksToFullscreenStack()");
3624 synchronized (mGlobalLock) {
3625 final long origId = Binder.clearCallingIdentity();
3626 try {
3627 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3628 if (stack != null){
3629 if (!stack.isActivityTypeStandardOrUndefined()) {
3630 throw new IllegalArgumentException(
3631 "You can't move tasks from non-standard stacks.");
3632 }
3633 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3634 }
3635 } finally {
3636 Binder.restoreCallingIdentity(origId);
3637 }
3638 }
3639 }
3640
3641 /**
3642 * Moves the top activity in the input stackId to the pinned stack.
3643 *
3644 * @param stackId Id of stack to move the top activity to pinned stack.
3645 * @param bounds Bounds to use for pinned stack.
3646 *
3647 * @return True if the top activity of the input stack was successfully moved to the pinned
3648 * stack.
3649 */
3650 @Override
3651 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003652 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003653 "moveTopActivityToPinnedStack()");
3654 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003655 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003656 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3657 + "Device doesn't support picture-in-picture mode");
3658 }
3659
3660 long ident = Binder.clearCallingIdentity();
3661 try {
3662 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3663 } finally {
3664 Binder.restoreCallingIdentity(ident);
3665 }
3666 }
3667 }
3668
3669 @Override
3670 public boolean isInMultiWindowMode(IBinder token) {
3671 final long origId = Binder.clearCallingIdentity();
3672 try {
3673 synchronized (mGlobalLock) {
3674 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3675 if (r == null) {
3676 return false;
3677 }
3678 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3679 return r.inMultiWindowMode();
3680 }
3681 } finally {
3682 Binder.restoreCallingIdentity(origId);
3683 }
3684 }
3685
3686 @Override
3687 public boolean isInPictureInPictureMode(IBinder token) {
3688 final long origId = Binder.clearCallingIdentity();
3689 try {
3690 synchronized (mGlobalLock) {
3691 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3692 }
3693 } finally {
3694 Binder.restoreCallingIdentity(origId);
3695 }
3696 }
3697
3698 private boolean isInPictureInPictureMode(ActivityRecord r) {
3699 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3700 || r.getStack().isInStackLocked(r) == null) {
3701 return false;
3702 }
3703
3704 // If we are animating to fullscreen then we have already dispatched the PIP mode
3705 // changed, so we should reflect that check here as well.
3706 final PinnedActivityStack stack = r.getStack();
3707 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3708 return !windowController.isAnimatingBoundsToFullscreen();
3709 }
3710
3711 @Override
3712 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3713 final long origId = Binder.clearCallingIdentity();
3714 try {
3715 synchronized (mGlobalLock) {
3716 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3717 "enterPictureInPictureMode", token, params);
3718
3719 // If the activity is already in picture in picture mode, then just return early
3720 if (isInPictureInPictureMode(r)) {
3721 return true;
3722 }
3723
3724 // Activity supports picture-in-picture, now check that we can enter PiP at this
3725 // point, if it is
3726 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3727 false /* beforeStopping */)) {
3728 return false;
3729 }
3730
3731 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003732 synchronized (mGlobalLock) {
3733 // Only update the saved args from the args that are set
3734 r.pictureInPictureArgs.copyOnlySet(params);
3735 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3736 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3737 // Adjust the source bounds by the insets for the transition down
3738 final Rect sourceBounds = new Rect(
3739 r.pictureInPictureArgs.getSourceRectHint());
3740 mStackSupervisor.moveActivityToPinnedStackLocked(
3741 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3742 final PinnedActivityStack stack = r.getStack();
3743 stack.setPictureInPictureAspectRatio(aspectRatio);
3744 stack.setPictureInPictureActions(actions);
3745 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3746 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3747 logPictureInPictureArgs(params);
3748 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003749 };
3750
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003751 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003752 // If the keyguard is showing or occluded, then try and dismiss it before
3753 // entering picture-in-picture (this will prompt the user to authenticate if the
3754 // device is currently locked).
3755 dismissKeyguard(token, new KeyguardDismissCallback() {
3756 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003757 public void onDismissSucceeded() {
3758 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003759 }
3760 }, null /* message */);
3761 } else {
3762 // Enter picture in picture immediately otherwise
3763 enterPipRunnable.run();
3764 }
3765 return true;
3766 }
3767 } finally {
3768 Binder.restoreCallingIdentity(origId);
3769 }
3770 }
3771
3772 @Override
3773 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3774 final long origId = Binder.clearCallingIdentity();
3775 try {
3776 synchronized (mGlobalLock) {
3777 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3778 "setPictureInPictureParams", token, params);
3779
3780 // Only update the saved args from the args that are set
3781 r.pictureInPictureArgs.copyOnlySet(params);
3782 if (r.inPinnedWindowingMode()) {
3783 // If the activity is already in picture-in-picture, update the pinned stack now
3784 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3785 // be used the next time the activity enters PiP
3786 final PinnedActivityStack stack = r.getStack();
3787 if (!stack.isAnimatingBoundsToFullscreen()) {
3788 stack.setPictureInPictureAspectRatio(
3789 r.pictureInPictureArgs.getAspectRatio());
3790 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3791 }
3792 }
3793 logPictureInPictureArgs(params);
3794 }
3795 } finally {
3796 Binder.restoreCallingIdentity(origId);
3797 }
3798 }
3799
3800 @Override
3801 public int getMaxNumPictureInPictureActions(IBinder token) {
3802 // Currently, this is a static constant, but later, we may change this to be dependent on
3803 // the context of the activity
3804 return 3;
3805 }
3806
3807 private void logPictureInPictureArgs(PictureInPictureParams params) {
3808 if (params.hasSetActions()) {
3809 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3810 params.getActions().size());
3811 }
3812 if (params.hasSetAspectRatio()) {
3813 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3814 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3815 MetricsLogger.action(lm);
3816 }
3817 }
3818
3819 /**
3820 * Checks the state of the system and the activity associated with the given {@param token} to
3821 * verify that picture-in-picture is supported for that activity.
3822 *
3823 * @return the activity record for the given {@param token} if all the checks pass.
3824 */
3825 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3826 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003827 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003828 throw new IllegalStateException(caller
3829 + ": Device doesn't support picture-in-picture mode.");
3830 }
3831
3832 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3833 if (r == null) {
3834 throw new IllegalStateException(caller
3835 + ": Can't find activity for token=" + token);
3836 }
3837
3838 if (!r.supportsPictureInPicture()) {
3839 throw new IllegalStateException(caller
3840 + ": Current activity does not support picture-in-picture.");
3841 }
3842
3843 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003844 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003845 params.getAspectRatio())) {
3846 final float minAspectRatio = mContext.getResources().getFloat(
3847 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3848 final float maxAspectRatio = mContext.getResources().getFloat(
3849 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3850 throw new IllegalArgumentException(String.format(caller
3851 + ": Aspect ratio is too extreme (must be between %f and %f).",
3852 minAspectRatio, maxAspectRatio));
3853 }
3854
3855 // Truncate the number of actions if necessary
3856 params.truncateActions(getMaxNumPictureInPictureActions(token));
3857
3858 return r;
3859 }
3860
3861 @Override
3862 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003863 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003864 synchronized (mGlobalLock) {
3865 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3866 if (r == null) {
3867 throw new IllegalArgumentException("Activity does not exist; token="
3868 + activityToken);
3869 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003870 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003871 }
3872 }
3873
3874 @Override
3875 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3876 Rect tempDockedTaskInsetBounds,
3877 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003878 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003879 long ident = Binder.clearCallingIdentity();
3880 try {
3881 synchronized (mGlobalLock) {
3882 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3883 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3884 PRESERVE_WINDOWS);
3885 }
3886 } finally {
3887 Binder.restoreCallingIdentity(ident);
3888 }
3889 }
3890
3891 @Override
3892 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003893 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003894 final long ident = Binder.clearCallingIdentity();
3895 try {
3896 synchronized (mGlobalLock) {
3897 mStackSupervisor.setSplitScreenResizing(resizing);
3898 }
3899 } finally {
3900 Binder.restoreCallingIdentity(ident);
3901 }
3902 }
3903
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003904 /**
3905 * Check that we have the features required for VR-related API calls, and throw an exception if
3906 * not.
3907 */
Wale Ogunwale59507092018-10-29 09:00:30 -07003908 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003909 if (!mContext.getPackageManager().hasSystemFeature(
3910 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3911 throw new UnsupportedOperationException("VR mode not supported on this device!");
3912 }
3913 }
3914
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 @Override
3916 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003917 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003918
3919 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3920
3921 ActivityRecord r;
3922 synchronized (mGlobalLock) {
3923 r = ActivityRecord.isInStackLocked(token);
3924 }
3925
3926 if (r == null) {
3927 throw new IllegalArgumentException();
3928 }
3929
3930 int err;
3931 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3932 VrManagerInternal.NO_ERROR) {
3933 return err;
3934 }
3935
3936 // Clear the binder calling uid since this path may call moveToTask().
3937 final long callingId = Binder.clearCallingIdentity();
3938 try {
3939 synchronized (mGlobalLock) {
3940 r.requestedVrComponent = (enabled) ? packageName : null;
3941
3942 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003943 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003944 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 }
3946 return 0;
3947 }
3948 } finally {
3949 Binder.restoreCallingIdentity(callingId);
3950 }
3951 }
3952
3953 @Override
3954 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3955 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3956 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003957 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003958 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3959 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3960 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003961 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003962 || activity.voiceSession != null) {
3963 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3964 return;
3965 }
3966 if (activity.pendingVoiceInteractionStart) {
3967 Slog.w(TAG, "Pending start of voice interaction already.");
3968 return;
3969 }
3970 activity.pendingVoiceInteractionStart = true;
3971 }
3972 LocalServices.getService(VoiceInteractionManagerInternal.class)
3973 .startLocalVoiceInteraction(callingActivity, options);
3974 }
3975
3976 @Override
3977 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3978 LocalServices.getService(VoiceInteractionManagerInternal.class)
3979 .stopLocalVoiceInteraction(callingActivity);
3980 }
3981
3982 @Override
3983 public boolean supportsLocalVoiceInteraction() {
3984 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3985 .supportsLocalVoiceInteraction();
3986 }
3987
3988 /** Notifies all listeners when the pinned stack animation starts. */
3989 @Override
3990 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003991 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 }
3993
3994 /** Notifies all listeners when the pinned stack animation ends. */
3995 @Override
3996 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003997 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003998 }
3999
4000 @Override
4001 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004002 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004003 final long ident = Binder.clearCallingIdentity();
4004 try {
4005 synchronized (mGlobalLock) {
4006 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4007 }
4008 } finally {
4009 Binder.restoreCallingIdentity(ident);
4010 }
4011 }
4012
4013 @Override
4014 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004015 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004016
4017 synchronized (mGlobalLock) {
4018 // Check if display is initialized in AM.
4019 if (!mStackSupervisor.isDisplayAdded(displayId)) {
4020 // Call might come when display is not yet added or has already been removed.
4021 if (DEBUG_CONFIGURATION) {
4022 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4023 + displayId);
4024 }
4025 return false;
4026 }
4027
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004028 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004030 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004031 }
4032
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004034 final Message msg = PooledLambda.obtainMessage(
4035 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4036 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004037 }
4038
4039 final long origId = Binder.clearCallingIdentity();
4040 try {
4041 if (values != null) {
4042 Settings.System.clearConfiguration(values);
4043 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004044 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004045 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4046 return mTmpUpdateConfigurationResult.changes != 0;
4047 } finally {
4048 Binder.restoreCallingIdentity(origId);
4049 }
4050 }
4051 }
4052
4053 @Override
4054 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004055 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056
4057 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004058 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004060 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004061 }
4062
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004063 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004064 final Message msg = PooledLambda.obtainMessage(
4065 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4066 DEFAULT_DISPLAY);
4067 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004068 }
4069
4070 final long origId = Binder.clearCallingIdentity();
4071 try {
4072 if (values != null) {
4073 Settings.System.clearConfiguration(values);
4074 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004075 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004076 UserHandle.USER_NULL, false /* deferResume */,
4077 mTmpUpdateConfigurationResult);
4078 return mTmpUpdateConfigurationResult.changes != 0;
4079 } finally {
4080 Binder.restoreCallingIdentity(origId);
4081 }
4082 }
4083 }
4084
4085 @Override
4086 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4087 CharSequence message) {
4088 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004089 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4091 }
4092 final long callingId = Binder.clearCallingIdentity();
4093 try {
4094 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004095 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004096 }
4097 } finally {
4098 Binder.restoreCallingIdentity(callingId);
4099 }
4100 }
4101
4102 @Override
4103 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004104 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004105 "cancelTaskWindowTransition()");
4106 final long ident = Binder.clearCallingIdentity();
4107 try {
4108 synchronized (mGlobalLock) {
4109 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4110 MATCH_TASK_IN_STACKS_ONLY);
4111 if (task == null) {
4112 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4113 return;
4114 }
4115 task.cancelWindowTransition();
4116 }
4117 } finally {
4118 Binder.restoreCallingIdentity(ident);
4119 }
4120 }
4121
4122 @Override
4123 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004124 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004125 final long ident = Binder.clearCallingIdentity();
4126 try {
4127 final TaskRecord task;
4128 synchronized (mGlobalLock) {
4129 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4130 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4131 if (task == null) {
4132 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4133 return null;
4134 }
4135 }
4136 // Don't call this while holding the lock as this operation might hit the disk.
4137 return task.getSnapshot(reducedResolution);
4138 } finally {
4139 Binder.restoreCallingIdentity(ident);
4140 }
4141 }
4142
4143 @Override
4144 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4145 synchronized (mGlobalLock) {
4146 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4147 if (r == null) {
4148 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4149 + token);
4150 return;
4151 }
4152 final long origId = Binder.clearCallingIdentity();
4153 try {
4154 r.setDisablePreviewScreenshots(disable);
4155 } finally {
4156 Binder.restoreCallingIdentity(origId);
4157 }
4158 }
4159 }
4160
4161 /** Return the user id of the last resumed activity. */
4162 @Override
4163 public @UserIdInt
4164 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004165 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4167 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004168 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004169 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004171 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 }
4173 }
4174
4175 @Override
4176 public void updateLockTaskFeatures(int userId, int flags) {
4177 final int callingUid = Binder.getCallingUid();
4178 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004179 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 "updateLockTaskFeatures()");
4181 }
4182 synchronized (mGlobalLock) {
4183 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4184 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004185 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004186 }
4187 }
4188
4189 @Override
4190 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4191 synchronized (mGlobalLock) {
4192 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4193 if (r == null) {
4194 return;
4195 }
4196 final long origId = Binder.clearCallingIdentity();
4197 try {
4198 r.setShowWhenLocked(showWhenLocked);
4199 } finally {
4200 Binder.restoreCallingIdentity(origId);
4201 }
4202 }
4203 }
4204
4205 @Override
4206 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4207 synchronized (mGlobalLock) {
4208 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4209 if (r == null) {
4210 return;
4211 }
4212 final long origId = Binder.clearCallingIdentity();
4213 try {
4214 r.setTurnScreenOn(turnScreenOn);
4215 } finally {
4216 Binder.restoreCallingIdentity(origId);
4217 }
4218 }
4219 }
4220
4221 @Override
4222 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004223 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 "registerRemoteAnimations");
4225 definition.setCallingPid(Binder.getCallingPid());
4226 synchronized (mGlobalLock) {
4227 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4228 if (r == null) {
4229 return;
4230 }
4231 final long origId = Binder.clearCallingIdentity();
4232 try {
4233 r.registerRemoteAnimations(definition);
4234 } finally {
4235 Binder.restoreCallingIdentity(origId);
4236 }
4237 }
4238 }
4239
4240 @Override
4241 public void registerRemoteAnimationForNextActivityStart(String packageName,
4242 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004243 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004244 "registerRemoteAnimationForNextActivityStart");
4245 adapter.setCallingPid(Binder.getCallingPid());
4246 synchronized (mGlobalLock) {
4247 final long origId = Binder.clearCallingIdentity();
4248 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004249 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004250 packageName, adapter);
4251 } finally {
4252 Binder.restoreCallingIdentity(origId);
4253 }
4254 }
4255 }
4256
4257 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4258 @Override
4259 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4260 synchronized (mGlobalLock) {
4261 final long origId = Binder.clearCallingIdentity();
4262 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004263 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004264 } finally {
4265 Binder.restoreCallingIdentity(origId);
4266 }
4267 }
4268 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004269
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004270 @Override
4271 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004272 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004273 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004274 final int pid = Binder.getCallingPid();
4275 final WindowProcessController wpc = mPidMap.get(pid);
4276 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004277 }
4278 }
4279
4280 @Override
4281 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004282 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004283 != PERMISSION_GRANTED) {
4284 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4285 + Binder.getCallingPid()
4286 + ", uid=" + Binder.getCallingUid()
4287 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4288 Slog.w(TAG, msg);
4289 throw new SecurityException(msg);
4290 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004291 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004292 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004293 final int pid = Binder.getCallingPid();
4294 final WindowProcessController proc = mPidMap.get(pid);
4295 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004296 }
4297 }
4298
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004299 @Override
4300 public void stopAppSwitches() {
4301 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4302 synchronized (mGlobalLock) {
4303 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4304 mDidAppSwitch = false;
4305 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4306 }
4307 }
4308
4309 @Override
4310 public void resumeAppSwitches() {
4311 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4312 synchronized (mGlobalLock) {
4313 // Note that we don't execute any pending app switches... we will
4314 // let those wait until either the timeout, or the next start
4315 // activity request.
4316 mAppSwitchesAllowedTime = 0;
4317 }
4318 }
4319
4320 void onStartActivitySetDidAppSwitch() {
4321 if (mDidAppSwitch) {
4322 // This is the second allowed switch since we stopped switches, so now just generally
4323 // allow switches. Use case:
4324 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4325 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4326 // anyone to switch again).
4327 mAppSwitchesAllowedTime = 0;
4328 } else {
4329 mDidAppSwitch = true;
4330 }
4331 }
4332
4333 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004334 boolean shouldDisableNonVrUiLocked() {
4335 return mVrController.shouldDisableNonVrUiLocked();
4336 }
4337
Wale Ogunwale53783742018-09-16 10:21:51 -07004338 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004339 // VR apps are expected to run in a main display. If an app is turning on VR for
4340 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4341 // fullscreen stack before enabling VR Mode.
4342 // TODO: The goal of this code is to keep the VR app on the main display. When the
4343 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4344 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4345 // option would be a better choice here.
4346 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4347 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4348 + " to main stack for VR");
4349 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4350 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4351 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4352 }
4353 mH.post(() -> {
4354 if (!mVrController.onVrModeChanged(r)) {
4355 return;
4356 }
4357 synchronized (mGlobalLock) {
4358 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4359 mWindowManager.disableNonVrUi(disableNonVrUi);
4360 if (disableNonVrUi) {
4361 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4362 // then remove the pinned stack.
4363 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4364 }
4365 }
4366 });
4367 }
4368
Wale Ogunwale53783742018-09-16 10:21:51 -07004369 @Override
4370 public int getPackageScreenCompatMode(String packageName) {
4371 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4372 synchronized (mGlobalLock) {
4373 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4374 }
4375 }
4376
4377 @Override
4378 public void setPackageScreenCompatMode(String packageName, int mode) {
4379 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4380 "setPackageScreenCompatMode");
4381 synchronized (mGlobalLock) {
4382 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4383 }
4384 }
4385
4386 @Override
4387 public boolean getPackageAskScreenCompat(String packageName) {
4388 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4389 synchronized (mGlobalLock) {
4390 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4391 }
4392 }
4393
4394 @Override
4395 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4396 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4397 "setPackageAskScreenCompat");
4398 synchronized (mGlobalLock) {
4399 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4400 }
4401 }
4402
Wale Ogunwale64258362018-10-16 15:13:37 -07004403 public static String relaunchReasonToString(int relaunchReason) {
4404 switch (relaunchReason) {
4405 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4406 return "window_resize";
4407 case RELAUNCH_REASON_FREE_RESIZE:
4408 return "free_resize";
4409 default:
4410 return null;
4411 }
4412 }
4413
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004414 ActivityStack getTopDisplayFocusedStack() {
4415 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004416 }
4417
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004418 /** Pokes the task persister. */
4419 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4420 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4421 }
4422
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004423 boolean isKeyguardLocked() {
4424 return mKeyguardController.isKeyguardLocked();
4425 }
4426
Wale Ogunwale31913b52018-10-13 08:29:31 -07004427 void dumpLastANRLocked(PrintWriter pw) {
4428 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4429 if (mLastANRState == null) {
4430 pw.println(" <no ANR has occurred since boot>");
4431 } else {
4432 pw.println(mLastANRState);
4433 }
4434 }
4435
4436 void dumpLastANRTracesLocked(PrintWriter pw) {
4437 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4438
4439 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4440 if (ArrayUtils.isEmpty(files)) {
4441 pw.println(" <no ANR has occurred since boot>");
4442 return;
4443 }
4444 // Find the latest file.
4445 File latest = null;
4446 for (File f : files) {
4447 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4448 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004449 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004450 }
4451 pw.print("File: ");
4452 pw.print(latest.getName());
4453 pw.println();
4454 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4455 String line;
4456 while ((line = in.readLine()) != null) {
4457 pw.println(line);
4458 }
4459 } catch (IOException e) {
4460 pw.print("Unable to read: ");
4461 pw.print(e);
4462 pw.println();
4463 }
4464 }
4465
4466 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4467 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4468 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4469 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4470 }
4471
4472 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4473 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4474 pw.println(header);
4475
4476 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4477 dumpPackage);
4478 boolean needSep = printedAnything;
4479
4480 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4481 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4482 " ResumedActivity: ");
4483 if (printed) {
4484 printedAnything = true;
4485 needSep = false;
4486 }
4487
4488 if (dumpPackage == null) {
4489 if (needSep) {
4490 pw.println();
4491 }
4492 printedAnything = true;
4493 mStackSupervisor.dump(pw, " ");
4494 }
4495
4496 if (!printedAnything) {
4497 pw.println(" (nothing)");
4498 }
4499 }
4500
4501 void dumpActivityContainersLocked(PrintWriter pw) {
4502 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4503 mStackSupervisor.dumpChildrenNames(pw, " ");
4504 pw.println(" ");
4505 }
4506
4507 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4508 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4509 getActivityStartController().dump(pw, "", dumpPackage);
4510 }
4511
4512 /**
4513 * There are three things that cmd can be:
4514 * - a flattened component name that matches an existing activity
4515 * - the cmd arg isn't the flattened component name of an existing activity:
4516 * dump all activity whose component contains the cmd as a substring
4517 * - A hex number of the ActivityRecord object instance.
4518 *
4519 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4520 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4521 */
4522 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4523 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4524 ArrayList<ActivityRecord> activities;
4525
4526 synchronized (mGlobalLock) {
4527 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4528 dumpFocusedStackOnly);
4529 }
4530
4531 if (activities.size() <= 0) {
4532 return false;
4533 }
4534
4535 String[] newArgs = new String[args.length - opti];
4536 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4537
4538 TaskRecord lastTask = null;
4539 boolean needSep = false;
4540 for (int i = activities.size() - 1; i >= 0; i--) {
4541 ActivityRecord r = activities.get(i);
4542 if (needSep) {
4543 pw.println();
4544 }
4545 needSep = true;
4546 synchronized (mGlobalLock) {
4547 final TaskRecord task = r.getTask();
4548 if (lastTask != task) {
4549 lastTask = task;
4550 pw.print("TASK "); pw.print(lastTask.affinity);
4551 pw.print(" id="); pw.print(lastTask.taskId);
4552 pw.print(" userId="); pw.println(lastTask.userId);
4553 if (dumpAll) {
4554 lastTask.dump(pw, " ");
4555 }
4556 }
4557 }
4558 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4559 }
4560 return true;
4561 }
4562
4563 /**
4564 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4565 * there is a thread associated with the activity.
4566 */
4567 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4568 final ActivityRecord r, String[] args, boolean dumpAll) {
4569 String innerPrefix = prefix + " ";
4570 synchronized (mGlobalLock) {
4571 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4572 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4573 pw.print(" pid=");
4574 if (r.hasProcess()) pw.println(r.app.getPid());
4575 else pw.println("(not running)");
4576 if (dumpAll) {
4577 r.dump(pw, innerPrefix);
4578 }
4579 }
4580 if (r.attachedToProcess()) {
4581 // flush anything that is already in the PrintWriter since the thread is going
4582 // to write to the file descriptor directly
4583 pw.flush();
4584 try {
4585 TransferPipe tp = new TransferPipe();
4586 try {
4587 r.app.getThread().dumpActivity(tp.getWriteFd(),
4588 r.appToken, innerPrefix, args);
4589 tp.go(fd);
4590 } finally {
4591 tp.kill();
4592 }
4593 } catch (IOException e) {
4594 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4595 } catch (RemoteException e) {
4596 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4597 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004598 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004599 }
4600
Wale Ogunwalef6733932018-06-27 05:14:34 -07004601 void writeSleepStateToProto(ProtoOutputStream proto) {
4602 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4603 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4604 st.toString());
4605 }
4606
4607 if (mRunningVoice != null) {
4608 final long vrToken = proto.start(
4609 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4610 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4611 mRunningVoice.toString());
4612 mVoiceWakeLock.writeToProto(
4613 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4614 proto.end(vrToken);
4615 }
4616
4617 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4618 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4619 mShuttingDown);
4620 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004621 }
4622
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004623 int getCurrentUserId() {
4624 return mAmInternal.getCurrentUserId();
4625 }
4626
4627 private void enforceNotIsolatedCaller(String caller) {
4628 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4629 throw new SecurityException("Isolated process not allowed to call " + caller);
4630 }
4631 }
4632
Wale Ogunwalef6733932018-06-27 05:14:34 -07004633 public Configuration getConfiguration() {
4634 Configuration ci;
4635 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004636 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004637 ci.userSetLocale = false;
4638 }
4639 return ci;
4640 }
4641
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004642 /**
4643 * Current global configuration information. Contains general settings for the entire system,
4644 * also corresponds to the merged configuration of the default display.
4645 */
4646 Configuration getGlobalConfiguration() {
4647 return mStackSupervisor.getConfiguration();
4648 }
4649
4650 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4651 boolean initLocale) {
4652 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4653 }
4654
4655 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4656 boolean initLocale, boolean deferResume) {
4657 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4658 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4659 UserHandle.USER_NULL, deferResume);
4660 }
4661
Wale Ogunwale59507092018-10-29 09:00:30 -07004662 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004663 final long origId = Binder.clearCallingIdentity();
4664 try {
4665 synchronized (mGlobalLock) {
4666 updateConfigurationLocked(values, null, false, true, userId,
4667 false /* deferResume */);
4668 }
4669 } finally {
4670 Binder.restoreCallingIdentity(origId);
4671 }
4672 }
4673
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004674 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4675 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4676 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4677 deferResume, null /* result */);
4678 }
4679
4680 /**
4681 * Do either or both things: (1) change the current configuration, and (2)
4682 * make sure the given activity is running with the (now) current
4683 * configuration. Returns true if the activity has been left running, or
4684 * false if <var>starting</var> is being destroyed to match the new
4685 * configuration.
4686 *
4687 * @param userId is only used when persistent parameter is set to true to persist configuration
4688 * for that particular user
4689 */
4690 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4691 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4692 ActivityTaskManagerService.UpdateConfigurationResult result) {
4693 int changes = 0;
4694 boolean kept = true;
4695
4696 if (mWindowManager != null) {
4697 mWindowManager.deferSurfaceLayout();
4698 }
4699 try {
4700 if (values != null) {
4701 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4702 deferResume);
4703 }
4704
4705 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4706 } finally {
4707 if (mWindowManager != null) {
4708 mWindowManager.continueSurfaceLayout();
4709 }
4710 }
4711
4712 if (result != null) {
4713 result.changes = changes;
4714 result.activityRelaunched = !kept;
4715 }
4716 return kept;
4717 }
4718
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004719 /** Update default (global) configuration and notify listeners about changes. */
4720 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4721 boolean persistent, int userId, boolean deferResume) {
4722 mTempConfig.setTo(getGlobalConfiguration());
4723 final int changes = mTempConfig.updateFrom(values);
4724 if (changes == 0) {
4725 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4726 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4727 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4728 // (even if there are no actual changes) to unfreeze the window.
4729 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4730 return 0;
4731 }
4732
4733 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4734 "Updating global configuration to: " + values);
4735
4736 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4737 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4738 values.colorMode,
4739 values.densityDpi,
4740 values.fontScale,
4741 values.hardKeyboardHidden,
4742 values.keyboard,
4743 values.keyboardHidden,
4744 values.mcc,
4745 values.mnc,
4746 values.navigation,
4747 values.navigationHidden,
4748 values.orientation,
4749 values.screenHeightDp,
4750 values.screenLayout,
4751 values.screenWidthDp,
4752 values.smallestScreenWidthDp,
4753 values.touchscreen,
4754 values.uiMode);
4755
4756
4757 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4758 final LocaleList locales = values.getLocales();
4759 int bestLocaleIndex = 0;
4760 if (locales.size() > 1) {
4761 if (mSupportedSystemLocales == null) {
4762 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4763 }
4764 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4765 }
4766 SystemProperties.set("persist.sys.locale",
4767 locales.get(bestLocaleIndex).toLanguageTag());
4768 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004769
4770 final Message m = PooledLambda.obtainMessage(
4771 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4772 locales.get(bestLocaleIndex));
4773 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004774 }
4775
Yunfan Chen75157d72018-07-27 14:47:21 +09004776 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004777
4778 // Update stored global config and notify everyone about the change.
4779 mStackSupervisor.onConfigurationChanged(mTempConfig);
4780
4781 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4782 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004783 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004784
4785 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004786 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004787
4788 AttributeCache ac = AttributeCache.instance();
4789 if (ac != null) {
4790 ac.updateConfiguration(mTempConfig);
4791 }
4792
4793 // Make sure all resources in our process are updated right now, so that anyone who is going
4794 // to retrieve resource values after we return will be sure to get the new ones. This is
4795 // especially important during boot, where the first config change needs to guarantee all
4796 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004797 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004798
4799 // We need another copy of global config because we're scheduling some calls instead of
4800 // running them in place. We need to be sure that object we send will be handled unchanged.
4801 final Configuration configCopy = new Configuration(mTempConfig);
4802 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004803 final Message msg = PooledLambda.obtainMessage(
4804 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4805 this, userId, configCopy);
4806 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004807 }
4808
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004809 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004810 final int pid = mPidMap.keyAt(i);
4811 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004812 if (DEBUG_CONFIGURATION) {
4813 Slog.v(TAG_CONFIGURATION, "Update process config of "
4814 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004815 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004816 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004817 }
4818
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004819 final Message msg = PooledLambda.obtainMessage(
4820 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4821 mAmInternal, changes, initLocale);
4822 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004823
4824 // Override configuration of the default display duplicates global config, so we need to
4825 // update it also. This will also notify WindowManager about changes.
4826 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4827 DEFAULT_DISPLAY);
4828
4829 return changes;
4830 }
4831
4832 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4833 boolean deferResume, int displayId) {
4834 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4835 displayId, null /* result */);
4836 }
4837
4838 /**
4839 * Updates override configuration specific for the selected display. If no config is provided,
4840 * new one will be computed in WM based on current display info.
4841 */
4842 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4843 ActivityRecord starting, boolean deferResume, int displayId,
4844 ActivityTaskManagerService.UpdateConfigurationResult result) {
4845 int changes = 0;
4846 boolean kept = true;
4847
4848 if (mWindowManager != null) {
4849 mWindowManager.deferSurfaceLayout();
4850 }
4851 try {
4852 if (values != null) {
4853 if (displayId == DEFAULT_DISPLAY) {
4854 // Override configuration of the default display duplicates global config, so
4855 // we're calling global config update instead for default display. It will also
4856 // apply the correct override config.
4857 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4858 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4859 } else {
4860 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4861 }
4862 }
4863
4864 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4865 } finally {
4866 if (mWindowManager != null) {
4867 mWindowManager.continueSurfaceLayout();
4868 }
4869 }
4870
4871 if (result != null) {
4872 result.changes = changes;
4873 result.activityRelaunched = !kept;
4874 }
4875 return kept;
4876 }
4877
4878 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4879 int displayId) {
4880 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4881 final int changes = mTempConfig.updateFrom(values);
4882 if (changes != 0) {
4883 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4884 + mTempConfig + " for displayId=" + displayId);
4885 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4886
4887 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4888 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004889 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004890
Wale Ogunwale5c918702018-10-18 11:06:33 -07004891 // Post message to start process to avoid possible deadlock of calling into AMS with
4892 // the ATMS lock held.
4893 final Message msg = PooledLambda.obtainMessage(
4894 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4895 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4896 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004897 }
4898 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004899 return changes;
4900 }
4901
Wale Ogunwalef6733932018-06-27 05:14:34 -07004902 private void updateEventDispatchingLocked(boolean booted) {
4903 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4904 }
4905
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004906 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4907 final ContentResolver resolver = mContext.getContentResolver();
4908 Settings.System.putConfigurationForUser(resolver, config, userId);
4909 }
4910
4911 private void sendLocaleToMountDaemonMsg(Locale l) {
4912 try {
4913 IBinder service = ServiceManager.getService("mount");
4914 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
4915 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
4916 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
4917 } catch (RemoteException e) {
4918 Log.e(TAG, "Error storing locale for decryption UI", e);
4919 }
4920 }
4921
4922 boolean isActivityStartsLoggingEnabled() {
4923 return mAmInternal.isActivityStartsLoggingEnabled();
4924 }
4925
Wale Ogunwalef6733932018-06-27 05:14:34 -07004926 void enableScreenAfterBoot(boolean booted) {
4927 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4928 SystemClock.uptimeMillis());
4929 mWindowManager.enableScreenAfterBoot();
4930
4931 synchronized (mGlobalLock) {
4932 updateEventDispatchingLocked(booted);
4933 }
4934 }
4935
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004936 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
4937 if (r == null || !r.hasProcess()) {
4938 return KEY_DISPATCHING_TIMEOUT_MS;
4939 }
4940 return getInputDispatchingTimeoutLocked(r.app);
4941 }
4942
4943 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07004944 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004945 }
4946
Wale Ogunwalef6733932018-06-27 05:14:34 -07004947 /**
4948 * Decide based on the configuration whether we should show the ANR,
4949 * crash, etc dialogs. The idea is that if there is no affordance to
4950 * press the on-screen buttons, or the user experience would be more
4951 * greatly impacted than the crash itself, we shouldn't show the dialog.
4952 *
4953 * A thought: SystemUI might also want to get told about this, the Power
4954 * dialog / global actions also might want different behaviors.
4955 */
4956 private void updateShouldShowDialogsLocked(Configuration config) {
4957 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4958 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4959 && config.navigation == Configuration.NAVIGATION_NONAV);
4960 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4961 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4962 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4963 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4964 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4965 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4966 HIDE_ERROR_DIALOGS, 0) != 0;
4967 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4968 }
4969
4970 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4971 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4972 FONT_SCALE, 1.0f, userId);
4973
4974 synchronized (this) {
4975 if (getGlobalConfiguration().fontScale == scaleFactor) {
4976 return;
4977 }
4978
4979 final Configuration configuration
4980 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4981 configuration.fontScale = scaleFactor;
4982 updatePersistentConfiguration(configuration, userId);
4983 }
4984 }
4985
4986 // Actually is sleeping or shutting down or whatever else in the future
4987 // is an inactive state.
4988 boolean isSleepingOrShuttingDownLocked() {
4989 return isSleepingLocked() || mShuttingDown;
4990 }
4991
4992 boolean isSleepingLocked() {
4993 return mSleeping;
4994 }
4995
Riddle Hsu16567132018-08-16 21:37:47 +08004996 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07004997 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4998 final TaskRecord task = r.getTask();
4999 if (task.isActivityTypeStandard()) {
5000 if (mCurAppTimeTracker != r.appTimeTracker) {
5001 // We are switching app tracking. Complete the current one.
5002 if (mCurAppTimeTracker != null) {
5003 mCurAppTimeTracker.stop();
5004 mH.obtainMessage(
5005 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
5006 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
5007 mCurAppTimeTracker = null;
5008 }
5009 if (r.appTimeTracker != null) {
5010 mCurAppTimeTracker = r.appTimeTracker;
5011 startTimeTrackingFocusedActivityLocked();
5012 }
5013 } else {
5014 startTimeTrackingFocusedActivityLocked();
5015 }
5016 } else {
5017 r.appTimeTracker = null;
5018 }
5019 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5020 // TODO: Probably not, because we don't want to resume voice on switching
5021 // back to this activity
5022 if (task.voiceInteractor != null) {
5023 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5024 } else {
5025 finishRunningVoiceLocked();
5026
5027 if (mLastResumedActivity != null) {
5028 final IVoiceInteractionSession session;
5029
5030 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5031 if (lastResumedActivityTask != null
5032 && lastResumedActivityTask.voiceSession != null) {
5033 session = lastResumedActivityTask.voiceSession;
5034 } else {
5035 session = mLastResumedActivity.voiceSession;
5036 }
5037
5038 if (session != null) {
5039 // We had been in a voice interaction session, but now focused has
5040 // move to something different. Just finish the session, we can't
5041 // return to it and retain the proper state and synchronization with
5042 // the voice interaction service.
5043 finishVoiceTask(session);
5044 }
5045 }
5046 }
5047
5048 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5049 mAmInternal.sendForegroundProfileChanged(r.userId);
5050 }
5051 updateResumedAppTrace(r);
5052 mLastResumedActivity = r;
5053
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005054 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005055
5056 applyUpdateLockStateLocked(r);
5057 applyUpdateVrModeLocked(r);
5058
5059 EventLogTags.writeAmSetResumedActivity(
5060 r == null ? -1 : r.userId,
5061 r == null ? "NULL" : r.shortComponentName,
5062 reason);
5063 }
5064
5065 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5066 synchronized (mGlobalLock) {
5067 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5068 updateSleepIfNeededLocked();
5069 return token;
5070 }
5071 }
5072
5073 void updateSleepIfNeededLocked() {
5074 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5075 final boolean wasSleeping = mSleeping;
5076 boolean updateOomAdj = false;
5077
5078 if (!shouldSleep) {
5079 // If wasSleeping is true, we need to wake up activity manager state from when
5080 // we started sleeping. In either case, we need to apply the sleep tokens, which
5081 // will wake up stacks or put them to sleep as appropriate.
5082 if (wasSleeping) {
5083 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005084 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5085 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005086 startTimeTrackingFocusedActivityLocked();
5087 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5088 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5089 }
5090 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5091 if (wasSleeping) {
5092 updateOomAdj = true;
5093 }
5094 } else if (!mSleeping && shouldSleep) {
5095 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005096 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5097 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005098 if (mCurAppTimeTracker != null) {
5099 mCurAppTimeTracker.stop();
5100 }
5101 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5102 mStackSupervisor.goingToSleepLocked();
5103 updateResumedAppTrace(null /* resumed */);
5104 updateOomAdj = true;
5105 }
5106 if (updateOomAdj) {
5107 mH.post(mAmInternal::updateOomAdj);
5108 }
5109 }
5110
5111 void updateOomAdj() {
5112 mH.post(mAmInternal::updateOomAdj);
5113 }
5114
Wale Ogunwale53783742018-09-16 10:21:51 -07005115 void updateCpuStats() {
5116 mH.post(mAmInternal::updateCpuStats);
5117 }
5118
5119 void updateUsageStats(ActivityRecord component, boolean resumed) {
5120 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5121 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5122 mH.sendMessage(m);
5123 }
5124
5125 void setBooting(boolean booting) {
5126 mAmInternal.setBooting(booting);
5127 }
5128
5129 boolean isBooting() {
5130 return mAmInternal.isBooting();
5131 }
5132
5133 void setBooted(boolean booted) {
5134 mAmInternal.setBooted(booted);
5135 }
5136
5137 boolean isBooted() {
5138 return mAmInternal.isBooted();
5139 }
5140
5141 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5142 mH.post(() -> {
5143 if (finishBooting) {
5144 mAmInternal.finishBooting();
5145 }
5146 if (enableScreen) {
5147 mInternal.enableScreenAfterBoot(isBooted());
5148 }
5149 });
5150 }
5151
5152 void setHeavyWeightProcess(ActivityRecord root) {
5153 mHeavyWeightProcess = root.app;
5154 final Message m = PooledLambda.obtainMessage(
5155 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5156 root.app, root.intent, root.userId);
5157 mH.sendMessage(m);
5158 }
5159
5160 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5161 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5162 return;
5163 }
5164
5165 mHeavyWeightProcess = null;
5166 final Message m = PooledLambda.obtainMessage(
5167 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5168 proc.mUserId);
5169 mH.sendMessage(m);
5170 }
5171
5172 private void cancelHeavyWeightProcessNotification(int userId) {
5173 final INotificationManager inm = NotificationManager.getService();
5174 if (inm == null) {
5175 return;
5176 }
5177 try {
5178 inm.cancelNotificationWithTag("android", null,
5179 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5180 } catch (RuntimeException e) {
5181 Slog.w(TAG, "Error canceling notification for service", e);
5182 } catch (RemoteException e) {
5183 }
5184
5185 }
5186
5187 private void postHeavyWeightProcessNotification(
5188 WindowProcessController proc, Intent intent, int userId) {
5189 if (proc == null) {
5190 return;
5191 }
5192
5193 final INotificationManager inm = NotificationManager.getService();
5194 if (inm == null) {
5195 return;
5196 }
5197
5198 try {
5199 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5200 String text = mContext.getString(R.string.heavy_weight_notification,
5201 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5202 Notification notification =
5203 new Notification.Builder(context,
5204 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5205 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5206 .setWhen(0)
5207 .setOngoing(true)
5208 .setTicker(text)
5209 .setColor(mContext.getColor(
5210 com.android.internal.R.color.system_notification_accent_color))
5211 .setContentTitle(text)
5212 .setContentText(
5213 mContext.getText(R.string.heavy_weight_notification_detail))
5214 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5215 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5216 new UserHandle(userId)))
5217 .build();
5218 try {
5219 inm.enqueueNotificationWithTag("android", "android", null,
5220 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5221 } catch (RuntimeException e) {
5222 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5223 } catch (RemoteException e) {
5224 }
5225 } catch (PackageManager.NameNotFoundException e) {
5226 Slog.w(TAG, "Unable to create context for heavy notification", e);
5227 }
5228
5229 }
5230
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005231 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5232 IBinder token, String resultWho, int requestCode, Intent[] intents,
5233 String[] resolvedTypes, int flags, Bundle bOptions) {
5234
5235 ActivityRecord activity = null;
5236 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5237 activity = ActivityRecord.isInStackLocked(token);
5238 if (activity == null) {
5239 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5240 return null;
5241 }
5242 if (activity.finishing) {
5243 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5244 return null;
5245 }
5246 }
5247
5248 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5249 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5250 bOptions);
5251 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5252 if (noCreate) {
5253 return rec;
5254 }
5255 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5256 if (activity.pendingResults == null) {
5257 activity.pendingResults = new HashSet<>();
5258 }
5259 activity.pendingResults.add(rec.ref);
5260 }
5261 return rec;
5262 }
5263
Andrii Kulian52d255c2018-07-13 11:32:19 -07005264 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005265 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005266 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005267 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5268 mCurAppTimeTracker.start(resumedActivity.packageName);
5269 }
5270 }
5271
5272 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5273 if (mTracedResumedActivity != null) {
5274 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5275 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5276 }
5277 if (resumed != null) {
5278 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5279 constructResumedTraceName(resumed.packageName), 0);
5280 }
5281 mTracedResumedActivity = resumed;
5282 }
5283
5284 private String constructResumedTraceName(String packageName) {
5285 return "focused app: " + packageName;
5286 }
5287
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005288 /** Applies latest configuration and/or visibility updates if needed. */
5289 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5290 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005291 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005292 // mainStack is null during startup.
5293 if (mainStack != null) {
5294 if (changes != 0 && starting == null) {
5295 // If the configuration changed, and the caller is not already
5296 // in the process of starting an activity, then find the top
5297 // activity to check if its configuration needs to change.
5298 starting = mainStack.topRunningActivityLocked();
5299 }
5300
5301 if (starting != null) {
5302 kept = starting.ensureActivityConfiguration(changes,
5303 false /* preserveWindow */);
5304 // And we need to make sure at this point that all other activities
5305 // are made visible with the correct configuration.
5306 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5307 !PRESERVE_WINDOWS);
5308 }
5309 }
5310
5311 return kept;
5312 }
5313
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005314 void scheduleAppGcsLocked() {
5315 mH.post(() -> mAmInternal.scheduleAppGcs());
5316 }
5317
Wale Ogunwale53783742018-09-16 10:21:51 -07005318 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5319 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5320 }
5321
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005322 /**
5323 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5324 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5325 * on demand.
5326 */
5327 IPackageManager getPackageManager() {
5328 return AppGlobals.getPackageManager();
5329 }
5330
5331 PackageManagerInternal getPackageManagerInternalLocked() {
5332 if (mPmInternal == null) {
5333 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5334 }
5335 return mPmInternal;
5336 }
5337
Wale Ogunwale008163e2018-07-23 23:11:08 -07005338 AppWarnings getAppWarningsLocked() {
5339 return mAppWarnings;
5340 }
5341
Wale Ogunwale214f3482018-10-04 11:00:47 -07005342 Intent getHomeIntent() {
5343 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5344 intent.setComponent(mTopComponent);
5345 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5346 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5347 intent.addCategory(Intent.CATEGORY_HOME);
5348 }
5349 return intent;
5350 }
5351
Wale Ogunwale214f3482018-10-04 11:00:47 -07005352 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5353 if (info == null) return null;
5354 ApplicationInfo newInfo = new ApplicationInfo(info);
5355 newInfo.initForUser(userId);
5356 return newInfo;
5357 }
5358
Wale Ogunwale9c103022018-10-18 07:44:54 -07005359 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005360 if (uid == SYSTEM_UID) {
5361 // The system gets to run in any process. If there are multiple processes with the same
5362 // uid, just pick the first (this should never happen).
5363 final SparseArray<WindowProcessController> procs =
5364 mProcessNames.getMap().get(processName);
5365 if (procs == null) return null;
5366 final int procCount = procs.size();
5367 for (int i = 0; i < procCount; i++) {
5368 final int procUid = procs.keyAt(i);
5369 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5370 // Don't use an app process or different user process for system component.
5371 continue;
5372 }
5373 return procs.valueAt(i);
5374 }
5375 }
5376
5377 return mProcessNames.get(processName, uid);
5378 }
5379
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005380 WindowProcessController getProcessController(IApplicationThread thread) {
5381 if (thread == null) {
5382 return null;
5383 }
5384
5385 final IBinder threadBinder = thread.asBinder();
5386 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5387 for (int i = pmap.size()-1; i >= 0; i--) {
5388 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5389 for (int j = procs.size() - 1; j >= 0; j--) {
5390 final WindowProcessController proc = procs.valueAt(j);
5391 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5392 return proc;
5393 }
5394 }
5395 }
5396
5397 return null;
5398 }
5399
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005400 int getUidStateLocked(int uid) {
5401 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5402 }
5403
Wale Ogunwale9de19442018-10-18 19:05:03 -07005404 /**
5405 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5406 * the whitelist
5407 */
5408 String getPendingTempWhitelistTagForUidLocked(int uid) {
5409 return mPendingTempWhitelist.get(uid);
5410 }
5411
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005412 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5413 if (true || Build.IS_USER) {
5414 return;
5415 }
5416
5417 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5418 StrictMode.allowThreadDiskWrites();
5419 try {
5420 File tracesDir = new File("/data/anr");
5421 File tracesFile = null;
5422 try {
5423 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5424
5425 StringBuilder sb = new StringBuilder();
5426 Time tobj = new Time();
5427 tobj.set(System.currentTimeMillis());
5428 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5429 sb.append(": ");
5430 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5431 sb.append(" since ");
5432 sb.append(msg);
5433 FileOutputStream fos = new FileOutputStream(tracesFile);
5434 fos.write(sb.toString().getBytes());
5435 if (app == null) {
5436 fos.write("\n*** No application process!".getBytes());
5437 }
5438 fos.close();
5439 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5440 } catch (IOException e) {
5441 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5442 return;
5443 }
5444
5445 if (app != null && app.getPid() > 0) {
5446 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5447 firstPids.add(app.getPid());
5448 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5449 }
5450
5451 File lastTracesFile = null;
5452 File curTracesFile = null;
5453 for (int i=9; i>=0; i--) {
5454 String name = String.format(Locale.US, "slow%02d.txt", i);
5455 curTracesFile = new File(tracesDir, name);
5456 if (curTracesFile.exists()) {
5457 if (lastTracesFile != null) {
5458 curTracesFile.renameTo(lastTracesFile);
5459 } else {
5460 curTracesFile.delete();
5461 }
5462 }
5463 lastTracesFile = curTracesFile;
5464 }
5465 tracesFile.renameTo(curTracesFile);
5466 } finally {
5467 StrictMode.setThreadPolicy(oldPolicy);
5468 }
5469 }
5470
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005471 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005472 static final int REPORT_TIME_TRACKER_MSG = 1;
Wale Ogunwale98875612018-10-12 07:53:02 -07005473 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5474 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005475
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005476 public H() {
5477 super(DisplayThread.get().getLooper());
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005478 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005479
5480 @Override
5481 public void handleMessage(Message msg) {
5482 switch (msg.what) {
5483 case REPORT_TIME_TRACKER_MSG: {
5484 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5485 tracker.deliverResult(mContext);
5486 } break;
5487 }
5488 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005489 }
5490
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005491 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005493
5494 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005495 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005496 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005497
5498 @Override
5499 public void handleMessage(Message msg) {
5500 switch (msg.what) {
5501 case DISMISS_DIALOG_UI_MSG: {
5502 final Dialog d = (Dialog) msg.obj;
5503 d.dismiss();
5504 break;
5505 }
5506 }
5507 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005508 }
5509
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005510 final class LocalService extends ActivityTaskManagerInternal {
5511 @Override
5512 public SleepToken acquireSleepToken(String tag, int displayId) {
5513 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005514 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005515 }
5516
5517 @Override
5518 public ComponentName getHomeActivityForUser(int userId) {
5519 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005520 ActivityRecord homeActivity =
5521 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005522 return homeActivity == null ? null : homeActivity.realActivity;
5523 }
5524 }
5525
5526 @Override
5527 public void onLocalVoiceInteractionStarted(IBinder activity,
5528 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5529 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005530 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005531 }
5532 }
5533
5534 @Override
5535 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5536 synchronized (mGlobalLock) {
5537 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5538 reasons, timestamp);
5539 }
5540 }
5541
5542 @Override
5543 public void notifyAppTransitionFinished() {
5544 synchronized (mGlobalLock) {
5545 mStackSupervisor.notifyAppTransitionDone();
5546 }
5547 }
5548
5549 @Override
5550 public void notifyAppTransitionCancelled() {
5551 synchronized (mGlobalLock) {
5552 mStackSupervisor.notifyAppTransitionDone();
5553 }
5554 }
5555
5556 @Override
5557 public List<IBinder> getTopVisibleActivities() {
5558 synchronized (mGlobalLock) {
5559 return mStackSupervisor.getTopVisibleActivities();
5560 }
5561 }
5562
5563 @Override
5564 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5565 synchronized (mGlobalLock) {
5566 mStackSupervisor.setDockedStackMinimized(minimized);
5567 }
5568 }
5569
5570 @Override
5571 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5572 Bundle bOptions) {
5573 Preconditions.checkNotNull(intents, "intents");
5574 final String[] resolvedTypes = new String[intents.length];
5575
5576 // UID of the package on user userId.
5577 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5578 // packageUid may not be initialized.
5579 int packageUid = 0;
5580 final long ident = Binder.clearCallingIdentity();
5581
5582 try {
5583 for (int i = 0; i < intents.length; i++) {
5584 resolvedTypes[i] =
5585 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5586 }
5587
5588 packageUid = AppGlobals.getPackageManager().getPackageUid(
5589 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5590 } catch (RemoteException e) {
5591 // Shouldn't happen.
5592 } finally {
5593 Binder.restoreCallingIdentity(ident);
5594 }
5595
5596 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005597 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005598 packageUid, packageName,
5599 intents, resolvedTypes, null /* resultTo */,
5600 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005601 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005602 }
5603 }
5604
5605 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005606 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5607 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5608 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5609 synchronized (mGlobalLock) {
5610 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5611 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5612 originatingPendingIntent);
5613 }
5614 }
5615
5616 @Override
5617 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5618 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5619 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5620 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5621 PendingIntentRecord originatingPendingIntent) {
5622 synchronized (mGlobalLock) {
5623 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5624 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5625 requestCode, startFlags, options, userId, inTask, reason,
5626 validateIncomingUser, originatingPendingIntent);
5627 }
5628 }
5629
5630 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005631 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5632 Intent intent, Bundle options, int userId) {
5633 return ActivityTaskManagerService.this.startActivityAsUser(
5634 caller, callerPacakge, intent,
5635 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5636 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5637 false /*validateIncomingUser*/);
5638 }
5639
5640 @Override
lumark588a3e82018-07-20 18:53:54 +08005641 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005642 synchronized (mGlobalLock) {
5643
5644 // We might change the visibilities here, so prepare an empty app transition which
5645 // might be overridden later if we actually change visibilities.
lumark588a3e82018-07-20 18:53:54 +08005646 final DisplayWindowController dwc = mStackSupervisor.getActivityDisplay(displayId)
5647 .getWindowContainerController();
5648 final boolean wasTransitionSet = dwc.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005649 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005650 dwc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005651 }
5652 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5653
5654 // If there was a transition set already we don't want to interfere with it as we
5655 // might be starting it too early.
5656 if (!wasTransitionSet) {
lumark588a3e82018-07-20 18:53:54 +08005657 dwc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005658 }
5659 }
5660 if (callback != null) {
5661 callback.run();
5662 }
5663 }
5664
5665 @Override
5666 public void notifyKeyguardTrustedChanged() {
5667 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005668 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005669 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5670 }
5671 }
5672 }
5673
5674 /**
5675 * Called after virtual display Id is updated by
5676 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5677 * {@param vrVr2dDisplayId}.
5678 */
5679 @Override
5680 public void setVr2dDisplayId(int vr2dDisplayId) {
5681 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5682 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005683 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005684 }
5685 }
5686
5687 @Override
5688 public void setFocusedActivity(IBinder token) {
5689 synchronized (mGlobalLock) {
5690 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5691 if (r == null) {
5692 throw new IllegalArgumentException(
5693 "setFocusedActivity: No activity record matching token=" + token);
5694 }
Louis Chang19443452018-10-09 12:10:21 +08005695 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005696 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005697 }
5698 }
5699 }
5700
5701 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005702 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005703 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005704 }
5705
5706 @Override
5707 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005708 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005709 }
5710
5711 @Override
5712 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005713 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005714 }
5715
5716 @Override
5717 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5718 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5719 }
5720
5721 @Override
5722 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005723 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005724 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005725
5726 @Override
5727 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5728 synchronized (mGlobalLock) {
5729 mActiveVoiceInteractionServiceComponent = component;
5730 }
5731 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005732
5733 @Override
5734 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5735 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5736 return;
5737 }
5738 synchronized (mGlobalLock) {
5739 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5740 if (types == null) {
5741 if (uid < 0) {
5742 return;
5743 }
5744 types = new ArrayMap<>();
5745 mAllowAppSwitchUids.put(userId, types);
5746 }
5747 if (uid < 0) {
5748 types.remove(type);
5749 } else {
5750 types.put(type, uid);
5751 }
5752 }
5753 }
5754
5755 @Override
5756 public void onUserStopped(int userId) {
5757 synchronized (mGlobalLock) {
5758 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5759 mAllowAppSwitchUids.remove(userId);
5760 }
5761 }
5762
5763 @Override
5764 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5765 synchronized (mGlobalLock) {
5766 return ActivityTaskManagerService.this.isGetTasksAllowed(
5767 caller, callingPid, callingUid);
5768 }
5769 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005770
5771 @Override
5772 public void onProcessAdded(WindowProcessController proc) {
5773 synchronized (mGlobalLock) {
5774 mProcessNames.put(proc.mName, proc.mUid, proc);
5775 }
5776 }
5777
5778 @Override
5779 public void onProcessRemoved(String name, int uid) {
5780 synchronized (mGlobalLock) {
5781 mProcessNames.remove(name, uid);
5782 }
5783 }
5784
5785 @Override
5786 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5787 synchronized (mGlobalLock) {
5788 if (proc == mHomeProcess) {
5789 mHomeProcess = null;
5790 }
5791 if (proc == mPreviousProcess) {
5792 mPreviousProcess = null;
5793 }
5794 }
5795 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005796
5797 @Override
5798 public int getTopProcessState() {
5799 synchronized (mGlobalLock) {
5800 return mTopProcessState;
5801 }
5802 }
5803
5804 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005805 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5806 synchronized (mGlobalLock) {
5807 return proc == mHeavyWeightProcess;
5808 }
5809 }
5810
5811 @Override
5812 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5813 synchronized (mGlobalLock) {
5814 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5815 }
5816 }
5817
5818 @Override
5819 public void finishHeavyWeightApp() {
5820 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005821 if (mHeavyWeightProcess != null) {
5822 mHeavyWeightProcess.finishActivities();
5823 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005824 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5825 mHeavyWeightProcess);
5826 }
5827 }
5828
5829 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005830 public boolean isSleeping() {
5831 synchronized (mGlobalLock) {
5832 return isSleepingLocked();
5833 }
5834 }
5835
5836 @Override
5837 public boolean isShuttingDown() {
5838 synchronized (mGlobalLock) {
5839 return mShuttingDown;
5840 }
5841 }
5842
5843 @Override
5844 public boolean shuttingDown(boolean booted, int timeout) {
5845 synchronized (mGlobalLock) {
5846 mShuttingDown = true;
5847 mStackSupervisor.prepareForShutdownLocked();
5848 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005849 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005850 return mStackSupervisor.shutdownLocked(timeout);
5851 }
5852 }
5853
5854 @Override
5855 public void enableScreenAfterBoot(boolean booted) {
5856 synchronized (mGlobalLock) {
5857 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5858 SystemClock.uptimeMillis());
5859 mWindowManager.enableScreenAfterBoot();
5860 updateEventDispatchingLocked(booted);
5861 }
5862 }
5863
5864 @Override
5865 public boolean showStrictModeViolationDialog() {
5866 synchronized (mGlobalLock) {
5867 return mShowDialogs && !mSleeping && !mShuttingDown;
5868 }
5869 }
5870
5871 @Override
5872 public void showSystemReadyErrorDialogsIfNeeded() {
5873 synchronized (mGlobalLock) {
5874 try {
5875 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5876 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5877 + " data partition or your device will be unstable.");
5878 mUiHandler.post(() -> {
5879 if (mShowDialogs) {
5880 AlertDialog d = new BaseErrorDialog(mUiContext);
5881 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5882 d.setCancelable(false);
5883 d.setTitle(mUiContext.getText(R.string.android_system_label));
5884 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5885 d.setButton(DialogInterface.BUTTON_POSITIVE,
5886 mUiContext.getText(R.string.ok),
5887 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5888 d.show();
5889 }
5890 });
5891 }
5892 } catch (RemoteException e) {
5893 }
5894
5895 if (!Build.isBuildConsistent()) {
5896 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5897 mUiHandler.post(() -> {
5898 if (mShowDialogs) {
5899 AlertDialog d = new BaseErrorDialog(mUiContext);
5900 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5901 d.setCancelable(false);
5902 d.setTitle(mUiContext.getText(R.string.android_system_label));
5903 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5904 d.setButton(DialogInterface.BUTTON_POSITIVE,
5905 mUiContext.getText(R.string.ok),
5906 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5907 d.show();
5908 }
5909 });
5910 }
5911 }
5912 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005913
5914 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005915 public void onProcessMapped(int pid, WindowProcessController proc) {
5916 synchronized (mGlobalLock) {
5917 mPidMap.put(pid, proc);
5918 }
5919 }
5920
5921 @Override
5922 public void onProcessUnMapped(int pid) {
5923 synchronized (mGlobalLock) {
5924 mPidMap.remove(pid);
5925 }
5926 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07005927
5928 @Override
5929 public void onPackageDataCleared(String name) {
5930 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07005931 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07005932 mAppWarnings.onPackageDataCleared(name);
5933 }
5934 }
5935
5936 @Override
5937 public void onPackageUninstalled(String name) {
5938 synchronized (mGlobalLock) {
5939 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07005940 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07005941 }
5942 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005943
5944 @Override
5945 public void onPackageAdded(String name, boolean replacing) {
5946 synchronized (mGlobalLock) {
5947 mCompatModePackages.handlePackageAddedLocked(name, replacing);
5948 }
5949 }
5950
5951 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07005952 public void onPackageReplaced(ApplicationInfo aInfo) {
5953 synchronized (mGlobalLock) {
5954 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
5955 }
5956 }
5957
5958 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005959 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
5960 synchronized (mGlobalLock) {
5961 return compatibilityInfoForPackageLocked(ai);
5962 }
5963 }
5964
Yunfan Chen75157d72018-07-27 14:47:21 +09005965 /**
5966 * Set the corresponding display information for the process global configuration. To be
5967 * called when we need to show IME on a different display.
5968 *
5969 * @param pid The process id associated with the IME window.
5970 * @param displayId The ID of the display showing the IME.
5971 */
5972 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07005973 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005974 if (pid == MY_PID || pid < 0) {
5975 if (DEBUG_CONFIGURATION) {
5976 Slog.w(TAG,
5977 "Trying to update display configuration for system/invalid process.");
5978 }
5979 return;
5980 }
5981 mH.post(() -> {
5982 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005983 final ActivityDisplay activityDisplay =
5984 mStackSupervisor.getActivityDisplay(displayId);
5985 if (activityDisplay == null) {
5986 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09005987 if (DEBUG_CONFIGURATION) {
5988 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07005989 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09005990 }
5991 return;
5992 }
Yunfan Chen79b96062018-10-17 12:45:23 -07005993 final WindowProcessController process = mPidMap.get(pid);
5994 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09005995 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005996 Slog.w(TAG, "Trying to update display configuration for invalid "
5997 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09005998 }
5999 return;
6000 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006001 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006002 }
6003 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006004
Yunfan Chen75157d72018-07-27 14:47:21 +09006005 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006006
6007 @Override
6008 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6009 int requestCode, int resultCode, Intent data) {
6010 synchronized (mGlobalLock) {
6011 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6012 if (r != null && r.getStack() != null) {
6013 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6014 resultCode, data);
6015 }
6016 }
6017 }
6018
6019 @Override
6020 public void clearPendingResultForActivity(IBinder activityToken,
6021 WeakReference<PendingIntentRecord> pir) {
6022 synchronized (mGlobalLock) {
6023 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6024 if (r != null && r.pendingResults != null) {
6025 r.pendingResults.remove(pir);
6026 }
6027 }
6028 }
6029
6030 @Override
6031 public IIntentSender getIntentSender(int type, String packageName,
6032 int callingUid, int userId, IBinder token, String resultWho,
6033 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6034 Bundle bOptions) {
6035 synchronized (mGlobalLock) {
6036 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6037 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6038 }
6039 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006040
6041 @Override
6042 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6043 synchronized (mGlobalLock) {
6044 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6045 if (r == null) {
6046 return null;
6047 }
6048 if (r.mServiceConnectionsHolder == null) {
6049 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6050 ActivityTaskManagerService.this, r);
6051 }
6052
6053 return r.mServiceConnectionsHolder;
6054 }
6055 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006056
6057 @Override
6058 public Intent getHomeIntent() {
6059 synchronized (mGlobalLock) {
6060 return ActivityTaskManagerService.this.getHomeIntent();
6061 }
6062 }
6063
6064 @Override
6065 public boolean startHomeActivity(int userId, String reason) {
6066 synchronized (mGlobalLock) {
Louis Chang89f43fc2018-10-05 10:59:14 +08006067 return mStackSupervisor.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
6068 }
6069 }
6070
6071 @Override
6072 public boolean startHomeOnAllDisplays(int userId, String reason) {
6073 synchronized (mGlobalLock) {
6074 return mStackSupervisor.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006075 }
6076 }
6077
6078 @Override
6079 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6080 synchronized (mGlobalLock) {
6081 if (mFactoryTest == FACTORY_TEST_OFF) {
6082 return false;
6083 }
6084 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6085 && wpc.mName.equals(mTopComponent.getPackageName())) {
6086 return true;
6087 }
6088 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6089 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6090 }
6091 }
6092
6093 @Override
6094 public void updateTopComponentForFactoryTest() {
6095 synchronized (mGlobalLock) {
6096 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6097 return;
6098 }
6099 final ResolveInfo ri = mContext.getPackageManager()
6100 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6101 final CharSequence errorMsg;
6102 if (ri != null) {
6103 final ActivityInfo ai = ri.activityInfo;
6104 final ApplicationInfo app = ai.applicationInfo;
6105 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6106 mTopAction = Intent.ACTION_FACTORY_TEST;
6107 mTopData = null;
6108 mTopComponent = new ComponentName(app.packageName, ai.name);
6109 errorMsg = null;
6110 } else {
6111 errorMsg = mContext.getResources().getText(
6112 com.android.internal.R.string.factorytest_not_system);
6113 }
6114 } else {
6115 errorMsg = mContext.getResources().getText(
6116 com.android.internal.R.string.factorytest_no_action);
6117 }
6118 if (errorMsg == null) {
6119 return;
6120 }
6121
6122 mTopAction = null;
6123 mTopData = null;
6124 mTopComponent = null;
6125 mUiHandler.post(() -> {
6126 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6127 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006128 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006129 });
6130 }
6131 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006132
6133 @Override
6134 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6135 Runnable finishInstrumentationCallback) {
6136 synchronized (mGlobalLock) {
6137 // Remove this application's activities from active lists.
6138 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6139
6140 wpc.clearRecentTasks();
6141 wpc.clearActivities();
6142
6143 if (wpc.isInstrumenting()) {
6144 finishInstrumentationCallback.run();
6145 }
6146
6147 mWindowManager.deferSurfaceLayout();
6148 try {
6149 if (!restarting && hasVisibleActivities
6150 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6151 // If there was nothing to resume, and we are not already restarting this
6152 // process, but there is a visible activity that is hosted by the process...
6153 // then make sure all visible activities are running, taking care of
6154 // restarting this process.
6155 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6156 }
6157 } finally {
6158 mWindowManager.continueSurfaceLayout();
6159 }
6160 }
6161 }
6162
6163 @Override
6164 public void closeSystemDialogs(String reason) {
6165 enforceNotIsolatedCaller("closeSystemDialogs");
6166
6167 final int pid = Binder.getCallingPid();
6168 final int uid = Binder.getCallingUid();
6169 final long origId = Binder.clearCallingIdentity();
6170 try {
6171 synchronized (mGlobalLock) {
6172 // Only allow this from foreground processes, so that background
6173 // applications can't abuse it to prevent system UI from being shown.
6174 if (uid >= FIRST_APPLICATION_UID) {
6175 final WindowProcessController proc = mPidMap.get(pid);
6176 if (!proc.isPerceptible()) {
6177 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6178 + " from background process " + proc);
6179 return;
6180 }
6181 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006182 mWindowManager.closeSystemDialogs(reason);
6183
6184 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006185 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006186 // Call into AM outside the synchronized block.
6187 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006188 } finally {
6189 Binder.restoreCallingIdentity(origId);
6190 }
6191 }
6192
6193 @Override
6194 public void cleanupDisabledPackageComponents(
6195 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6196 synchronized (mGlobalLock) {
6197 // Clean-up disabled activities.
6198 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6199 packageName, disabledClasses, true, false, userId) && booted) {
6200 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6201 mStackSupervisor.scheduleIdleLocked();
6202 }
6203
6204 // Clean-up disabled tasks
6205 getRecentTasks().cleanupDisabledPackageTasksLocked(
6206 packageName, disabledClasses, userId);
6207 }
6208 }
6209
6210 @Override
6211 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6212 int userId) {
6213 synchronized (mGlobalLock) {
6214
6215 boolean didSomething =
6216 getActivityStartController().clearPendingActivityLaunches(packageName);
6217 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6218 null, doit, evenPersistent, userId);
6219 return didSomething;
6220 }
6221 }
6222
6223 @Override
6224 public void resumeTopActivities(boolean scheduleIdle) {
6225 synchronized (mGlobalLock) {
6226 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6227 if (scheduleIdle) {
6228 mStackSupervisor.scheduleIdleLocked();
6229 }
6230 }
6231 }
6232
6233 @Override
6234 public void preBindApplication(WindowProcessController wpc) {
6235 synchronized (mGlobalLock) {
6236 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6237 }
6238 }
6239
6240 @Override
6241 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6242 synchronized (mGlobalLock) {
6243 return mStackSupervisor.attachApplicationLocked(wpc);
6244 }
6245 }
6246
6247 @Override
6248 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6249 try {
6250 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6251 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6252 }
6253 } catch (RemoteException ex) {
6254 throw new SecurityException("Fail to check is caller a privileged app", ex);
6255 }
6256
6257 synchronized (mGlobalLock) {
6258 final long ident = Binder.clearCallingIdentity();
6259 try {
6260 if (mAmInternal.shouldConfirmCredentials(userId)) {
6261 if (mKeyguardController.isKeyguardLocked()) {
6262 // Showing launcher to avoid user entering credential twice.
6263 startHomeActivity(currentUserId, "notifyLockedProfile");
6264 }
6265 mStackSupervisor.lockAllProfileTasks(userId);
6266 }
6267 } finally {
6268 Binder.restoreCallingIdentity(ident);
6269 }
6270 }
6271 }
6272
6273 @Override
6274 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6275 mAmInternal.enforceCallingPermission(
6276 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6277
6278 synchronized (mGlobalLock) {
6279 final long ident = Binder.clearCallingIdentity();
6280 try {
6281 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6282 FLAG_ACTIVITY_TASK_ON_HOME);
6283 ActivityOptions activityOptions = options != null
6284 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006285 final ActivityRecord homeActivity =
6286 mStackSupervisor.getDefaultDisplayHomeActivity();
6287 if (homeActivity != null) {
6288 activityOptions.setLaunchTaskId(homeActivity.getTask().taskId);
6289 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006290 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6291 UserHandle.CURRENT);
6292 } finally {
6293 Binder.restoreCallingIdentity(ident);
6294 }
6295 }
6296 }
6297
6298 @Override
6299 public void writeActivitiesToProto(ProtoOutputStream proto) {
6300 synchronized (mGlobalLock) {
6301 // The output proto of "activity --proto activities"
6302 // is ActivityManagerServiceDumpActivitiesProto
6303 mStackSupervisor.writeToProto(proto,
6304 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6305 }
6306 }
6307
6308 @Override
6309 public void saveANRState(String reason) {
6310 synchronized (mGlobalLock) {
6311 final StringWriter sw = new StringWriter();
6312 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6313 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6314 if (reason != null) {
6315 pw.println(" Reason: " + reason);
6316 }
6317 pw.println();
6318 getActivityStartController().dump(pw, " ", null);
6319 pw.println();
6320 pw.println("-------------------------------------------------------------------------------");
6321 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6322 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6323 "" /* header */);
6324 pw.println();
6325 pw.close();
6326
6327 mLastANRState = sw.toString();
6328 }
6329 }
6330
6331 @Override
6332 public void clearSavedANRState() {
6333 synchronized (mGlobalLock) {
6334 mLastANRState = null;
6335 }
6336 }
6337
6338 @Override
6339 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6340 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6341 synchronized (mGlobalLock) {
6342 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6343 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6344 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6345 dumpLastANRLocked(pw);
6346 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6347 dumpLastANRTracesLocked(pw);
6348 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6349 dumpActivityStarterLocked(pw, dumpPackage);
6350 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6351 dumpActivityContainersLocked(pw);
6352 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6353 if (getRecentTasks() != null) {
6354 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6355 }
6356 }
6357 }
6358 }
6359
6360 @Override
6361 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6362 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6363 int wakefulness) {
6364 synchronized (mGlobalLock) {
6365 if (mHomeProcess != null && (dumpPackage == null
6366 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6367 if (needSep) {
6368 pw.println();
6369 needSep = false;
6370 }
6371 pw.println(" mHomeProcess: " + mHomeProcess);
6372 }
6373 if (mPreviousProcess != null && (dumpPackage == null
6374 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6375 if (needSep) {
6376 pw.println();
6377 needSep = false;
6378 }
6379 pw.println(" mPreviousProcess: " + mPreviousProcess);
6380 }
6381 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6382 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6383 StringBuilder sb = new StringBuilder(128);
6384 sb.append(" mPreviousProcessVisibleTime: ");
6385 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6386 pw.println(sb);
6387 }
6388 if (mHeavyWeightProcess != null && (dumpPackage == null
6389 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6390 if (needSep) {
6391 pw.println();
6392 needSep = false;
6393 }
6394 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6395 }
6396 if (dumpPackage == null) {
6397 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6398 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6399 }
6400 if (dumpAll) {
6401 if (dumpPackage == null) {
6402 pw.println(" mConfigWillChange: "
6403 + getTopDisplayFocusedStack().mConfigWillChange);
6404 }
6405 if (mCompatModePackages.getPackages().size() > 0) {
6406 boolean printed = false;
6407 for (Map.Entry<String, Integer> entry
6408 : mCompatModePackages.getPackages().entrySet()) {
6409 String pkg = entry.getKey();
6410 int mode = entry.getValue();
6411 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6412 continue;
6413 }
6414 if (!printed) {
6415 pw.println(" mScreenCompatPackages:");
6416 printed = true;
6417 }
6418 pw.println(" " + pkg + ": " + mode);
6419 }
6420 }
6421 }
6422
6423 if (dumpPackage == null) {
6424 pw.println(" mWakefulness="
6425 + PowerManagerInternal.wakefulnessToString(wakefulness));
6426 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6427 if (mRunningVoice != null) {
6428 pw.println(" mRunningVoice=" + mRunningVoice);
6429 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6430 }
6431 pw.println(" mSleeping=" + mSleeping);
6432 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6433 pw.println(" mVrController=" + mVrController);
6434 }
6435 if (mCurAppTimeTracker != null) {
6436 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6437 }
6438 if (mAllowAppSwitchUids.size() > 0) {
6439 boolean printed = false;
6440 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6441 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6442 for (int j = 0; j < types.size(); j++) {
6443 if (dumpPackage == null ||
6444 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6445 if (needSep) {
6446 pw.println();
6447 needSep = false;
6448 }
6449 if (!printed) {
6450 pw.println(" mAllowAppSwitchUids:");
6451 printed = true;
6452 }
6453 pw.print(" User ");
6454 pw.print(mAllowAppSwitchUids.keyAt(i));
6455 pw.print(": Type ");
6456 pw.print(types.keyAt(j));
6457 pw.print(" = ");
6458 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6459 pw.println();
6460 }
6461 }
6462 }
6463 }
6464 if (dumpPackage == null) {
6465 if (mController != null) {
6466 pw.println(" mController=" + mController
6467 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6468 }
6469 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6470 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6471 }
6472
6473 return needSep;
6474 }
6475 }
6476
6477 @Override
6478 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6479 synchronized (mGlobalLock) {
6480 if (dumpPackage == null) {
6481 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6482 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6483 writeSleepStateToProto(proto);
6484 if (mController != null) {
6485 final long token = proto.start(CONTROLLER);
6486 proto.write(CONTROLLER, mController.toString());
6487 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6488 proto.end(token);
6489 }
6490 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6491 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6492 }
6493
6494 if (mHomeProcess != null && (dumpPackage == null
6495 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006496 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006497 }
6498
6499 if (mPreviousProcess != null && (dumpPackage == null
6500 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006501 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006502 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6503 }
6504
6505 if (mHeavyWeightProcess != null && (dumpPackage == null
6506 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006507 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006508 }
6509
6510 for (Map.Entry<String, Integer> entry
6511 : mCompatModePackages.getPackages().entrySet()) {
6512 String pkg = entry.getKey();
6513 int mode = entry.getValue();
6514 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6515 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6516 proto.write(PACKAGE, pkg);
6517 proto.write(MODE, mode);
6518 proto.end(compatToken);
6519 }
6520 }
6521
6522 if (mCurAppTimeTracker != null) {
6523 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6524 }
6525
6526 }
6527 }
6528
6529 @Override
6530 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6531 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6532 boolean dumpFocusedStackOnly) {
6533 synchronized (mGlobalLock) {
6534 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6535 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6536 }
6537 }
6538
6539 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006540 public void dumpForOom(PrintWriter pw) {
6541 synchronized (mGlobalLock) {
6542 pw.println(" mHomeProcess: " + mHomeProcess);
6543 pw.println(" mPreviousProcess: " + mPreviousProcess);
6544 if (mHeavyWeightProcess != null) {
6545 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6546 }
6547 }
6548 }
6549
6550 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006551 public boolean canGcNow() {
6552 synchronized (mGlobalLock) {
6553 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6554 }
6555 }
6556
6557 @Override
6558 public WindowProcessController getTopApp() {
6559 synchronized (mGlobalLock) {
6560 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6561 return top != null ? top.app : null;
6562 }
6563 }
6564
6565 @Override
6566 public void rankTaskLayersIfNeeded() {
6567 synchronized (mGlobalLock) {
6568 if (mStackSupervisor != null) {
6569 mStackSupervisor.rankTaskLayersIfNeeded();
6570 }
6571 }
6572 }
6573
6574 @Override
6575 public void scheduleDestroyAllActivities(String reason) {
6576 synchronized (mGlobalLock) {
6577 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6578 }
6579 }
6580
6581 @Override
6582 public void removeUser(int userId) {
6583 synchronized (mGlobalLock) {
6584 mStackSupervisor.removeUserLocked(userId);
6585 }
6586 }
6587
6588 @Override
6589 public boolean switchUser(int userId, UserState userState) {
6590 synchronized (mGlobalLock) {
6591 return mStackSupervisor.switchUserLocked(userId, userState);
6592 }
6593 }
6594
6595 @Override
6596 public void onHandleAppCrash(WindowProcessController wpc) {
6597 synchronized (mGlobalLock) {
6598 mStackSupervisor.handleAppCrashLocked(wpc);
6599 }
6600 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006601
6602 @Override
6603 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6604 synchronized (mGlobalLock) {
6605 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6606 }
6607 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006608
6609 @Override
6610 public void onUidActive(int uid, int procState) {
6611 synchronized (mGlobalLock) {
6612 mActiveUids.put(uid, procState);
6613 }
6614 }
6615
6616 @Override
6617 public void onUidInactive(int uid) {
6618 synchronized (mGlobalLock) {
6619 mActiveUids.remove(uid);
6620 }
6621 }
6622
6623 @Override
6624 public void onActiveUidsCleared() {
6625 synchronized (mGlobalLock) {
6626 mActiveUids.clear();
6627 }
6628 }
6629
6630 @Override
6631 public void onUidProcStateChanged(int uid, int procState) {
6632 synchronized (mGlobalLock) {
6633 if (mActiveUids.get(uid) != null) {
6634 mActiveUids.put(uid, procState);
6635 }
6636 }
6637 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006638
6639 @Override
6640 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6641 synchronized (mGlobalLock) {
6642 mPendingTempWhitelist.put(uid, tag);
6643 }
6644 }
6645
6646 @Override
6647 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6648 synchronized (mGlobalLock) {
6649 mPendingTempWhitelist.remove(uid);
6650 }
6651 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006652
6653 @Override
6654 public boolean handleAppCrashInActivityController(String processName, int pid,
6655 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6656 Runnable killCrashingAppCallback) {
6657 synchronized (mGlobalLock) {
6658 if (mController == null) {
6659 return false;
6660 }
6661
6662 try {
6663 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6664 stackTrace)) {
6665 killCrashingAppCallback.run();
6666 return true;
6667 }
6668 } catch (RemoteException e) {
6669 mController = null;
6670 Watchdog.getInstance().setActivityController(null);
6671 }
6672 return false;
6673 }
6674 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006675
6676 @Override
6677 public void removeRecentTasksByPackageName(String packageName, int userId) {
6678 synchronized (mGlobalLock) {
6679 mRecentTasks.removeTasksByPackageName(packageName, userId);
6680 }
6681 }
6682
6683 @Override
6684 public void cleanupRecentTasksForUser(int userId) {
6685 synchronized (mGlobalLock) {
6686 mRecentTasks.cleanupLocked(userId);
6687 }
6688 }
6689
6690 @Override
6691 public void loadRecentTasksForUser(int userId) {
6692 synchronized (mGlobalLock) {
6693 mRecentTasks.loadUserRecentsLocked(userId);
6694 }
6695 }
6696
6697 @Override
6698 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6699 synchronized (mGlobalLock) {
6700 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6701 }
6702 }
6703
6704 @Override
6705 public void flushRecentTasks() {
6706 mRecentTasks.flush();
6707 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006708
6709 @Override
6710 public WindowProcessController getHomeProcess() {
6711 synchronized (mGlobalLock) {
6712 return mHomeProcess;
6713 }
6714 }
6715
6716 @Override
6717 public WindowProcessController getPreviousProcess() {
6718 synchronized (mGlobalLock) {
6719 return mPreviousProcess;
6720 }
6721 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006722
6723 @Override
6724 public void clearLockedTasks(String reason) {
6725 synchronized (mGlobalLock) {
6726 getLockTaskController().clearLockedTasks(reason);
6727 }
6728 }
6729
6730 @Override
6731 public void updateUserConfiguration() {
6732 synchronized (mGlobalLock) {
6733 final Configuration configuration = new Configuration(getGlobalConfiguration());
6734 final int currentUserId = mAmInternal.getCurrentUserId();
6735 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6736 configuration, currentUserId, Settings.System.canWrite(mContext));
6737 updateConfigurationLocked(configuration, null /* starting */,
6738 false /* initLocale */, false /* persistent */, currentUserId,
6739 false /* deferResume */);
6740 }
6741 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006742
6743 @Override
6744 public boolean canShowErrorDialogs() {
6745 synchronized (mGlobalLock) {
6746 return mShowDialogs && !mSleeping && !mShuttingDown
6747 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6748 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6749 mAmInternal.getCurrentUserId())
6750 && !(UserManager.isDeviceInDemoMode(mContext)
6751 && mAmInternal.getCurrentUser().isDemo());
6752 }
6753 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08006754
6755 @Override
6756 public void setProfileApp(String profileApp) {
6757 synchronized (mGlobalLock) {
6758 mProfileApp = profileApp;
6759 }
6760 }
6761
6762 @Override
6763 public void setProfileProc(WindowProcessController wpc) {
6764 synchronized (mGlobalLock) {
6765 mProfileProc = wpc;
6766 }
6767 }
6768
6769 @Override
6770 public void setProfilerInfo(ProfilerInfo profilerInfo) {
6771 synchronized (mGlobalLock) {
6772 mProfilerInfo = profilerInfo;
6773 }
6774 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006775 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07006776}