blob: 0ce71fdd0dfec898531a1415e46a277ec013f660 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
88import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.server.LocalServices;
248import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700249import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700252import com.android.server.am.ActivityManagerService;
253import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
254import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
255import com.android.server.am.AppTimeTracker;
256import com.android.server.am.BaseErrorDialog;
257import com.android.server.am.EventLogTags;
258import com.android.server.am.PendingIntentController;
259import com.android.server.am.PendingIntentRecord;
260import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900261import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700262import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700263import com.android.server.pm.UserManagerService;
264import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700265import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266
Wale Ogunwale31913b52018-10-13 08:29:31 -0700267import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700270import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700273import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700274import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700275import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700277import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700278import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400280import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700283import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Map;
285import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286
287/**
288 * System service for managing activities and their containers (task, stacks, displays,... ).
289 *
290 * {@hide}
291 */
292public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700293 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700295 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
296 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
297 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
298 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
299 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700300 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700302 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700303 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 /** Used to indicate that an app transition should be animated. */
308 static final boolean ANIMATE = true;
309
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700310 /** Hardware-reported OpenGLES version. */
311 final int GL_ES_VERSION;
312
Wale Ogunwale31913b52018-10-13 08:29:31 -0700313 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
314 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
315 public static final String DUMP_LASTANR_CMD = "lastanr" ;
316 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
317 public static final String DUMP_STARTER_CMD = "starter" ;
318 public static final String DUMP_CONTAINERS_CMD = "containers" ;
319 public static final String DUMP_RECENTS_CMD = "recents" ;
320 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
321
Wale Ogunwale64258362018-10-16 15:13:37 -0700322 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
323 public static final int RELAUNCH_REASON_NONE = 0;
324 /** This activity is being relaunched due to windowing mode change. */
325 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
326 /** This activity is being relaunched due to a free-resize operation. */
327 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
328
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700329 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700330
Wale Ogunwalef6733932018-06-27 05:14:34 -0700331 /**
332 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
333 * change at runtime. Use mContext for non-UI purposes.
334 */
335 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700336 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700337 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700338 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700340 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700341 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800342 @VisibleForTesting
343 final 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 Ogunwaled32da472018-11-16 07:19:28 -0800353 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700355 private UserManagerService mUserManager;
356 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700357 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700358 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
359 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700360 /** All processes currently running that might have a window organized by name. */
361 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700362 /** All processes we currently have running mapped by pid */
363 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700364 /** This is the process holding what we currently consider to be the "home" activity. */
365 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700366 /** The currently running heavy-weight process, if any. */
367 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700368 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700369 /**
370 * This is the process holding the activity the user last visited that is in a different process
371 * from the one they are currently in.
372 */
373 WindowProcessController mPreviousProcess;
374 /** The time at which the previous process was last visible. */
375 long mPreviousProcessVisibleTime;
376
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 /** List of intents that were used to start the most recent tasks. */
378 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700379 /** State of external calls telling us if the device is awake or asleep. */
380 private boolean mKeyguardShown = false;
381
382 // Wrapper around VoiceInteractionServiceManager
383 private AssistUtils mAssistUtils;
384
385 // VoiceInteraction session ID that changes for each new request except when
386 // being called for multi-window assist in a single session.
387 private int mViSessionId = 1000;
388
389 // How long to wait in getAssistContextExtras for the activity and foreground services
390 // to respond with the result.
391 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
392
393 // How long top wait when going through the modern assist (which doesn't need to block
394 // on getting this result before starting to launch its UI).
395 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
396
397 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
398 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
399
Alison Cichowlas3e340502018-08-07 17:15:01 -0400400 // Permission tokens are used to temporarily granted a trusted app the ability to call
401 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
402 // showing any appropriate error messages to the user.
403 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
404 10 * MINUTE_IN_MILLIS;
405
406 // How long before the service actually expires a token. This is slightly longer than
407 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
408 // expiration exception.
409 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
410 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
411
412 // How long the service will remember expired tokens, for the purpose of providing error
413 // messaging when a client uses an expired token.
414 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
415 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
416
417 // Activity tokens of system activities that are delegating their call to
418 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
419 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
420
421 // Permission tokens that have expired, but we remember for error reporting.
422 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700424 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
425
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700426 // Keeps track of the active voice interaction service component, notified from
427 // VoiceInteractionManagerService
428 ComponentName mActiveVoiceInteractionServiceComponent;
429
Wale Ogunwalee2172292018-10-25 10:11:10 -0700430 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700431 KeyguardController mKeyguardController;
432 private final ClientLifecycleManager mLifecycleManager;
433 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700434 /** The controller for all operations related to locktask. */
435 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700436 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700437
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700438 boolean mSuppressResizeConfigChanges;
439
440 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
441 new UpdateConfigurationResult();
442
443 static final class UpdateConfigurationResult {
444 // Configuration changes that were updated.
445 int changes;
446 // If the activity was relaunched to match the new configuration.
447 boolean activityRelaunched;
448
449 void reset() {
450 changes = 0;
451 activityRelaunched = false;
452 }
453 }
454
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700455 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700456 private int mConfigurationSeq;
457 // To cache the list of supported system locales
458 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700459
460 /**
461 * Temp object used when global and/or display override configuration is updated. It is also
462 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
463 * anyone...
464 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700465 private Configuration mTempConfig = new Configuration();
466
Wale Ogunwalef6733932018-06-27 05:14:34 -0700467 /** Temporary to avoid allocations. */
468 final StringBuilder mStringBuilder = new StringBuilder(256);
469
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700470 // Amount of time after a call to stopAppSwitches() during which we will
471 // prevent further untrusted switches from happening.
472 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
473
474 /**
475 * The time at which we will allow normal application switches again,
476 * after a call to {@link #stopAppSwitches()}.
477 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700478 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 /**
480 * This is set to true after the first switch after mAppSwitchesAllowedTime
481 * is set; any switches after that will clear the time.
482 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700483 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484
485 IActivityController mController = null;
486 boolean mControllerIsAMonkey = false;
487
Wale Ogunwale214f3482018-10-04 11:00:47 -0700488 final int mFactoryTest;
489
490 /** Used to control how we initialize the service. */
491 ComponentName mTopComponent;
492 String mTopAction = Intent.ACTION_MAIN;
493 String mTopData;
494
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800495 /** Profiling app information. */
496 String mProfileApp = null;
497 WindowProcessController mProfileProc = null;
498 ProfilerInfo mProfilerInfo = null;
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700501 * Dump of the activity state at the time of the last ANR. Cleared after
502 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
503 */
504 String mLastANRState;
505
506 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 * Used to retain an update lock when the foreground activity is in
508 * immersive mode.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
512 /**
513 * Packages that are being allowed to perform unrestricted app switches. Mapping is
514 * User -> Type -> uid.
515 */
516 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
517
518 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700519 private int mThumbnailWidth;
520 private int mThumbnailHeight;
521 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522
523 /**
524 * Flag that indicates if multi-window is enabled.
525 *
526 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
527 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
528 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
529 * At least one of the forms of multi-window must be enabled in order for this flag to be
530 * initialized to 'true'.
531 *
532 * @see #mSupportsSplitScreenMultiWindow
533 * @see #mSupportsFreeformWindowManagement
534 * @see #mSupportsPictureInPicture
535 * @see #mSupportsMultiDisplay
536 */
537 boolean mSupportsMultiWindow;
538 boolean mSupportsSplitScreenMultiWindow;
539 boolean mSupportsFreeformWindowManagement;
540 boolean mSupportsPictureInPicture;
541 boolean mSupportsMultiDisplay;
542 boolean mForceResizableActivities;
543
544 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
545
546 // VR Vr2d Display Id.
547 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700548
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 /**
550 * Set while we are wanting to sleep, to prevent any
551 * activities from being started/resumed.
552 *
553 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
554 *
555 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
556 * while in the sleep state until there is a pending transition out of sleep, in which case
557 * mSleeping is set to false, and remains false while awake.
558 *
559 * Whether mSleeping can quickly toggled between true/false without the device actually
560 * display changing states is undefined.
561 */
562 private boolean mSleeping = false;
563
564 /**
565 * The process state used for processes that are running the top activities.
566 * This changes between TOP and TOP_SLEEPING to following mSleeping.
567 */
568 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
569
570 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
571 // automatically. Important for devices without direct input devices.
572 private boolean mShowDialogs = true;
573
574 /** Set if we are shutting down the system, similar to sleeping. */
575 boolean mShuttingDown = false;
576
577 /**
578 * We want to hold a wake lock while running a voice interaction session, since
579 * this may happen with the screen off and we need to keep the CPU running to
580 * be able to continue to interact with the user.
581 */
582 PowerManager.WakeLock mVoiceWakeLock;
583
584 /**
585 * Set while we are running a voice interaction. This overrides sleeping while it is active.
586 */
587 IVoiceInteractionSession mRunningVoice;
588
589 /**
590 * The last resumed activity. This is identical to the current resumed activity most
591 * of the time but could be different when we're pausing one activity before we resume
592 * another activity.
593 */
594 ActivityRecord mLastResumedActivity;
595
596 /**
597 * The activity that is currently being traced as the active resumed activity.
598 *
599 * @see #updateResumedAppTrace
600 */
601 private @Nullable ActivityRecord mTracedResumedActivity;
602
603 /** If non-null, we are tracking the time the user spends in the currently focused app. */
604 AppTimeTracker mCurAppTimeTracker;
605
Wale Ogunwale008163e2018-07-23 23:11:08 -0700606 private AppWarnings mAppWarnings;
607
Wale Ogunwale53783742018-09-16 10:21:51 -0700608 /**
609 * Packages that the user has asked to have run in screen size
610 * compatibility mode instead of filling the screen.
611 */
612 CompatModePackages mCompatModePackages;
613
Wale Ogunwalef6733932018-06-27 05:14:34 -0700614 private FontScaleSettingObserver mFontScaleSettingObserver;
615
616 private final class FontScaleSettingObserver extends ContentObserver {
617 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
618 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
619
620 public FontScaleSettingObserver() {
621 super(mH);
622 final ContentResolver resolver = mContext.getContentResolver();
623 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
624 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
625 UserHandle.USER_ALL);
626 }
627
628 @Override
629 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
630 if (mFontScaleUri.equals(uri)) {
631 updateFontScaleIfNeeded(userId);
632 } else if (mHideErrorDialogsUri.equals(uri)) {
633 synchronized (mGlobalLock) {
634 updateShouldShowDialogsLocked(getGlobalConfiguration());
635 }
636 }
637 }
638 }
639
Charles Chen8d98dd22018-12-26 17:36:54 +0800640 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
641 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700642 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700643 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700644 mSystemThread = ActivityThread.currentActivityThread();
645 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700646 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800647 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700648 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700649 }
650
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700651 public void onSystemReady() {
652 synchronized (mGlobalLock) {
653 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
654 PackageManager.FEATURE_CANT_SAVE_STATE);
655 mAssistUtils = new AssistUtils(mContext);
656 mVrController.onSystemReady();
657 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700658 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700659 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700660 }
661
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700662 public void onInitPowerManagement() {
663 synchronized (mGlobalLock) {
664 mStackSupervisor.initPowerManagement();
665 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
666 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
667 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
668 mVoiceWakeLock.setReferenceCounted(false);
669 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 mFontScaleSettingObserver = new FontScaleSettingObserver();
674 }
675
Wale Ogunwale59507092018-10-29 09:00:30 -0700676 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700677 final boolean freeformWindowManagement =
678 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
679 || Settings.Global.getInt(
680 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
681
682 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
683 final boolean supportsPictureInPicture = supportsMultiWindow &&
684 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
685 final boolean supportsSplitScreenMultiWindow =
686 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
687 final boolean supportsMultiDisplay = mContext.getPackageManager()
688 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700689 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
690 final boolean forceResizable = Settings.Global.getInt(
691 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700692 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700693
694 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900695 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700696
697 final Configuration configuration = new Configuration();
698 Settings.System.getConfiguration(resolver, configuration);
699 if (forceRtl) {
700 // This will take care of setting the correct layout direction flags
701 configuration.setLayoutDirection(configuration.locale);
702 }
703
704 synchronized (mGlobalLock) {
705 mForceResizableActivities = forceResizable;
706 final boolean multiWindowFormEnabled = freeformWindowManagement
707 || supportsSplitScreenMultiWindow
708 || supportsPictureInPicture
709 || supportsMultiDisplay;
710 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
711 mSupportsMultiWindow = true;
712 mSupportsFreeformWindowManagement = freeformWindowManagement;
713 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
714 mSupportsPictureInPicture = supportsPictureInPicture;
715 mSupportsMultiDisplay = supportsMultiDisplay;
716 } else {
717 mSupportsMultiWindow = false;
718 mSupportsFreeformWindowManagement = false;
719 mSupportsSplitScreenMultiWindow = false;
720 mSupportsPictureInPicture = false;
721 mSupportsMultiDisplay = false;
722 }
723 mWindowManager.setForceResizableTasks(mForceResizableActivities);
724 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700725 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
726 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700727 // This happens before any activities are started, so we can change global configuration
728 // in-place.
729 updateConfigurationLocked(configuration, null, true);
730 final Configuration globalConfig = getGlobalConfiguration();
731 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
732
733 // Load resources only after the current configuration has been set.
734 final Resources res = mContext.getResources();
735 mThumbnailWidth = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_width);
737 mThumbnailHeight = res.getDimensionPixelSize(
738 com.android.internal.R.dimen.thumbnail_height);
739
740 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
741 mFullscreenThumbnailScale = (float) res
742 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
743 (float) globalConfig.screenWidthDp;
744 } else {
745 mFullscreenThumbnailScale = res.getFraction(
746 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
747 }
748 }
749 }
750
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800751 public WindowManagerGlobalLock getGlobalLock() {
752 return mGlobalLock;
753 }
754
Riddle Hsud93a6c42018-11-29 21:50:06 +0800755 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
756 Looper looper) {
757 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700758 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700759 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700760 final File systemDir = SystemServiceManager.ensureSystemDir();
761 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
762 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700763 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700764
765 mTempConfig.setToDefaults();
766 mTempConfig.setLocales(LocaleList.getDefault());
767 mConfigurationSeq = mTempConfig.seq = 1;
768 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800769 mRootActivityContainer = new RootActivityContainer(this);
770 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700771
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700772 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700774 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700775 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700776 mRecentTasks = createRecentTasks();
777 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700779 mKeyguardController = mStackSupervisor.getKeyguardController();
780 }
781
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700782 public void onActivityManagerInternalAdded() {
783 synchronized (mGlobalLock) {
784 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
785 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
786 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700787 }
788
Yunfan Chen75157d72018-07-27 14:47:21 +0900789 int increaseConfigurationSeqLocked() {
790 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
791 return mConfigurationSeq;
792 }
793
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700794 protected ActivityStackSupervisor createStackSupervisor() {
795 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
796 supervisor.initialize();
797 return supervisor;
798 }
799
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700800 public void setWindowManager(WindowManagerService wm) {
801 synchronized (mGlobalLock) {
802 mWindowManager = wm;
803 mLockTaskController.setWindowManager(wm);
804 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800805 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700806 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700807 }
808
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700809 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
810 synchronized (mGlobalLock) {
811 mUsageStatsInternal = usageStatsManager;
812 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700813 }
814
Wale Ogunwalef6733932018-06-27 05:14:34 -0700815 UserManagerService getUserManager() {
816 if (mUserManager == null) {
817 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
818 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
819 }
820 return mUserManager;
821 }
822
823 AppOpsService getAppOpsService() {
824 if (mAppOpsService == null) {
825 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
826 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
827 }
828 return mAppOpsService;
829 }
830
831 boolean hasUserRestriction(String restriction, int userId) {
832 return getUserManager().hasUserRestriction(restriction, userId);
833 }
834
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700835 protected RecentTasks createRecentTasks() {
836 return new RecentTasks(this, mStackSupervisor);
837 }
838
839 RecentTasks getRecentTasks() {
840 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700841 }
842
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700843 ClientLifecycleManager getLifecycleManager() {
844 return mLifecycleManager;
845 }
846
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700847 ActivityStartController getActivityStartController() {
848 return mActivityStartController;
849 }
850
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700851 TaskChangeNotificationController getTaskChangeNotificationController() {
852 return mTaskChangeNotificationController;
853 }
854
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700855 LockTaskController getLockTaskController() {
856 return mLockTaskController;
857 }
858
Yunfan Chen75157d72018-07-27 14:47:21 +0900859 /**
860 * Return the global configuration used by the process corresponding to the input pid. This is
861 * usually the global configuration with some overrides specific to that process.
862 */
863 Configuration getGlobalConfigurationForCallingPid() {
864 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800865 return getGlobalConfigurationForPid(pid);
866 }
867
868 /**
869 * Return the global configuration used by the process corresponding to the given pid.
870 */
871 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900872 if (pid == MY_PID || pid < 0) {
873 return getGlobalConfiguration();
874 }
875 synchronized (mGlobalLock) {
876 final WindowProcessController app = mPidMap.get(pid);
877 return app != null ? app.getConfiguration() : getGlobalConfiguration();
878 }
879 }
880
881 /**
882 * Return the device configuration info used by the process corresponding to the input pid.
883 * The value is consistent with the global configuration for the process.
884 */
885 @Override
886 public ConfigurationInfo getDeviceConfigurationInfo() {
887 ConfigurationInfo config = new ConfigurationInfo();
888 synchronized (mGlobalLock) {
889 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
890 config.reqTouchScreen = globalConfig.touchscreen;
891 config.reqKeyboardType = globalConfig.keyboard;
892 config.reqNavigation = globalConfig.navigation;
893 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
894 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
895 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
896 }
897 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
898 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
899 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
900 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700901 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900902 }
903 return config;
904 }
905
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700906 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700907 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700908 }
909
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700910 public static final class Lifecycle extends SystemService {
911 private final ActivityTaskManagerService mService;
912
913 public Lifecycle(Context context) {
914 super(context);
915 mService = new ActivityTaskManagerService(context);
916 }
917
918 @Override
919 public void onStart() {
920 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700921 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700922 }
923
Garfield Tan891146c2018-10-09 12:14:00 -0700924 @Override
925 public void onUnlockUser(int userId) {
926 synchronized (mService.getGlobalLock()) {
927 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
928 }
929 }
930
931 @Override
932 public void onCleanupUser(int userId) {
933 synchronized (mService.getGlobalLock()) {
934 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
935 }
936 }
937
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700938 public ActivityTaskManagerService getService() {
939 return mService;
940 }
941 }
942
943 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700944 public final int startActivity(IApplicationThread caller, String callingPackage,
945 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
946 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
947 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
948 resultWho, requestCode, startFlags, profilerInfo, bOptions,
949 UserHandle.getCallingUserId());
950 }
951
952 @Override
953 public final int startActivities(IApplicationThread caller, String callingPackage,
954 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
955 int userId) {
956 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700957 enforceNotIsolatedCaller(reason);
958 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700959 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000960 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
961 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
962 reason, null /* originatingPendingIntent */,
963 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700964 }
965
966 @Override
967 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
968 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
969 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
970 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
971 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
972 true /*validateIncomingUser*/);
973 }
974
975 int startActivityAsUser(IApplicationThread caller, String callingPackage,
976 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
977 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
978 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700979 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700980
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700981 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700982 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
983
984 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700985 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700986 .setCaller(caller)
987 .setCallingPackage(callingPackage)
988 .setResolvedType(resolvedType)
989 .setResultTo(resultTo)
990 .setResultWho(resultWho)
991 .setRequestCode(requestCode)
992 .setStartFlags(startFlags)
993 .setProfilerInfo(profilerInfo)
994 .setActivityOptions(bOptions)
995 .setMayWait(userId)
996 .execute();
997
998 }
999
1000 @Override
1001 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1002 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001003 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1004 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001005 // Refuse possible leaked file descriptors
1006 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1007 throw new IllegalArgumentException("File descriptors passed in Intent");
1008 }
1009
1010 if (!(target instanceof PendingIntentRecord)) {
1011 throw new IllegalArgumentException("Bad PendingIntent object");
1012 }
1013
1014 PendingIntentRecord pir = (PendingIntentRecord)target;
1015
1016 synchronized (mGlobalLock) {
1017 // If this is coming from the currently resumed activity, it is
1018 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001019 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001020 if (stack.mResumedActivity != null &&
1021 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001022 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001023 }
1024 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001025 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001027 }
1028
1029 @Override
1030 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1031 Bundle bOptions) {
1032 // Refuse possible leaked file descriptors
1033 if (intent != null && intent.hasFileDescriptors()) {
1034 throw new IllegalArgumentException("File descriptors passed in Intent");
1035 }
1036 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1037
1038 synchronized (mGlobalLock) {
1039 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1040 if (r == null) {
1041 SafeActivityOptions.abort(options);
1042 return false;
1043 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001044 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001045 // The caller is not running... d'oh!
1046 SafeActivityOptions.abort(options);
1047 return false;
1048 }
1049 intent = new Intent(intent);
1050 // The caller is not allowed to change the data.
1051 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1052 // And we are resetting to find the next component...
1053 intent.setComponent(null);
1054
1055 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1056
1057 ActivityInfo aInfo = null;
1058 try {
1059 List<ResolveInfo> resolves =
1060 AppGlobals.getPackageManager().queryIntentActivities(
1061 intent, r.resolvedType,
1062 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1063 UserHandle.getCallingUserId()).getList();
1064
1065 // Look for the original activity in the list...
1066 final int N = resolves != null ? resolves.size() : 0;
1067 for (int i=0; i<N; i++) {
1068 ResolveInfo rInfo = resolves.get(i);
1069 if (rInfo.activityInfo.packageName.equals(r.packageName)
1070 && rInfo.activityInfo.name.equals(r.info.name)) {
1071 // We found the current one... the next matching is
1072 // after it.
1073 i++;
1074 if (i<N) {
1075 aInfo = resolves.get(i).activityInfo;
1076 }
1077 if (debug) {
1078 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1079 + "/" + r.info.name);
1080 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1081 ? "null" : aInfo.packageName + "/" + aInfo.name));
1082 }
1083 break;
1084 }
1085 }
1086 } catch (RemoteException e) {
1087 }
1088
1089 if (aInfo == null) {
1090 // Nobody who is next!
1091 SafeActivityOptions.abort(options);
1092 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1093 return false;
1094 }
1095
1096 intent.setComponent(new ComponentName(
1097 aInfo.applicationInfo.packageName, aInfo.name));
1098 intent.setFlags(intent.getFlags()&~(
1099 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1100 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1101 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1102 FLAG_ACTIVITY_NEW_TASK));
1103
1104 // Okay now we need to start the new activity, replacing the currently running activity.
1105 // This is a little tricky because we want to start the new one as if the current one is
1106 // finished, but not finish the current one first so that there is no flicker.
1107 // And thus...
1108 final boolean wasFinishing = r.finishing;
1109 r.finishing = true;
1110
1111 // Propagate reply information over to the new activity.
1112 final ActivityRecord resultTo = r.resultTo;
1113 final String resultWho = r.resultWho;
1114 final int requestCode = r.requestCode;
1115 r.resultTo = null;
1116 if (resultTo != null) {
1117 resultTo.removeResultsLocked(r, resultWho, requestCode);
1118 }
1119
1120 final long origId = Binder.clearCallingIdentity();
1121 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001122 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001123 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001124 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001125 .setResolvedType(r.resolvedType)
1126 .setActivityInfo(aInfo)
1127 .setResultTo(resultTo != null ? resultTo.appToken : null)
1128 .setResultWho(resultWho)
1129 .setRequestCode(requestCode)
1130 .setCallingPid(-1)
1131 .setCallingUid(r.launchedFromUid)
1132 .setCallingPackage(r.launchedFromPackage)
1133 .setRealCallingPid(-1)
1134 .setRealCallingUid(r.launchedFromUid)
1135 .setActivityOptions(options)
1136 .execute();
1137 Binder.restoreCallingIdentity(origId);
1138
1139 r.finishing = wasFinishing;
1140 if (res != ActivityManager.START_SUCCESS) {
1141 return false;
1142 }
1143 return true;
1144 }
1145 }
1146
1147 @Override
1148 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1149 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1150 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1151 final WaitResult res = new WaitResult();
1152 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001153 enforceNotIsolatedCaller("startActivityAndWait");
1154 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1155 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001156 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001157 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001158 .setCaller(caller)
1159 .setCallingPackage(callingPackage)
1160 .setResolvedType(resolvedType)
1161 .setResultTo(resultTo)
1162 .setResultWho(resultWho)
1163 .setRequestCode(requestCode)
1164 .setStartFlags(startFlags)
1165 .setActivityOptions(bOptions)
1166 .setMayWait(userId)
1167 .setProfilerInfo(profilerInfo)
1168 .setWaitResult(res)
1169 .execute();
1170 }
1171 return res;
1172 }
1173
1174 @Override
1175 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1176 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1177 int startFlags, Configuration config, Bundle bOptions, int userId) {
1178 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001179 enforceNotIsolatedCaller("startActivityWithConfig");
1180 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1181 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001182 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001183 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001184 .setCaller(caller)
1185 .setCallingPackage(callingPackage)
1186 .setResolvedType(resolvedType)
1187 .setResultTo(resultTo)
1188 .setResultWho(resultWho)
1189 .setRequestCode(requestCode)
1190 .setStartFlags(startFlags)
1191 .setGlobalConfiguration(config)
1192 .setActivityOptions(bOptions)
1193 .setMayWait(userId)
1194 .execute();
1195 }
1196 }
1197
Alison Cichowlas3e340502018-08-07 17:15:01 -04001198
1199 @Override
1200 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1201 int callingUid = Binder.getCallingUid();
1202 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1203 throw new SecurityException("Only the system process can request a permission token, "
1204 + "received request from uid: " + callingUid);
1205 }
1206 IBinder permissionToken = new Binder();
1207 synchronized (mGlobalLock) {
1208 mStartActivitySources.put(permissionToken, delegatorToken);
1209 }
1210
1211 Message expireMsg = PooledLambda.obtainMessage(
1212 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1213 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1214
1215 Message forgetMsg = PooledLambda.obtainMessage(
1216 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1217 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1218
1219 return permissionToken;
1220 }
1221
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001222 @Override
1223 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1224 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001225 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1226 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001227 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001228 // permission grants) as any app that may launch one of your own activities. So we only
1229 // allow this in two cases:
1230 // 1) The caller is an activity that is part of the core framework, and then only when it
1231 // is running as the system.
1232 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1233 // can only be requested by a system activity, which may then delegate this call to
1234 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001235 final ActivityRecord sourceRecord;
1236 final int targetUid;
1237 final String targetPackage;
1238 final boolean isResolver;
1239 synchronized (mGlobalLock) {
1240 if (resultTo == null) {
1241 throw new SecurityException("Must be called from an activity");
1242 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001243 final IBinder sourceToken;
1244 if (permissionToken != null) {
1245 // To even attempt to use a permissionToken, an app must also have this signature
1246 // permission.
1247 mAmInternal.enforceCallingPermission(
1248 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1249 "startActivityAsCaller");
1250 // If called with a permissionToken, we want the sourceRecord from the delegator
1251 // activity that requested this token.
1252 sourceToken = mStartActivitySources.remove(permissionToken);
1253 if (sourceToken == null) {
1254 // Invalid permissionToken, check if it recently expired.
1255 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1256 throw new SecurityException("Called with expired permission token: "
1257 + permissionToken);
1258 } else {
1259 throw new SecurityException("Called with invalid permission token: "
1260 + permissionToken);
1261 }
1262 }
1263 } else {
1264 // This method was called directly by the source.
1265 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001266 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001267
Wale Ogunwaled32da472018-11-16 07:19:28 -08001268 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001269 if (sourceRecord == null) {
1270 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001271 }
1272 if (sourceRecord.app == null) {
1273 throw new SecurityException("Called without a process attached to activity");
1274 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001275
1276 // Whether called directly or from a delegate, the source activity must be from the
1277 // android package.
1278 if (!sourceRecord.info.packageName.equals("android")) {
1279 throw new SecurityException("Must be called from an activity that is "
1280 + "declared in the android package");
1281 }
1282
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001283 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001284 // This is still okay, as long as this activity is running under the
1285 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001286 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001287 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001288 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001289 + " must be system uid or original calling uid "
1290 + sourceRecord.launchedFromUid);
1291 }
1292 }
1293 if (ignoreTargetSecurity) {
1294 if (intent.getComponent() == null) {
1295 throw new SecurityException(
1296 "Component must be specified with ignoreTargetSecurity");
1297 }
1298 if (intent.getSelector() != null) {
1299 throw new SecurityException(
1300 "Selector not allowed with ignoreTargetSecurity");
1301 }
1302 }
1303 targetUid = sourceRecord.launchedFromUid;
1304 targetPackage = sourceRecord.launchedFromPackage;
1305 isResolver = sourceRecord.isResolverOrChildActivity();
1306 }
1307
1308 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001309 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001310 }
1311
1312 // TODO: Switch to user app stacks here.
1313 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001314 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001315 .setCallingUid(targetUid)
1316 .setCallingPackage(targetPackage)
1317 .setResolvedType(resolvedType)
1318 .setResultTo(resultTo)
1319 .setResultWho(resultWho)
1320 .setRequestCode(requestCode)
1321 .setStartFlags(startFlags)
1322 .setActivityOptions(bOptions)
1323 .setMayWait(userId)
1324 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1325 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1326 .execute();
1327 } catch (SecurityException e) {
1328 // XXX need to figure out how to propagate to original app.
1329 // A SecurityException here is generally actually a fault of the original
1330 // calling activity (such as a fairly granting permissions), so propagate it
1331 // back to them.
1332 /*
1333 StringBuilder msg = new StringBuilder();
1334 msg.append("While launching");
1335 msg.append(intent.toString());
1336 msg.append(": ");
1337 msg.append(e.getMessage());
1338 */
1339 throw e;
1340 }
1341 }
1342
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001343 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1344 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1345 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1346 }
1347
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001348 @Override
1349 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1350 Intent intent, String resolvedType, IVoiceInteractionSession session,
1351 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1352 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001354 if (session == null || interactor == null) {
1355 throw new NullPointerException("null session or interactor");
1356 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001357 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001359 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001360 .setCallingUid(callingUid)
1361 .setCallingPackage(callingPackage)
1362 .setResolvedType(resolvedType)
1363 .setVoiceSession(session)
1364 .setVoiceInteractor(interactor)
1365 .setStartFlags(startFlags)
1366 .setProfilerInfo(profilerInfo)
1367 .setActivityOptions(bOptions)
1368 .setMayWait(userId)
1369 .execute();
1370 }
1371
1372 @Override
1373 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1374 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001375 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1376 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001377
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001378 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001379 .setCallingUid(callingUid)
1380 .setCallingPackage(callingPackage)
1381 .setResolvedType(resolvedType)
1382 .setActivityOptions(bOptions)
1383 .setMayWait(userId)
1384 .execute();
1385 }
1386
1387 @Override
1388 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1389 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001390 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001391 final int callingPid = Binder.getCallingPid();
1392 final long origId = Binder.clearCallingIdentity();
1393 try {
1394 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001395 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1396 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001397
1398 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001399 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1400 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001401 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1402 recentsUid, assistDataReceiver);
1403 }
1404 } finally {
1405 Binder.restoreCallingIdentity(origId);
1406 }
1407 }
1408
1409 @Override
1410 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001412 "startActivityFromRecents()");
1413
1414 final int callingPid = Binder.getCallingPid();
1415 final int callingUid = Binder.getCallingUid();
1416 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1417 final long origId = Binder.clearCallingIdentity();
1418 try {
1419 synchronized (mGlobalLock) {
1420 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1421 safeOptions);
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(origId);
1425 }
1426 }
1427
1428 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001429 * Public API to check if the client is allowed to start an activity on specified display.
1430 *
1431 * If the target display is private or virtual, some restrictions will apply.
1432 *
1433 * @param displayId Target display id.
1434 * @param intent Intent used to launch the activity.
1435 * @param resolvedType The MIME type of the intent.
1436 * @param userId The id of the user for whom the call is made.
1437 * @return {@code true} if a call to start an activity on the target display should succeed and
1438 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1439 */
1440 @Override
1441 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1442 String resolvedType, int userId) {
1443 final int callingUid = Binder.getCallingUid();
1444 final int callingPid = Binder.getCallingPid();
1445 final long origId = Binder.clearCallingIdentity();
1446
1447 try {
1448 // Collect information about the target of the Intent.
1449 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1450 0 /* startFlags */, null /* profilerInfo */, userId,
1451 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1452 UserHandle.USER_NULL));
1453 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1454
1455 synchronized (mGlobalLock) {
1456 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1457 aInfo);
1458 }
1459 } finally {
1460 Binder.restoreCallingIdentity(origId);
1461 }
1462 }
1463
1464 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001465 * This is the internal entry point for handling Activity.finish().
1466 *
1467 * @param token The Binder token referencing the Activity we want to finish.
1468 * @param resultCode Result code, if any, from this Activity.
1469 * @param resultData Result data (Intent), if any, from this Activity.
1470 * @param finishTask Whether to finish the task associated with this Activity.
1471 *
1472 * @return Returns true if the activity successfully finished, or false if it is still running.
1473 */
1474 @Override
1475 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1476 int finishTask) {
1477 // Refuse possible leaked file descriptors
1478 if (resultData != null && resultData.hasFileDescriptors()) {
1479 throw new IllegalArgumentException("File descriptors passed in Intent");
1480 }
1481
1482 synchronized (mGlobalLock) {
1483 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1484 if (r == null) {
1485 return true;
1486 }
1487 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001488 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001489 ActivityRecord rootR = tr.getRootActivity();
1490 if (rootR == null) {
1491 Slog.w(TAG, "Finishing task with all activities already finished");
1492 }
1493 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1494 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001495 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001496 return false;
1497 }
1498
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001499 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1500 // We should consolidate.
1501 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001502 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001503 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001504 if (next != null) {
1505 // ask watcher if this is allowed
1506 boolean resumeOK = true;
1507 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001508 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001509 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001510 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001511 Watchdog.getInstance().setActivityController(null);
1512 }
1513
1514 if (!resumeOK) {
1515 Slog.i(TAG, "Not finishing activity because controller resumed");
1516 return false;
1517 }
1518 }
1519 }
1520 final long origId = Binder.clearCallingIdentity();
1521 try {
1522 boolean res;
1523 final boolean finishWithRootActivity =
1524 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1525 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1526 || (finishWithRootActivity && r == rootR)) {
1527 // If requested, remove the task that is associated to this activity only if it
1528 // was the root activity in the task. The result code and data is ignored
1529 // because we don't support returning them across task boundaries. Also, to
1530 // keep backwards compatibility we remove the task from recents when finishing
1531 // task with root activity.
1532 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1533 finishWithRootActivity, "finish-activity");
1534 if (!res) {
1535 Slog.i(TAG, "Removing task failed to finish activity");
1536 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001537 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001538 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001539 } else {
1540 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1541 resultData, "app-request", true);
1542 if (!res) {
1543 Slog.i(TAG, "Failed to finish by app-request");
1544 }
1545 }
1546 return res;
1547 } finally {
1548 Binder.restoreCallingIdentity(origId);
1549 }
1550 }
1551 }
1552
1553 @Override
1554 public boolean finishActivityAffinity(IBinder token) {
1555 synchronized (mGlobalLock) {
1556 final long origId = Binder.clearCallingIdentity();
1557 try {
1558 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1559 if (r == null) {
1560 return false;
1561 }
1562
1563 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1564 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001565 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001566 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 return false;
1568 }
1569 return task.getStack().finishActivityAffinityLocked(r);
1570 } finally {
1571 Binder.restoreCallingIdentity(origId);
1572 }
1573 }
1574 }
1575
1576 @Override
1577 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1578 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001579 try {
1580 WindowProcessController proc = null;
1581 synchronized (mGlobalLock) {
1582 ActivityStack stack = ActivityRecord.getStackLocked(token);
1583 if (stack == null) {
1584 return;
1585 }
1586 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1587 false /* fromTimeout */, false /* processPausingActivities */, config);
1588 if (r != null) {
1589 proc = r.app;
1590 }
1591 if (stopProfiling && proc != null) {
1592 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001593 }
1594 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001595 } finally {
1596 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001598 }
1599
1600 @Override
1601 public final void activityResumed(IBinder token) {
1602 final long origId = Binder.clearCallingIdentity();
1603 synchronized (mGlobalLock) {
1604 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001605 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 }
1607 Binder.restoreCallingIdentity(origId);
1608 }
1609
1610 @Override
1611 public final void activityPaused(IBinder token) {
1612 final long origId = Binder.clearCallingIdentity();
1613 synchronized (mGlobalLock) {
1614 ActivityStack stack = ActivityRecord.getStackLocked(token);
1615 if (stack != null) {
1616 stack.activityPausedLocked(token, false);
1617 }
1618 }
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public final void activityStopped(IBinder token, Bundle icicle,
1624 PersistableBundle persistentState, CharSequence description) {
1625 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1626
1627 // Refuse possible leaked file descriptors
1628 if (icicle != null && icicle.hasFileDescriptors()) {
1629 throw new IllegalArgumentException("File descriptors passed in Bundle");
1630 }
1631
1632 final long origId = Binder.clearCallingIdentity();
1633
1634 synchronized (mGlobalLock) {
1635 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1636 if (r != null) {
1637 r.activityStoppedLocked(icicle, persistentState, description);
1638 }
1639 }
1640
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001641 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642
1643 Binder.restoreCallingIdentity(origId);
1644 }
1645
1646 @Override
1647 public final void activityDestroyed(IBinder token) {
1648 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1649 synchronized (mGlobalLock) {
1650 ActivityStack stack = ActivityRecord.getStackLocked(token);
1651 if (stack != null) {
1652 stack.activityDestroyedLocked(token, "activityDestroyed");
1653 }
1654 }
1655 }
1656
1657 @Override
1658 public final void activityRelaunched(IBinder token) {
1659 final long origId = Binder.clearCallingIdentity();
1660 synchronized (mGlobalLock) {
1661 mStackSupervisor.activityRelaunchedLocked(token);
1662 }
1663 Binder.restoreCallingIdentity(origId);
1664 }
1665
1666 public final void activitySlept(IBinder token) {
1667 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1668
1669 final long origId = Binder.clearCallingIdentity();
1670
1671 synchronized (mGlobalLock) {
1672 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1673 if (r != null) {
1674 mStackSupervisor.activitySleptLocked(r);
1675 }
1676 }
1677
1678 Binder.restoreCallingIdentity(origId);
1679 }
1680
1681 @Override
1682 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1683 synchronized (mGlobalLock) {
1684 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1685 if (r == null) {
1686 return;
1687 }
1688 final long origId = Binder.clearCallingIdentity();
1689 try {
1690 r.setRequestedOrientation(requestedOrientation);
1691 } finally {
1692 Binder.restoreCallingIdentity(origId);
1693 }
1694 }
1695 }
1696
1697 @Override
1698 public int getRequestedOrientation(IBinder token) {
1699 synchronized (mGlobalLock) {
1700 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1701 if (r == null) {
1702 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1703 }
1704 return r.getRequestedOrientation();
1705 }
1706 }
1707
1708 @Override
1709 public void setImmersive(IBinder token, boolean immersive) {
1710 synchronized (mGlobalLock) {
1711 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1712 if (r == null) {
1713 throw new IllegalArgumentException();
1714 }
1715 r.immersive = immersive;
1716
1717 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001718 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001719 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001720 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001721 }
1722 }
1723 }
1724
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001725 void applyUpdateLockStateLocked(ActivityRecord r) {
1726 // Modifications to the UpdateLock state are done on our handler, outside
1727 // the activity manager's locks. The new state is determined based on the
1728 // state *now* of the relevant activity record. The object is passed to
1729 // the handler solely for logging detail, not to be consulted/modified.
1730 final boolean nextState = r != null && r.immersive;
1731 mH.post(() -> {
1732 if (mUpdateLock.isHeld() != nextState) {
1733 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1734 "Applying new update lock state '" + nextState + "' for " + r);
1735 if (nextState) {
1736 mUpdateLock.acquire();
1737 } else {
1738 mUpdateLock.release();
1739 }
1740 }
1741 });
1742 }
1743
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001744 @Override
1745 public boolean isImmersive(IBinder token) {
1746 synchronized (mGlobalLock) {
1747 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1748 if (r == null) {
1749 throw new IllegalArgumentException();
1750 }
1751 return r.immersive;
1752 }
1753 }
1754
1755 @Override
1756 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001757 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001758 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001759 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001760 return (r != null) ? r.immersive : false;
1761 }
1762 }
1763
1764 @Override
1765 public void overridePendingTransition(IBinder token, String packageName,
1766 int enterAnim, int exitAnim) {
1767 synchronized (mGlobalLock) {
1768 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1769 if (self == null) {
1770 return;
1771 }
1772
1773 final long origId = Binder.clearCallingIdentity();
1774
1775 if (self.isState(
1776 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001777 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001778 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 }
1780
1781 Binder.restoreCallingIdentity(origId);
1782 }
1783 }
1784
1785 @Override
1786 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001787 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001788 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001789 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001790 if (r == null) {
1791 return ActivityManager.COMPAT_MODE_UNKNOWN;
1792 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001793 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001794 }
1795 }
1796
1797 @Override
1798 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001801 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001802 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001803 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001804 if (r == null) {
1805 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1806 return;
1807 }
1808 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001809 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 }
1811 }
1812
1813 @Override
1814 public int getLaunchedFromUid(IBinder activityToken) {
1815 ActivityRecord srec;
1816 synchronized (mGlobalLock) {
1817 srec = ActivityRecord.forTokenLocked(activityToken);
1818 }
1819 if (srec == null) {
1820 return -1;
1821 }
1822 return srec.launchedFromUid;
1823 }
1824
1825 @Override
1826 public String getLaunchedFromPackage(IBinder activityToken) {
1827 ActivityRecord srec;
1828 synchronized (mGlobalLock) {
1829 srec = ActivityRecord.forTokenLocked(activityToken);
1830 }
1831 if (srec == null) {
1832 return null;
1833 }
1834 return srec.launchedFromPackage;
1835 }
1836
1837 @Override
1838 public boolean convertFromTranslucent(IBinder token) {
1839 final long origId = Binder.clearCallingIdentity();
1840 try {
1841 synchronized (mGlobalLock) {
1842 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1843 if (r == null) {
1844 return false;
1845 }
1846 final boolean translucentChanged = r.changeWindowTranslucency(true);
1847 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001848 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001849 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001850 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001851 return translucentChanged;
1852 }
1853 } finally {
1854 Binder.restoreCallingIdentity(origId);
1855 }
1856 }
1857
1858 @Override
1859 public boolean convertToTranslucent(IBinder token, Bundle options) {
1860 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1861 final long origId = Binder.clearCallingIdentity();
1862 try {
1863 synchronized (mGlobalLock) {
1864 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1865 if (r == null) {
1866 return false;
1867 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001868 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001869 int index = task.mActivities.lastIndexOf(r);
1870 if (index > 0) {
1871 ActivityRecord under = task.mActivities.get(index - 1);
1872 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1873 }
1874 final boolean translucentChanged = r.changeWindowTranslucency(false);
1875 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001876 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001877 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001878 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001879 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001880 return translucentChanged;
1881 }
1882 } finally {
1883 Binder.restoreCallingIdentity(origId);
1884 }
1885 }
1886
1887 @Override
1888 public void notifyActivityDrawn(IBinder token) {
1889 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1890 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001891 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001893 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001894 }
1895 }
1896 }
1897
1898 @Override
1899 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1900 synchronized (mGlobalLock) {
1901 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1902 if (r == null) {
1903 return;
1904 }
1905 r.reportFullyDrawnLocked(restoredFromBundle);
1906 }
1907 }
1908
1909 @Override
1910 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1911 synchronized (mGlobalLock) {
1912 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1913 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1914 return stack.mDisplayId;
1915 }
1916 return DEFAULT_DISPLAY;
1917 }
1918 }
1919
1920 @Override
1921 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001922 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001923 long ident = Binder.clearCallingIdentity();
1924 try {
1925 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001926 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001927 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001928 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001929 }
1930 return null;
1931 }
1932 } finally {
1933 Binder.restoreCallingIdentity(ident);
1934 }
1935 }
1936
1937 @Override
1938 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001939 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001940 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1941 final long callingId = Binder.clearCallingIdentity();
1942 try {
1943 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001944 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001945 if (stack == null) {
1946 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1947 return;
1948 }
1949 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001950 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001951 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 }
1953 }
1954 } finally {
1955 Binder.restoreCallingIdentity(callingId);
1956 }
1957 }
1958
1959 @Override
1960 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001961 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001962 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1963 final long callingId = Binder.clearCallingIdentity();
1964 try {
1965 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001966 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001967 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001968 if (task == null) {
1969 return;
1970 }
1971 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001972 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001973 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 }
1975 }
1976 } finally {
1977 Binder.restoreCallingIdentity(callingId);
1978 }
1979 }
1980
1981 @Override
1982 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001983 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001984 synchronized (mGlobalLock) {
1985 final long ident = Binder.clearCallingIdentity();
1986 try {
1987 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1988 "remove-task");
1989 } finally {
1990 Binder.restoreCallingIdentity(ident);
1991 }
1992 }
1993 }
1994
1995 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001996 public void removeAllVisibleRecentTasks() {
1997 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1998 synchronized (mGlobalLock) {
1999 final long ident = Binder.clearCallingIdentity();
2000 try {
2001 getRecentTasks().removeAllVisibleTasks();
2002 } finally {
2003 Binder.restoreCallingIdentity(ident);
2004 }
2005 }
2006 }
2007
2008 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002009 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2010 synchronized (mGlobalLock) {
2011 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2012 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002013 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002014 }
2015 }
2016 return false;
2017 }
2018
2019 @Override
2020 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2021 Intent resultData) {
2022
2023 synchronized (mGlobalLock) {
2024 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2025 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002026 return r.getActivityStack().navigateUpToLocked(
2027 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002028 }
2029 return false;
2030 }
2031 }
2032
2033 /**
2034 * Attempts to move a task backwards in z-order (the order of activities within the task is
2035 * unchanged).
2036 *
2037 * There are several possible results of this call:
2038 * - if the task is locked, then we will show the lock toast
2039 * - if there is a task behind the provided task, then that task is made visible and resumed as
2040 * this task is moved to the back
2041 * - otherwise, if there are no other tasks in the stack:
2042 * - if this task is in the pinned stack, then we remove the stack completely, which will
2043 * have the effect of moving the task to the top or bottom of the fullscreen stack
2044 * (depending on whether it is visible)
2045 * - otherwise, we simply return home and hide this task
2046 *
2047 * @param token A reference to the activity we wish to move
2048 * @param nonRoot If false then this only works if the activity is the root
2049 * of a task; if true it will work for any activity in a task.
2050 * @return Returns true if the move completed, false if not.
2051 */
2052 @Override
2053 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002054 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002055 synchronized (mGlobalLock) {
2056 final long origId = Binder.clearCallingIdentity();
2057 try {
2058 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002059 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002060 if (task != null) {
2061 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2062 }
2063 } finally {
2064 Binder.restoreCallingIdentity(origId);
2065 }
2066 }
2067 return false;
2068 }
2069
2070 @Override
2071 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002072 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 long ident = Binder.clearCallingIdentity();
2074 Rect rect = new Rect();
2075 try {
2076 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002077 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002078 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2079 if (task == null) {
2080 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2081 return rect;
2082 }
2083 if (task.getStack() != null) {
2084 // Return the bounds from window manager since it will be adjusted for various
2085 // things like the presense of a docked stack for tasks that aren't resizeable.
2086 task.getWindowContainerBounds(rect);
2087 } else {
2088 // Task isn't in window manager yet since it isn't associated with a stack.
2089 // Return the persist value from activity manager
2090 if (!task.matchParentBounds()) {
2091 rect.set(task.getBounds());
2092 } else if (task.mLastNonFullscreenBounds != null) {
2093 rect.set(task.mLastNonFullscreenBounds);
2094 }
2095 }
2096 }
2097 } finally {
2098 Binder.restoreCallingIdentity(ident);
2099 }
2100 return rect;
2101 }
2102
2103 @Override
2104 public ActivityManager.TaskDescription getTaskDescription(int id) {
2105 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002106 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002107 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002108 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002109 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2110 if (tr != null) {
2111 return tr.lastTaskDescription;
2112 }
2113 }
2114 return null;
2115 }
2116
2117 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002118 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2119 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2120 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2121 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2122 return;
2123 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002124 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002125 synchronized (mGlobalLock) {
2126 final long ident = Binder.clearCallingIdentity();
2127 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002128 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002129 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002130 if (task == null) {
2131 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2132 return;
2133 }
2134
2135 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2136 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2137
2138 if (!task.isActivityTypeStandardOrUndefined()) {
2139 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2140 + " non-standard task " + taskId + " to windowing mode="
2141 + windowingMode);
2142 }
2143
2144 final ActivityStack stack = task.getStack();
2145 if (toTop) {
2146 stack.moveToFront("setTaskWindowingMode", task);
2147 }
2148 stack.setWindowingMode(windowingMode);
2149 } finally {
2150 Binder.restoreCallingIdentity(ident);
2151 }
2152 }
2153 }
2154
2155 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002156 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002157 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002158 ActivityRecord r = getCallingRecordLocked(token);
2159 return r != null ? r.info.packageName : null;
2160 }
2161 }
2162
2163 @Override
2164 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002165 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002166 ActivityRecord r = getCallingRecordLocked(token);
2167 return r != null ? r.intent.getComponent() : null;
2168 }
2169 }
2170
2171 private ActivityRecord getCallingRecordLocked(IBinder token) {
2172 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2173 if (r == null) {
2174 return null;
2175 }
2176 return r.resultTo;
2177 }
2178
2179 @Override
2180 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002181 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002182
2183 synchronized (mGlobalLock) {
2184 final long origId = Binder.clearCallingIdentity();
2185 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002186 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002187 } finally {
2188 Binder.restoreCallingIdentity(origId);
2189 }
2190 }
2191 }
2192
2193 /**
2194 * TODO: Add mController hook
2195 */
2196 @Override
2197 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002198 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199
2200 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2201 synchronized (mGlobalLock) {
2202 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2203 false /* fromRecents */);
2204 }
2205 }
2206
2207 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2208 boolean fromRecents) {
2209
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211 Binder.getCallingUid(), -1, -1, "Task to front")) {
2212 SafeActivityOptions.abort(options);
2213 return;
2214 }
2215 final long origId = Binder.clearCallingIdentity();
2216 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002217 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002218 if (task == null) {
2219 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002220 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002221 return;
2222 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002223 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002224 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002225 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002226 return;
2227 }
2228 ActivityOptions realOptions = options != null
2229 ? options.getOptions(mStackSupervisor)
2230 : null;
2231 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2232 false /* forceNonResizable */);
2233
2234 final ActivityRecord topActivity = task.getTopActivity();
2235 if (topActivity != null) {
2236
2237 // We are reshowing a task, use a starting window to hide the initial draw delay
2238 // so the transition can start earlier.
2239 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2240 true /* taskSwitch */, fromRecents);
2241 }
2242 } finally {
2243 Binder.restoreCallingIdentity(origId);
2244 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 }
2246
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002247 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2248 int callingPid, int callingUid, String name) {
2249 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2250 return true;
2251 }
2252
2253 if (getRecentTasks().isCallerRecents(sourceUid)) {
2254 return true;
2255 }
2256
2257 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2258 if (perm == PackageManager.PERMISSION_GRANTED) {
2259 return true;
2260 }
2261 if (checkAllowAppSwitchUid(sourceUid)) {
2262 return true;
2263 }
2264
2265 // If the actual IPC caller is different from the logical source, then
2266 // also see if they are allowed to control app switches.
2267 if (callingUid != -1 && callingUid != sourceUid) {
2268 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2269 if (perm == PackageManager.PERMISSION_GRANTED) {
2270 return true;
2271 }
2272 if (checkAllowAppSwitchUid(callingUid)) {
2273 return true;
2274 }
2275 }
2276
2277 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2278 return false;
2279 }
2280
2281 private boolean checkAllowAppSwitchUid(int uid) {
2282 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2283 if (types != null) {
2284 for (int i = types.size() - 1; i >= 0; i--) {
2285 if (types.valueAt(i).intValue() == uid) {
2286 return true;
2287 }
2288 }
2289 }
2290 return false;
2291 }
2292
2293 @Override
2294 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2295 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2296 "setActivityController()");
2297 synchronized (mGlobalLock) {
2298 mController = controller;
2299 mControllerIsAMonkey = imAMonkey;
2300 Watchdog.getInstance().setActivityController(controller);
2301 }
2302 }
2303
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002304 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002305 synchronized (mGlobalLock) {
2306 return mController != null && mControllerIsAMonkey;
2307 }
2308 }
2309
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002310 @Override
2311 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2312 synchronized (mGlobalLock) {
2313 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2314 }
2315 }
2316
2317 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002318 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2319 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2320 }
2321
2322 @Override
2323 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2324 @WindowConfiguration.ActivityType int ignoreActivityType,
2325 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2326 final int callingUid = Binder.getCallingUid();
2327 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2328
2329 synchronized (mGlobalLock) {
2330 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2331
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002332 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002333 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002334 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002335 ignoreWindowingMode, callingUid, allowed);
2336 }
2337
2338 return list;
2339 }
2340
2341 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002342 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2343 synchronized (mGlobalLock) {
2344 final long origId = Binder.clearCallingIdentity();
2345 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2346 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002347 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002348 }
2349 Binder.restoreCallingIdentity(origId);
2350 }
2351 }
2352
2353 @Override
2354 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002355 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002356 ActivityStack stack = ActivityRecord.getStackLocked(token);
2357 if (stack != null) {
2358 return stack.willActivityBeVisibleLocked(token);
2359 }
2360 return false;
2361 }
2362 }
2363
2364 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002365 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002366 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002367 synchronized (mGlobalLock) {
2368 final long ident = Binder.clearCallingIdentity();
2369 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002370 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002371 if (task == null) {
2372 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2373 return;
2374 }
2375
2376 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2377 + " to stackId=" + stackId + " toTop=" + toTop);
2378
Wale Ogunwaled32da472018-11-16 07:19:28 -08002379 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002380 if (stack == null) {
2381 throw new IllegalStateException(
2382 "moveTaskToStack: No stack for stackId=" + stackId);
2383 }
2384 if (!stack.isActivityTypeStandardOrUndefined()) {
2385 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2386 + taskId + " to stack " + stackId);
2387 }
2388 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002389 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002390 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2391 }
2392 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2393 "moveTaskToStack");
2394 } finally {
2395 Binder.restoreCallingIdentity(ident);
2396 }
2397 }
2398 }
2399
2400 @Override
2401 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2402 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002403 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002404
2405 final long ident = Binder.clearCallingIdentity();
2406 try {
2407 synchronized (mGlobalLock) {
2408 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002409 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002410 if (stack == null) {
2411 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2412 return;
2413 }
2414 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2415 throw new IllegalArgumentException("Stack: " + stackId
2416 + " doesn't support animated resize.");
2417 }
2418 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2419 animationDuration, false /* fromFullscreen */);
2420 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002421 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422 if (stack == null) {
2423 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2424 return;
2425 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002426 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002427 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2428 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2429 }
2430 }
2431 } finally {
2432 Binder.restoreCallingIdentity(ident);
2433 }
2434 }
2435
2436 /**
2437 * Moves the specified task to the primary-split-screen stack.
2438 *
2439 * @param taskId Id of task to move.
2440 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2441 * exist already. See
2442 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2443 * and
2444 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2445 * @param toTop If the task and stack should be moved to the top.
2446 * @param animate Whether we should play an animation for the moving the task.
2447 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2448 * stack. Pass {@code null} to use default bounds.
2449 * @param showRecents If the recents activity should be shown on the other side of the task
2450 * going into split-screen mode.
2451 */
2452 @Override
2453 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2454 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002455 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002456 "setTaskWindowingModeSplitScreenPrimary()");
2457 synchronized (mGlobalLock) {
2458 final long ident = Binder.clearCallingIdentity();
2459 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002460 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002461 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002462 if (task == null) {
2463 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2464 return false;
2465 }
2466 if (DEBUG_STACK) Slog.d(TAG_STACK,
2467 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2468 + " to createMode=" + createMode + " toTop=" + toTop);
2469 if (!task.isActivityTypeStandardOrUndefined()) {
2470 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2471 + " non-standard task " + taskId + " to split-screen windowing mode");
2472 }
2473
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002474 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002475 final int windowingMode = task.getWindowingMode();
2476 final ActivityStack stack = task.getStack();
2477 if (toTop) {
2478 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2479 }
2480 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002481 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2482 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002483 return windowingMode != task.getWindowingMode();
2484 } finally {
2485 Binder.restoreCallingIdentity(ident);
2486 }
2487 }
2488 }
2489
2490 /**
2491 * Removes stacks in the input windowing modes from the system if they are of activity type
2492 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2493 */
2494 @Override
2495 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002496 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002497 "removeStacksInWindowingModes()");
2498
2499 synchronized (mGlobalLock) {
2500 final long ident = Binder.clearCallingIdentity();
2501 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002502 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002503 } finally {
2504 Binder.restoreCallingIdentity(ident);
2505 }
2506 }
2507 }
2508
2509 @Override
2510 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002511 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002512 "removeStacksWithActivityTypes()");
2513
2514 synchronized (mGlobalLock) {
2515 final long ident = Binder.clearCallingIdentity();
2516 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002517 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002518 } finally {
2519 Binder.restoreCallingIdentity(ident);
2520 }
2521 }
2522 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002523
2524 @Override
2525 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2526 int userId) {
2527 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002528 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2529 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002530 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002531 final boolean detailed = checkGetTasksPermission(
2532 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2533 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002534 == PackageManager.PERMISSION_GRANTED;
2535
2536 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002537 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002538 callingUid);
2539 }
2540 }
2541
2542 @Override
2543 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002544 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002545 long ident = Binder.clearCallingIdentity();
2546 try {
2547 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002548 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002549 }
2550 } finally {
2551 Binder.restoreCallingIdentity(ident);
2552 }
2553 }
2554
2555 @Override
2556 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002558 long ident = Binder.clearCallingIdentity();
2559 try {
2560 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002561 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002562 }
2563 } finally {
2564 Binder.restoreCallingIdentity(ident);
2565 }
2566 }
2567
2568 @Override
2569 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002570 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002571 final long callingUid = Binder.getCallingUid();
2572 final long origId = Binder.clearCallingIdentity();
2573 try {
2574 synchronized (mGlobalLock) {
2575 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002576 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002577 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2578 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2579 }
2580 } finally {
2581 Binder.restoreCallingIdentity(origId);
2582 }
2583 }
2584
2585 @Override
2586 public void startLockTaskModeByToken(IBinder token) {
2587 synchronized (mGlobalLock) {
2588 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2589 if (r == null) {
2590 return;
2591 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002592 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002593 }
2594 }
2595
2596 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002597 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002598 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002599 // This makes inner call to look as if it was initiated by system.
2600 long ident = Binder.clearCallingIdentity();
2601 try {
2602 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002603 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002604 MATCH_TASK_IN_STACKS_ONLY);
2605 if (task == null) {
2606 return;
2607 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002608
2609 // When starting lock task mode the stack must be in front and focused
2610 task.getStack().moveToFront("startSystemLockTaskMode");
2611 startLockTaskModeLocked(task, true /* isSystemCaller */);
2612 }
2613 } finally {
2614 Binder.restoreCallingIdentity(ident);
2615 }
2616 }
2617
2618 @Override
2619 public void stopLockTaskModeByToken(IBinder token) {
2620 synchronized (mGlobalLock) {
2621 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2622 if (r == null) {
2623 return;
2624 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002625 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002626 }
2627 }
2628
2629 /**
2630 * This API should be called by SystemUI only when user perform certain action to dismiss
2631 * lock task mode. We should only dismiss pinned lock task mode in this case.
2632 */
2633 @Override
2634 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002635 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002636 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2637 }
2638
2639 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2640 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2641 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2642 return;
2643 }
2644
Wale Ogunwaled32da472018-11-16 07:19:28 -08002645 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002646 if (stack == null || task != stack.topTask()) {
2647 throw new IllegalArgumentException("Invalid task, not in foreground");
2648 }
2649
2650 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2651 // system or a specific app.
2652 // * System-initiated requests will only start the pinned mode (screen pinning)
2653 // * App-initiated requests
2654 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2655 // - will start the pinned mode, otherwise
2656 final int callingUid = Binder.getCallingUid();
2657 long ident = Binder.clearCallingIdentity();
2658 try {
2659 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002660 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002661
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002662 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663 } finally {
2664 Binder.restoreCallingIdentity(ident);
2665 }
2666 }
2667
2668 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2669 final int callingUid = Binder.getCallingUid();
2670 long ident = Binder.clearCallingIdentity();
2671 try {
2672 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002673 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 }
2675 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2676 // task and jumping straight into a call in the case of emergency call back.
2677 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2678 if (tm != null) {
2679 tm.showInCallScreen(false);
2680 }
2681 } finally {
2682 Binder.restoreCallingIdentity(ident);
2683 }
2684 }
2685
2686 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002687 public void updateLockTaskPackages(int userId, String[] packages) {
2688 final int callingUid = Binder.getCallingUid();
2689 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2690 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2691 "updateLockTaskPackages()");
2692 }
2693 synchronized (this) {
2694 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2695 + Arrays.toString(packages));
2696 getLockTaskController().updateLockTaskPackages(userId, packages);
2697 }
2698 }
2699
2700 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 public boolean isInLockTaskMode() {
2702 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2703 }
2704
2705 @Override
2706 public int getLockTaskModeState() {
2707 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002708 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 }
2710 }
2711
2712 @Override
2713 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2714 synchronized (mGlobalLock) {
2715 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2716 if (r != null) {
2717 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002718 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002719 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002720 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721 }
2722 }
2723 }
2724
2725 @Override
2726 public Bundle getActivityOptions(IBinder token) {
2727 final long origId = Binder.clearCallingIdentity();
2728 try {
2729 synchronized (mGlobalLock) {
2730 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2731 if (r != null) {
2732 final ActivityOptions activityOptions = r.takeOptionsLocked();
2733 return activityOptions == null ? null : activityOptions.toBundle();
2734 }
2735 return null;
2736 }
2737 } finally {
2738 Binder.restoreCallingIdentity(origId);
2739 }
2740 }
2741
2742 @Override
2743 public List<IBinder> getAppTasks(String callingPackage) {
2744 int callingUid = Binder.getCallingUid();
2745 long ident = Binder.clearCallingIdentity();
2746 try {
2747 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002748 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002749 }
2750 } finally {
2751 Binder.restoreCallingIdentity(ident);
2752 }
2753 }
2754
2755 @Override
2756 public void finishVoiceTask(IVoiceInteractionSession session) {
2757 synchronized (mGlobalLock) {
2758 final long origId = Binder.clearCallingIdentity();
2759 try {
2760 // TODO: VI Consider treating local voice interactions and voice tasks
2761 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002762 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002763 } finally {
2764 Binder.restoreCallingIdentity(origId);
2765 }
2766 }
2767
2768 }
2769
2770 @Override
2771 public boolean isTopOfTask(IBinder token) {
2772 synchronized (mGlobalLock) {
2773 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002774 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 }
2776 }
2777
2778 @Override
2779 public void notifyLaunchTaskBehindComplete(IBinder token) {
2780 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2781 }
2782
2783 @Override
2784 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002785 mH.post(() -> {
2786 synchronized (mGlobalLock) {
2787 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002788 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002789 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002790 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002791 } catch (RemoteException e) {
2792 }
2793 }
2794 }
2795
2796 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002797 }
2798
2799 /** Called from an app when assist data is ready. */
2800 @Override
2801 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2802 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002803 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 synchronized (pae) {
2805 pae.result = extras;
2806 pae.structure = structure;
2807 pae.content = content;
2808 if (referrer != null) {
2809 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2810 }
2811 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002812 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002813 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2814 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002815 structure.setHomeActivity(pae.isHome);
2816 }
2817 pae.haveResult = true;
2818 pae.notifyAll();
2819 if (pae.intent == null && pae.receiver == null) {
2820 // Caller is just waiting for the result.
2821 return;
2822 }
2823 }
2824 // We are now ready to launch the assist activity.
2825 IAssistDataReceiver sendReceiver = null;
2826 Bundle sendBundle = null;
2827 synchronized (mGlobalLock) {
2828 buildAssistBundleLocked(pae, extras);
2829 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002830 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002831 if (!exists) {
2832 // Timed out.
2833 return;
2834 }
2835
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002836 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002837 // Caller wants result sent back to them.
2838 sendBundle = new Bundle();
2839 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2840 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2841 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2842 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2843 }
2844 }
2845 if (sendReceiver != null) {
2846 try {
2847 sendReceiver.onHandleAssistData(sendBundle);
2848 } catch (RemoteException e) {
2849 }
2850 return;
2851 }
2852
2853 final long ident = Binder.clearCallingIdentity();
2854 try {
2855 if (TextUtils.equals(pae.intent.getAction(),
2856 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2857 pae.intent.putExtras(pae.extras);
2858 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2859 } else {
2860 pae.intent.replaceExtras(pae.extras);
2861 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2862 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2863 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002864 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002865
2866 try {
2867 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2868 } catch (ActivityNotFoundException e) {
2869 Slog.w(TAG, "No activity to handle assist action.", e);
2870 }
2871 }
2872 } finally {
2873 Binder.restoreCallingIdentity(ident);
2874 }
2875 }
2876
2877 @Override
2878 public int addAppTask(IBinder activityToken, Intent intent,
2879 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2880 final int callingUid = Binder.getCallingUid();
2881 final long callingIdent = Binder.clearCallingIdentity();
2882
2883 try {
2884 synchronized (mGlobalLock) {
2885 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2886 if (r == null) {
2887 throw new IllegalArgumentException("Activity does not exist; token="
2888 + activityToken);
2889 }
2890 ComponentName comp = intent.getComponent();
2891 if (comp == null) {
2892 throw new IllegalArgumentException("Intent " + intent
2893 + " must specify explicit component");
2894 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002895 if (thumbnail.getWidth() != mThumbnailWidth
2896 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002897 throw new IllegalArgumentException("Bad thumbnail size: got "
2898 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002899 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 }
2901 if (intent.getSelector() != null) {
2902 intent.setSelector(null);
2903 }
2904 if (intent.getSourceBounds() != null) {
2905 intent.setSourceBounds(null);
2906 }
2907 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2908 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2909 // The caller has added this as an auto-remove task... that makes no
2910 // sense, so turn off auto-remove.
2911 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2912 }
2913 }
2914 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2915 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2916 if (ainfo.applicationInfo.uid != callingUid) {
2917 throw new SecurityException(
2918 "Can't add task for another application: target uid="
2919 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2920 }
2921
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002922 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002923 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002924 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002925 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002926 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002927 // The app has too many tasks already and we can't add any more
2928 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2929 return INVALID_TASK_ID;
2930 }
2931 task.lastTaskDescription.copyFrom(description);
2932
2933 // TODO: Send the thumbnail to WM to store it.
2934
2935 return task.taskId;
2936 }
2937 } finally {
2938 Binder.restoreCallingIdentity(callingIdent);
2939 }
2940 }
2941
2942 @Override
2943 public Point getAppTaskThumbnailSize() {
2944 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002945 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 }
2948
2949 @Override
2950 public void setTaskResizeable(int taskId, int resizeableMode) {
2951 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002952 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002953 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2954 if (task == null) {
2955 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2956 return;
2957 }
2958 task.setResizeMode(resizeableMode);
2959 }
2960 }
2961
2962 @Override
2963 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002964 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 long ident = Binder.clearCallingIdentity();
2966 try {
2967 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002968 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002969 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002970 if (task == null) {
2971 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2972 return;
2973 }
2974 // Place the task in the right stack if it isn't there already based on
2975 // the requested bounds.
2976 // The stack transition logic is:
2977 // - a null bounds on a freeform task moves that task to fullscreen
2978 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2979 // that task to freeform
2980 // - otherwise the task is not moved
2981 ActivityStack stack = task.getStack();
2982 if (!task.getWindowConfiguration().canResizeTask()) {
2983 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2984 }
2985 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2986 stack = stack.getDisplay().getOrCreateStack(
2987 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2988 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2989 stack = stack.getDisplay().getOrCreateStack(
2990 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2991 }
2992
2993 // Reparent the task to the right stack if necessary
2994 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2995 if (stack != task.getStack()) {
2996 // Defer resume until the task is resized below
2997 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2998 DEFER_RESUME, "resizeTask");
2999 preserveWindow = false;
3000 }
3001
3002 // After reparenting (which only resizes the task to the stack bounds), resize the
3003 // task to the actual bounds provided
3004 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3005 }
3006 } finally {
3007 Binder.restoreCallingIdentity(ident);
3008 }
3009 }
3010
3011 @Override
3012 public boolean releaseActivityInstance(IBinder token) {
3013 synchronized (mGlobalLock) {
3014 final long origId = Binder.clearCallingIdentity();
3015 try {
3016 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3017 if (r == null) {
3018 return false;
3019 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003020 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003021 } finally {
3022 Binder.restoreCallingIdentity(origId);
3023 }
3024 }
3025 }
3026
3027 @Override
3028 public void releaseSomeActivities(IApplicationThread appInt) {
3029 synchronized (mGlobalLock) {
3030 final long origId = Binder.clearCallingIdentity();
3031 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003032 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003033 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 } finally {
3035 Binder.restoreCallingIdentity(origId);
3036 }
3037 }
3038 }
3039
3040 @Override
3041 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003042 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003043 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003044 != PackageManager.PERMISSION_GRANTED) {
3045 throw new SecurityException("Requires permission "
3046 + android.Manifest.permission.DEVICE_POWER);
3047 }
3048
3049 synchronized (mGlobalLock) {
3050 long ident = Binder.clearCallingIdentity();
3051 if (mKeyguardShown != keyguardShowing) {
3052 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003053 final Message msg = PooledLambda.obtainMessage(
3054 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3055 keyguardShowing);
3056 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003057 }
3058 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003059 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003060 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003061 } finally {
3062 Binder.restoreCallingIdentity(ident);
3063 }
3064 }
3065
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003066 mH.post(() -> {
3067 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3068 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3069 }
3070 });
3071 }
3072
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003073 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003074 mH.post(() -> {
3075 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3076 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3077 }
3078 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003079 }
3080
3081 @Override
3082 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003083 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3084 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003085
3086 final File passedIconFile = new File(filePath);
3087 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3088 passedIconFile.getName());
3089 if (!legitIconFile.getPath().equals(filePath)
3090 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3091 throw new IllegalArgumentException("Bad file path: " + filePath
3092 + " passed for userId " + userId);
3093 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003094 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003095 }
3096
3097 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003098 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3100 final ActivityOptions activityOptions = safeOptions != null
3101 ? safeOptions.getOptions(mStackSupervisor)
3102 : null;
3103 if (activityOptions == null
3104 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3105 || activityOptions.getCustomInPlaceResId() == 0) {
3106 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3107 "with valid animation");
3108 }
lumark588a3e82018-07-20 18:53:54 +08003109 // Get top display of front most application.
3110 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3111 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003112 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3113 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3114 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003115 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003116 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003117 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003118 }
3119
3120 @Override
3121 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003122 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003123 synchronized (mGlobalLock) {
3124 final long ident = Binder.clearCallingIdentity();
3125 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003126 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003127 if (stack == null) {
3128 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3129 return;
3130 }
3131 if (!stack.isActivityTypeStandardOrUndefined()) {
3132 throw new IllegalArgumentException(
3133 "Removing non-standard stack is not allowed.");
3134 }
3135 mStackSupervisor.removeStack(stack);
3136 } finally {
3137 Binder.restoreCallingIdentity(ident);
3138 }
3139 }
3140 }
3141
3142 @Override
3143 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003144 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145
3146 synchronized (mGlobalLock) {
3147 final long ident = Binder.clearCallingIdentity();
3148 try {
3149 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3150 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003151 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003152 } finally {
3153 Binder.restoreCallingIdentity(ident);
3154 }
3155 }
3156 }
3157
3158 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003159 public void exitFreeformMode(IBinder token) {
3160 synchronized (mGlobalLock) {
3161 long ident = Binder.clearCallingIdentity();
3162 try {
3163 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3164 if (r == null) {
3165 throw new IllegalArgumentException(
3166 "exitFreeformMode: No activity record matching token=" + token);
3167 }
3168
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003169 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003170 if (stack == null || !stack.inFreeformWindowingMode()) {
3171 throw new IllegalStateException(
3172 "exitFreeformMode: You can only go fullscreen from freeform.");
3173 }
3174
3175 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3176 } finally {
3177 Binder.restoreCallingIdentity(ident);
3178 }
3179 }
3180 }
3181
3182 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3183 @Override
3184 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003185 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003186 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003187 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003188 }
3189
3190 /** Unregister a task stack listener so that it stops receiving callbacks. */
3191 @Override
3192 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003193 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003195 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003196 }
3197
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 @Override
3199 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3200 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3201 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3202 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3203 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3204 }
3205
3206 @Override
3207 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3208 IBinder activityToken, int flags) {
3209 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3210 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3211 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3212 }
3213
3214 @Override
3215 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3216 Bundle args) {
3217 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3218 true /* focused */, true /* newSessionId */, userHandle, args,
3219 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3220 }
3221
3222 @Override
3223 public Bundle getAssistContextExtras(int requestType) {
3224 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3225 null, null, true /* focused */, true /* newSessionId */,
3226 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3227 if (pae == null) {
3228 return null;
3229 }
3230 synchronized (pae) {
3231 while (!pae.haveResult) {
3232 try {
3233 pae.wait();
3234 } catch (InterruptedException e) {
3235 }
3236 }
3237 }
3238 synchronized (mGlobalLock) {
3239 buildAssistBundleLocked(pae, pae.result);
3240 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003241 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003242 }
3243 return pae.extras;
3244 }
3245
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003246 /**
3247 * Binder IPC calls go through the public entry point.
3248 * This can be called with or without the global lock held.
3249 */
3250 private static int checkCallingPermission(String permission) {
3251 return checkPermission(
3252 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3253 }
3254
3255 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003256 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003257 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3258 mAmInternal.enforceCallingPermission(permission, func);
3259 }
3260 }
3261
3262 @VisibleForTesting
3263 int checkGetTasksPermission(String permission, int pid, int uid) {
3264 return checkPermission(permission, pid, uid);
3265 }
3266
3267 static int checkPermission(String permission, int pid, int uid) {
3268 if (permission == null) {
3269 return PackageManager.PERMISSION_DENIED;
3270 }
3271 return checkComponentPermission(permission, pid, uid, -1, true);
3272 }
3273
Wale Ogunwale214f3482018-10-04 11:00:47 -07003274 public static int checkComponentPermission(String permission, int pid, int uid,
3275 int owningUid, boolean exported) {
3276 return ActivityManagerService.checkComponentPermission(
3277 permission, pid, uid, owningUid, exported);
3278 }
3279
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003280 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3281 if (getRecentTasks().isCallerRecents(callingUid)) {
3282 // Always allow the recents component to get tasks
3283 return true;
3284 }
3285
3286 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3287 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3288 if (!allowed) {
3289 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3290 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3291 // Temporary compatibility: some existing apps on the system image may
3292 // still be requesting the old permission and not switched to the new
3293 // one; if so, we'll still allow them full access. This means we need
3294 // to see if they are holding the old permission and are a system app.
3295 try {
3296 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3297 allowed = true;
3298 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3299 + " is using old GET_TASKS but privileged; allowing");
3300 }
3301 } catch (RemoteException e) {
3302 }
3303 }
3304 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3305 + " does not hold REAL_GET_TASKS; limiting output");
3306 }
3307 return allowed;
3308 }
3309
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003310 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3311 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3312 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3313 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003315 "enqueueAssistContext()");
3316
3317 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003318 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003319 if (activity == null) {
3320 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3321 return null;
3322 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003323 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003324 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3325 return null;
3326 }
3327 if (focused) {
3328 if (activityToken != null) {
3329 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3330 if (activity != caller) {
3331 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3332 + " is not current top " + activity);
3333 return null;
3334 }
3335 }
3336 } else {
3337 activity = ActivityRecord.forTokenLocked(activityToken);
3338 if (activity == null) {
3339 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3340 + " couldn't be found");
3341 return null;
3342 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003343 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003344 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3345 return null;
3346 }
3347 }
3348
3349 PendingAssistExtras pae;
3350 Bundle extras = new Bundle();
3351 if (args != null) {
3352 extras.putAll(args);
3353 }
3354 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003355 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356
3357 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3358 userHandle);
3359 pae.isHome = activity.isActivityTypeHome();
3360
3361 // Increment the sessionId if necessary
3362 if (newSessionId) {
3363 mViSessionId++;
3364 }
3365 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003366 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3367 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 } catch (RemoteException e) {
3371 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3372 return null;
3373 }
3374 return pae;
3375 }
3376 }
3377
3378 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3379 if (result != null) {
3380 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3381 }
3382 if (pae.hint != null) {
3383 pae.extras.putBoolean(pae.hint, true);
3384 }
3385 }
3386
3387 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3388 IAssistDataReceiver receiver;
3389 synchronized (mGlobalLock) {
3390 mPendingAssistExtras.remove(pae);
3391 receiver = pae.receiver;
3392 }
3393 if (receiver != null) {
3394 // Caller wants result sent back to them.
3395 Bundle sendBundle = new Bundle();
3396 // At least return the receiver extras
3397 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3398 try {
3399 pae.receiver.onHandleAssistData(sendBundle);
3400 } catch (RemoteException e) {
3401 }
3402 }
3403 }
3404
3405 public class PendingAssistExtras extends Binder implements Runnable {
3406 public final ActivityRecord activity;
3407 public boolean isHome;
3408 public final Bundle extras;
3409 public final Intent intent;
3410 public final String hint;
3411 public final IAssistDataReceiver receiver;
3412 public final int userHandle;
3413 public boolean haveResult = false;
3414 public Bundle result = null;
3415 public AssistStructure structure = null;
3416 public AssistContent content = null;
3417 public Bundle receiverExtras;
3418
3419 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3420 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3421 int _userHandle) {
3422 activity = _activity;
3423 extras = _extras;
3424 intent = _intent;
3425 hint = _hint;
3426 receiver = _receiver;
3427 receiverExtras = _receiverExtras;
3428 userHandle = _userHandle;
3429 }
3430
3431 @Override
3432 public void run() {
3433 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3434 synchronized (this) {
3435 haveResult = true;
3436 notifyAll();
3437 }
3438 pendingAssistExtrasTimedOut(this);
3439 }
3440 }
3441
3442 @Override
3443 public boolean isAssistDataAllowedOnCurrentActivity() {
3444 int userId;
3445 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003446 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003447 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3448 return false;
3449 }
3450
3451 final ActivityRecord activity = focusedStack.getTopActivity();
3452 if (activity == null) {
3453 return false;
3454 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003455 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003456 }
3457 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3458 }
3459
3460 @Override
3461 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3462 long ident = Binder.clearCallingIdentity();
3463 try {
3464 synchronized (mGlobalLock) {
3465 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003466 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003467 if (top != caller) {
3468 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3469 + " is not current top " + top);
3470 return false;
3471 }
3472 if (!top.nowVisible) {
3473 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3474 + " is not visible");
3475 return false;
3476 }
3477 }
3478 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3479 token);
3480 } finally {
3481 Binder.restoreCallingIdentity(ident);
3482 }
3483 }
3484
3485 @Override
3486 public boolean isRootVoiceInteraction(IBinder token) {
3487 synchronized (mGlobalLock) {
3488 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3489 if (r == null) {
3490 return false;
3491 }
3492 return r.rootVoiceInteraction;
3493 }
3494 }
3495
Wale Ogunwalef6733932018-06-27 05:14:34 -07003496 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3497 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3498 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3499 if (activityToCallback == null) return;
3500 activityToCallback.setVoiceSessionLocked(voiceSession);
3501
3502 // Inform the activity
3503 try {
3504 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3505 voiceInteractor);
3506 long token = Binder.clearCallingIdentity();
3507 try {
3508 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3509 } finally {
3510 Binder.restoreCallingIdentity(token);
3511 }
3512 // TODO: VI Should we cache the activity so that it's easier to find later
3513 // rather than scan through all the stacks and activities?
3514 } catch (RemoteException re) {
3515 activityToCallback.clearVoiceSessionLocked();
3516 // TODO: VI Should this terminate the voice session?
3517 }
3518 }
3519
3520 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3521 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3522 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3523 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3524 boolean wasRunningVoice = mRunningVoice != null;
3525 mRunningVoice = session;
3526 if (!wasRunningVoice) {
3527 mVoiceWakeLock.acquire();
3528 updateSleepIfNeededLocked();
3529 }
3530 }
3531 }
3532
3533 void finishRunningVoiceLocked() {
3534 if (mRunningVoice != null) {
3535 mRunningVoice = null;
3536 mVoiceWakeLock.release();
3537 updateSleepIfNeededLocked();
3538 }
3539 }
3540
3541 @Override
3542 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3543 synchronized (mGlobalLock) {
3544 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3545 if (keepAwake) {
3546 mVoiceWakeLock.acquire();
3547 } else {
3548 mVoiceWakeLock.release();
3549 }
3550 }
3551 }
3552 }
3553
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003554 @Override
3555 public ComponentName getActivityClassForToken(IBinder token) {
3556 synchronized (mGlobalLock) {
3557 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3558 if (r == null) {
3559 return null;
3560 }
3561 return r.intent.getComponent();
3562 }
3563 }
3564
3565 @Override
3566 public String getPackageForToken(IBinder token) {
3567 synchronized (mGlobalLock) {
3568 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3569 if (r == null) {
3570 return null;
3571 }
3572 return r.packageName;
3573 }
3574 }
3575
3576 @Override
3577 public void showLockTaskEscapeMessage(IBinder token) {
3578 synchronized (mGlobalLock) {
3579 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3580 if (r == null) {
3581 return;
3582 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003583 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003584 }
3585 }
3586
3587 @Override
3588 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003589 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003590 final long token = Binder.clearCallingIdentity();
3591 try {
3592 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003593 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003594 }
3595 } finally {
3596 Binder.restoreCallingIdentity(token);
3597 }
3598 }
3599
3600 /**
3601 * Try to place task to provided position. The final position might be different depending on
3602 * current user and stacks state. The task will be moved to target stack if it's currently in
3603 * different stack.
3604 */
3605 @Override
3606 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003607 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003608 synchronized (mGlobalLock) {
3609 long ident = Binder.clearCallingIdentity();
3610 try {
3611 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3612 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003613 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003614 if (task == null) {
3615 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3616 + taskId);
3617 }
3618
Wale Ogunwaled32da472018-11-16 07:19:28 -08003619 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620
3621 if (stack == null) {
3622 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3623 + stackId);
3624 }
3625 if (!stack.isActivityTypeStandardOrUndefined()) {
3626 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3627 + " the position of task " + taskId + " in/to non-standard stack");
3628 }
3629
3630 // TODO: Have the callers of this API call a separate reparent method if that is
3631 // what they intended to do vs. having this method also do reparenting.
3632 if (task.getStack() == stack) {
3633 // Change position in current stack.
3634 stack.positionChildAt(task, position);
3635 } else {
3636 // Reparent to new stack.
3637 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3638 !DEFER_RESUME, "positionTaskInStack");
3639 }
3640 } finally {
3641 Binder.restoreCallingIdentity(ident);
3642 }
3643 }
3644 }
3645
3646 @Override
3647 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3648 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3649 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3650 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3651 synchronized (mGlobalLock) {
3652 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3653 if (record == null) {
3654 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3655 + "found for: " + token);
3656 }
3657 record.setSizeConfigurations(horizontalSizeConfiguration,
3658 verticalSizeConfigurations, smallestSizeConfigurations);
3659 }
3660 }
3661
3662 /**
3663 * Dismisses split-screen multi-window mode.
3664 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3665 */
3666 @Override
3667 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003668 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3670 final long ident = Binder.clearCallingIdentity();
3671 try {
3672 synchronized (mGlobalLock) {
3673 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003674 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675 if (stack == null) {
3676 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3677 return;
3678 }
3679
3680 if (toTop) {
3681 // Caller wants the current split-screen primary stack to be the top stack after
3682 // it goes fullscreen, so move it to the front.
3683 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003684 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003685 // In this case the current split-screen primary stack shouldn't be the top
3686 // stack after it goes fullscreen, but it current has focus, so we move the
3687 // focus to the top-most split-screen secondary stack next to it.
3688 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3689 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3690 if (otherStack != null) {
3691 otherStack.moveToFront("dismissSplitScreenMode_other");
3692 }
3693 }
3694
Evan Rosky10475742018-09-05 19:02:48 -07003695 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003696 }
3697 } finally {
3698 Binder.restoreCallingIdentity(ident);
3699 }
3700 }
3701
3702 /**
3703 * Dismisses Pip
3704 * @param animate True if the dismissal should be animated.
3705 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3706 * default animation duration should be used.
3707 */
3708 @Override
3709 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003710 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003711 final long ident = Binder.clearCallingIdentity();
3712 try {
3713 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003714 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003715 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003716 if (stack == null) {
3717 Slog.w(TAG, "dismissPip: pinned stack not found.");
3718 return;
3719 }
3720 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3721 throw new IllegalArgumentException("Stack: " + stack
3722 + " doesn't support animated resize.");
3723 }
3724 if (animate) {
3725 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3726 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3727 } else {
3728 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3729 }
3730 }
3731 } finally {
3732 Binder.restoreCallingIdentity(ident);
3733 }
3734 }
3735
3736 @Override
3737 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003738 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003739 synchronized (mGlobalLock) {
3740 mSuppressResizeConfigChanges = suppress;
3741 }
3742 }
3743
3744 /**
3745 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3746 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3747 * activity and clearing the task at the same time.
3748 */
3749 @Override
3750 // TODO: API should just be about changing windowing modes...
3751 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003752 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 "moveTasksToFullscreenStack()");
3754 synchronized (mGlobalLock) {
3755 final long origId = Binder.clearCallingIdentity();
3756 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003757 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003758 if (stack != null){
3759 if (!stack.isActivityTypeStandardOrUndefined()) {
3760 throw new IllegalArgumentException(
3761 "You can't move tasks from non-standard stacks.");
3762 }
3763 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3764 }
3765 } finally {
3766 Binder.restoreCallingIdentity(origId);
3767 }
3768 }
3769 }
3770
3771 /**
3772 * Moves the top activity in the input stackId to the pinned stack.
3773 *
3774 * @param stackId Id of stack to move the top activity to pinned stack.
3775 * @param bounds Bounds to use for pinned stack.
3776 *
3777 * @return True if the top activity of the input stack was successfully moved to the pinned
3778 * stack.
3779 */
3780 @Override
3781 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003782 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003783 "moveTopActivityToPinnedStack()");
3784 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003785 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003786 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3787 + "Device doesn't support picture-in-picture mode");
3788 }
3789
3790 long ident = Binder.clearCallingIdentity();
3791 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003792 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003793 } finally {
3794 Binder.restoreCallingIdentity(ident);
3795 }
3796 }
3797 }
3798
3799 @Override
3800 public boolean isInMultiWindowMode(IBinder token) {
3801 final long origId = Binder.clearCallingIdentity();
3802 try {
3803 synchronized (mGlobalLock) {
3804 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3805 if (r == null) {
3806 return false;
3807 }
3808 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3809 return r.inMultiWindowMode();
3810 }
3811 } finally {
3812 Binder.restoreCallingIdentity(origId);
3813 }
3814 }
3815
3816 @Override
3817 public boolean isInPictureInPictureMode(IBinder token) {
3818 final long origId = Binder.clearCallingIdentity();
3819 try {
3820 synchronized (mGlobalLock) {
3821 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3822 }
3823 } finally {
3824 Binder.restoreCallingIdentity(origId);
3825 }
3826 }
3827
3828 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003829 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3830 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003831 return false;
3832 }
3833
3834 // If we are animating to fullscreen then we have already dispatched the PIP mode
3835 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003836 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3837 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 }
3839
3840 @Override
3841 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3842 final long origId = Binder.clearCallingIdentity();
3843 try {
3844 synchronized (mGlobalLock) {
3845 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3846 "enterPictureInPictureMode", token, params);
3847
3848 // If the activity is already in picture in picture mode, then just return early
3849 if (isInPictureInPictureMode(r)) {
3850 return true;
3851 }
3852
3853 // Activity supports picture-in-picture, now check that we can enter PiP at this
3854 // point, if it is
3855 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3856 false /* beforeStopping */)) {
3857 return false;
3858 }
3859
3860 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003861 synchronized (mGlobalLock) {
3862 // Only update the saved args from the args that are set
3863 r.pictureInPictureArgs.copyOnlySet(params);
3864 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3865 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3866 // Adjust the source bounds by the insets for the transition down
3867 final Rect sourceBounds = new Rect(
3868 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003869 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003870 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003871 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003872 stack.setPictureInPictureAspectRatio(aspectRatio);
3873 stack.setPictureInPictureActions(actions);
3874 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3875 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3876 logPictureInPictureArgs(params);
3877 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003878 };
3879
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003880 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003881 // If the keyguard is showing or occluded, then try and dismiss it before
3882 // entering picture-in-picture (this will prompt the user to authenticate if the
3883 // device is currently locked).
3884 dismissKeyguard(token, new KeyguardDismissCallback() {
3885 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003886 public void onDismissSucceeded() {
3887 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 }
3889 }, null /* message */);
3890 } else {
3891 // Enter picture in picture immediately otherwise
3892 enterPipRunnable.run();
3893 }
3894 return true;
3895 }
3896 } finally {
3897 Binder.restoreCallingIdentity(origId);
3898 }
3899 }
3900
3901 @Override
3902 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3903 final long origId = Binder.clearCallingIdentity();
3904 try {
3905 synchronized (mGlobalLock) {
3906 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3907 "setPictureInPictureParams", token, params);
3908
3909 // Only update the saved args from the args that are set
3910 r.pictureInPictureArgs.copyOnlySet(params);
3911 if (r.inPinnedWindowingMode()) {
3912 // If the activity is already in picture-in-picture, update the pinned stack now
3913 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3914 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003915 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003916 if (!stack.isAnimatingBoundsToFullscreen()) {
3917 stack.setPictureInPictureAspectRatio(
3918 r.pictureInPictureArgs.getAspectRatio());
3919 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3920 }
3921 }
3922 logPictureInPictureArgs(params);
3923 }
3924 } finally {
3925 Binder.restoreCallingIdentity(origId);
3926 }
3927 }
3928
3929 @Override
3930 public int getMaxNumPictureInPictureActions(IBinder token) {
3931 // Currently, this is a static constant, but later, we may change this to be dependent on
3932 // the context of the activity
3933 return 3;
3934 }
3935
3936 private void logPictureInPictureArgs(PictureInPictureParams params) {
3937 if (params.hasSetActions()) {
3938 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3939 params.getActions().size());
3940 }
3941 if (params.hasSetAspectRatio()) {
3942 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3943 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3944 MetricsLogger.action(lm);
3945 }
3946 }
3947
3948 /**
3949 * Checks the state of the system and the activity associated with the given {@param token} to
3950 * verify that picture-in-picture is supported for that activity.
3951 *
3952 * @return the activity record for the given {@param token} if all the checks pass.
3953 */
3954 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3955 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003956 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003957 throw new IllegalStateException(caller
3958 + ": Device doesn't support picture-in-picture mode.");
3959 }
3960
3961 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3962 if (r == null) {
3963 throw new IllegalStateException(caller
3964 + ": Can't find activity for token=" + token);
3965 }
3966
3967 if (!r.supportsPictureInPicture()) {
3968 throw new IllegalStateException(caller
3969 + ": Current activity does not support picture-in-picture.");
3970 }
3971
3972 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003973 && !mWindowManager.isValidPictureInPictureAspectRatio(
3974 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003975 final float minAspectRatio = mContext.getResources().getFloat(
3976 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3977 final float maxAspectRatio = mContext.getResources().getFloat(
3978 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3979 throw new IllegalArgumentException(String.format(caller
3980 + ": Aspect ratio is too extreme (must be between %f and %f).",
3981 minAspectRatio, maxAspectRatio));
3982 }
3983
3984 // Truncate the number of actions if necessary
3985 params.truncateActions(getMaxNumPictureInPictureActions(token));
3986
3987 return r;
3988 }
3989
3990 @Override
3991 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003992 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003993 synchronized (mGlobalLock) {
3994 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3995 if (r == null) {
3996 throw new IllegalArgumentException("Activity does not exist; token="
3997 + activityToken);
3998 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003999 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004000 }
4001 }
4002
4003 @Override
4004 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4005 Rect tempDockedTaskInsetBounds,
4006 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004007 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004008 long ident = Binder.clearCallingIdentity();
4009 try {
4010 synchronized (mGlobalLock) {
4011 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4012 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4013 PRESERVE_WINDOWS);
4014 }
4015 } finally {
4016 Binder.restoreCallingIdentity(ident);
4017 }
4018 }
4019
4020 @Override
4021 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004022 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004023 final long ident = Binder.clearCallingIdentity();
4024 try {
4025 synchronized (mGlobalLock) {
4026 mStackSupervisor.setSplitScreenResizing(resizing);
4027 }
4028 } finally {
4029 Binder.restoreCallingIdentity(ident);
4030 }
4031 }
4032
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004033 /**
4034 * Check that we have the features required for VR-related API calls, and throw an exception if
4035 * not.
4036 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004037 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004038 if (!mContext.getPackageManager().hasSystemFeature(
4039 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4040 throw new UnsupportedOperationException("VR mode not supported on this device!");
4041 }
4042 }
4043
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 @Override
4045 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004046 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004047
4048 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4049
4050 ActivityRecord r;
4051 synchronized (mGlobalLock) {
4052 r = ActivityRecord.isInStackLocked(token);
4053 }
4054
4055 if (r == null) {
4056 throw new IllegalArgumentException();
4057 }
4058
4059 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004060 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004061 VrManagerInternal.NO_ERROR) {
4062 return err;
4063 }
4064
4065 // Clear the binder calling uid since this path may call moveToTask().
4066 final long callingId = Binder.clearCallingIdentity();
4067 try {
4068 synchronized (mGlobalLock) {
4069 r.requestedVrComponent = (enabled) ? packageName : null;
4070
4071 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004072 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004073 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004074 }
4075 return 0;
4076 }
4077 } finally {
4078 Binder.restoreCallingIdentity(callingId);
4079 }
4080 }
4081
4082 @Override
4083 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4084 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4085 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004086 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004087 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4088 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4089 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004090 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004091 || activity.voiceSession != null) {
4092 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4093 return;
4094 }
4095 if (activity.pendingVoiceInteractionStart) {
4096 Slog.w(TAG, "Pending start of voice interaction already.");
4097 return;
4098 }
4099 activity.pendingVoiceInteractionStart = true;
4100 }
4101 LocalServices.getService(VoiceInteractionManagerInternal.class)
4102 .startLocalVoiceInteraction(callingActivity, options);
4103 }
4104
4105 @Override
4106 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4107 LocalServices.getService(VoiceInteractionManagerInternal.class)
4108 .stopLocalVoiceInteraction(callingActivity);
4109 }
4110
4111 @Override
4112 public boolean supportsLocalVoiceInteraction() {
4113 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4114 .supportsLocalVoiceInteraction();
4115 }
4116
4117 /** Notifies all listeners when the pinned stack animation starts. */
4118 @Override
4119 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004120 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004121 }
4122
4123 /** Notifies all listeners when the pinned stack animation ends. */
4124 @Override
4125 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004126 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004127 }
4128
4129 @Override
4130 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004131 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004132 final long ident = Binder.clearCallingIdentity();
4133 try {
4134 synchronized (mGlobalLock) {
4135 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4136 }
4137 } finally {
4138 Binder.restoreCallingIdentity(ident);
4139 }
4140 }
4141
4142 @Override
4143 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004144 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004145
4146 synchronized (mGlobalLock) {
4147 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004148 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004149 // Call might come when display is not yet added or has already been removed.
4150 if (DEBUG_CONFIGURATION) {
4151 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4152 + displayId);
4153 }
4154 return false;
4155 }
4156
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004157 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004158 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004159 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004160 }
4161
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004162 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004163 final Message msg = PooledLambda.obtainMessage(
4164 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4165 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004166 }
4167
4168 final long origId = Binder.clearCallingIdentity();
4169 try {
4170 if (values != null) {
4171 Settings.System.clearConfiguration(values);
4172 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004173 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004174 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4175 return mTmpUpdateConfigurationResult.changes != 0;
4176 } finally {
4177 Binder.restoreCallingIdentity(origId);
4178 }
4179 }
4180 }
4181
4182 @Override
4183 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004184 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004185
4186 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004187 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004188 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004189 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004190 }
4191
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004192 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004193 final Message msg = PooledLambda.obtainMessage(
4194 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4195 DEFAULT_DISPLAY);
4196 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197 }
4198
4199 final long origId = Binder.clearCallingIdentity();
4200 try {
4201 if (values != null) {
4202 Settings.System.clearConfiguration(values);
4203 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004204 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004205 UserHandle.USER_NULL, false /* deferResume */,
4206 mTmpUpdateConfigurationResult);
4207 return mTmpUpdateConfigurationResult.changes != 0;
4208 } finally {
4209 Binder.restoreCallingIdentity(origId);
4210 }
4211 }
4212 }
4213
4214 @Override
4215 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4216 CharSequence message) {
4217 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004218 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004219 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4220 }
4221 final long callingId = Binder.clearCallingIdentity();
4222 try {
4223 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004224 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004225 }
4226 } finally {
4227 Binder.restoreCallingIdentity(callingId);
4228 }
4229 }
4230
4231 @Override
4232 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004233 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004234 "cancelTaskWindowTransition()");
4235 final long ident = Binder.clearCallingIdentity();
4236 try {
4237 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004238 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004239 MATCH_TASK_IN_STACKS_ONLY);
4240 if (task == null) {
4241 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4242 return;
4243 }
4244 task.cancelWindowTransition();
4245 }
4246 } finally {
4247 Binder.restoreCallingIdentity(ident);
4248 }
4249 }
4250
4251 @Override
4252 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004253 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 final long ident = Binder.clearCallingIdentity();
4255 try {
4256 final TaskRecord task;
4257 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004258 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004259 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4260 if (task == null) {
4261 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4262 return null;
4263 }
4264 }
4265 // Don't call this while holding the lock as this operation might hit the disk.
4266 return task.getSnapshot(reducedResolution);
4267 } finally {
4268 Binder.restoreCallingIdentity(ident);
4269 }
4270 }
4271
4272 @Override
4273 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4274 synchronized (mGlobalLock) {
4275 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4276 if (r == null) {
4277 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4278 + token);
4279 return;
4280 }
4281 final long origId = Binder.clearCallingIdentity();
4282 try {
4283 r.setDisablePreviewScreenshots(disable);
4284 } finally {
4285 Binder.restoreCallingIdentity(origId);
4286 }
4287 }
4288 }
4289
4290 /** Return the user id of the last resumed activity. */
4291 @Override
4292 public @UserIdInt
4293 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004294 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004295 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4296 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004297 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004298 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004299 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004300 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004301 }
4302 }
4303
4304 @Override
4305 public void updateLockTaskFeatures(int userId, int flags) {
4306 final int callingUid = Binder.getCallingUid();
4307 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004308 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 "updateLockTaskFeatures()");
4310 }
4311 synchronized (mGlobalLock) {
4312 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4313 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004314 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004315 }
4316 }
4317
4318 @Override
4319 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4320 synchronized (mGlobalLock) {
4321 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4322 if (r == null) {
4323 return;
4324 }
4325 final long origId = Binder.clearCallingIdentity();
4326 try {
4327 r.setShowWhenLocked(showWhenLocked);
4328 } finally {
4329 Binder.restoreCallingIdentity(origId);
4330 }
4331 }
4332 }
4333
4334 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004335 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4336 synchronized (mGlobalLock) {
4337 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4338 if (r == null) {
4339 return;
4340 }
4341 final long origId = Binder.clearCallingIdentity();
4342 try {
4343 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4344 } finally {
4345 Binder.restoreCallingIdentity(origId);
4346 }
4347 }
4348 }
4349
4350 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004351 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4352 synchronized (mGlobalLock) {
4353 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4354 if (r == null) {
4355 return;
4356 }
4357 final long origId = Binder.clearCallingIdentity();
4358 try {
4359 r.setTurnScreenOn(turnScreenOn);
4360 } finally {
4361 Binder.restoreCallingIdentity(origId);
4362 }
4363 }
4364 }
4365
4366 @Override
4367 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004368 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004369 "registerRemoteAnimations");
4370 definition.setCallingPid(Binder.getCallingPid());
4371 synchronized (mGlobalLock) {
4372 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4373 if (r == null) {
4374 return;
4375 }
4376 final long origId = Binder.clearCallingIdentity();
4377 try {
4378 r.registerRemoteAnimations(definition);
4379 } finally {
4380 Binder.restoreCallingIdentity(origId);
4381 }
4382 }
4383 }
4384
4385 @Override
4386 public void registerRemoteAnimationForNextActivityStart(String packageName,
4387 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004388 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004389 "registerRemoteAnimationForNextActivityStart");
4390 adapter.setCallingPid(Binder.getCallingPid());
4391 synchronized (mGlobalLock) {
4392 final long origId = Binder.clearCallingIdentity();
4393 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004394 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004395 packageName, adapter);
4396 } finally {
4397 Binder.restoreCallingIdentity(origId);
4398 }
4399 }
4400 }
4401
Evan Rosky966759f2019-01-15 10:33:58 -08004402 @Override
4403 public void registerRemoteAnimationsForDisplay(int displayId,
4404 RemoteAnimationDefinition definition) {
4405 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4406 "registerRemoteAnimations");
4407 definition.setCallingPid(Binder.getCallingPid());
4408 synchronized (mGlobalLock) {
4409 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4410 if (display == null) {
4411 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4412 return;
4413 }
4414 final long origId = Binder.clearCallingIdentity();
4415 try {
4416 display.mDisplayContent.registerRemoteAnimations(definition);
4417 } finally {
4418 Binder.restoreCallingIdentity(origId);
4419 }
4420 }
4421 }
4422
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004423 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4424 @Override
4425 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4426 synchronized (mGlobalLock) {
4427 final long origId = Binder.clearCallingIdentity();
4428 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004429 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004430 } finally {
4431 Binder.restoreCallingIdentity(origId);
4432 }
4433 }
4434 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004435
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004436 @Override
4437 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004438 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004439 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004440 final int pid = Binder.getCallingPid();
4441 final WindowProcessController wpc = mPidMap.get(pid);
4442 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004443 }
4444 }
4445
4446 @Override
4447 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004448 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004449 != PERMISSION_GRANTED) {
4450 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4451 + Binder.getCallingPid()
4452 + ", uid=" + Binder.getCallingUid()
4453 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4454 Slog.w(TAG, msg);
4455 throw new SecurityException(msg);
4456 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004457 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004458 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004459 final int pid = Binder.getCallingPid();
4460 final WindowProcessController proc = mPidMap.get(pid);
4461 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004462 }
4463 }
4464
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004465 @Override
4466 public void stopAppSwitches() {
4467 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4468 synchronized (mGlobalLock) {
4469 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4470 mDidAppSwitch = false;
4471 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4472 }
4473 }
4474
4475 @Override
4476 public void resumeAppSwitches() {
4477 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4478 synchronized (mGlobalLock) {
4479 // Note that we don't execute any pending app switches... we will
4480 // let those wait until either the timeout, or the next start
4481 // activity request.
4482 mAppSwitchesAllowedTime = 0;
4483 }
4484 }
4485
4486 void onStartActivitySetDidAppSwitch() {
4487 if (mDidAppSwitch) {
4488 // This is the second allowed switch since we stopped switches, so now just generally
4489 // allow switches. Use case:
4490 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4491 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4492 // anyone to switch again).
4493 mAppSwitchesAllowedTime = 0;
4494 } else {
4495 mDidAppSwitch = true;
4496 }
4497 }
4498
4499 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004500 boolean shouldDisableNonVrUiLocked() {
4501 return mVrController.shouldDisableNonVrUiLocked();
4502 }
4503
Wale Ogunwale53783742018-09-16 10:21:51 -07004504 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004505 // VR apps are expected to run in a main display. If an app is turning on VR for
4506 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4507 // fullscreen stack before enabling VR Mode.
4508 // TODO: The goal of this code is to keep the VR app on the main display. When the
4509 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4510 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4511 // option would be a better choice here.
4512 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4513 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4514 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004515 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004516 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004517 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004518 }
4519 mH.post(() -> {
4520 if (!mVrController.onVrModeChanged(r)) {
4521 return;
4522 }
4523 synchronized (mGlobalLock) {
4524 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4525 mWindowManager.disableNonVrUi(disableNonVrUi);
4526 if (disableNonVrUi) {
4527 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4528 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004529 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004530 }
4531 }
4532 });
4533 }
4534
Wale Ogunwale53783742018-09-16 10:21:51 -07004535 @Override
4536 public int getPackageScreenCompatMode(String packageName) {
4537 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4538 synchronized (mGlobalLock) {
4539 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4540 }
4541 }
4542
4543 @Override
4544 public void setPackageScreenCompatMode(String packageName, int mode) {
4545 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4546 "setPackageScreenCompatMode");
4547 synchronized (mGlobalLock) {
4548 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4549 }
4550 }
4551
4552 @Override
4553 public boolean getPackageAskScreenCompat(String packageName) {
4554 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4555 synchronized (mGlobalLock) {
4556 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4557 }
4558 }
4559
4560 @Override
4561 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4562 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4563 "setPackageAskScreenCompat");
4564 synchronized (mGlobalLock) {
4565 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4566 }
4567 }
4568
Wale Ogunwale64258362018-10-16 15:13:37 -07004569 public static String relaunchReasonToString(int relaunchReason) {
4570 switch (relaunchReason) {
4571 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4572 return "window_resize";
4573 case RELAUNCH_REASON_FREE_RESIZE:
4574 return "free_resize";
4575 default:
4576 return null;
4577 }
4578 }
4579
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004580 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004581 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004582 }
4583
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004584 /** Pokes the task persister. */
4585 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4586 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4587 }
4588
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004589 boolean isKeyguardLocked() {
4590 return mKeyguardController.isKeyguardLocked();
4591 }
4592
Garfield Tan01548632018-11-27 10:15:48 -08004593 /**
4594 * Clears launch params for the given package.
4595 * @param packageNames the names of the packages of which the launch params are to be cleared
4596 */
4597 @Override
4598 public void clearLaunchParamsForPackages(List<String> packageNames) {
4599 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4600 "clearLaunchParamsForPackages");
4601 synchronized (mGlobalLock) {
4602 for (int i = 0; i < packageNames.size(); ++i) {
4603 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4604 }
4605 }
4606 }
4607
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004608 /**
4609 * Makes the display with the given id a single task instance display. I.e the display can only
4610 * contain one task.
4611 */
4612 @Override
4613 public void setDisplayToSingleTaskInstance(int displayId) {
4614 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4615 "setDisplayToSingleTaskInstance");
4616 final long origId = Binder.clearCallingIdentity();
4617 try {
4618 final ActivityDisplay display =
4619 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4620 if (display != null) {
4621 display.setDisplayToSingleTaskInstance();
4622 }
4623 } finally {
4624 Binder.restoreCallingIdentity(origId);
4625 }
4626 }
4627
Wale Ogunwale31913b52018-10-13 08:29:31 -07004628 void dumpLastANRLocked(PrintWriter pw) {
4629 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4630 if (mLastANRState == null) {
4631 pw.println(" <no ANR has occurred since boot>");
4632 } else {
4633 pw.println(mLastANRState);
4634 }
4635 }
4636
4637 void dumpLastANRTracesLocked(PrintWriter pw) {
4638 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4639
4640 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4641 if (ArrayUtils.isEmpty(files)) {
4642 pw.println(" <no ANR has occurred since boot>");
4643 return;
4644 }
4645 // Find the latest file.
4646 File latest = null;
4647 for (File f : files) {
4648 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4649 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004650 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004651 }
4652 pw.print("File: ");
4653 pw.print(latest.getName());
4654 pw.println();
4655 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4656 String line;
4657 while ((line = in.readLine()) != null) {
4658 pw.println(line);
4659 }
4660 } catch (IOException e) {
4661 pw.print("Unable to read: ");
4662 pw.print(e);
4663 pw.println();
4664 }
4665 }
4666
4667 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4668 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4669 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4670 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4671 }
4672
4673 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4674 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4675 pw.println(header);
4676
Wale Ogunwaled32da472018-11-16 07:19:28 -08004677 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004678 dumpPackage);
4679 boolean needSep = printedAnything;
4680
4681 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004682 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004683 " ResumedActivity: ");
4684 if (printed) {
4685 printedAnything = true;
4686 needSep = false;
4687 }
4688
4689 if (dumpPackage == null) {
4690 if (needSep) {
4691 pw.println();
4692 }
4693 printedAnything = true;
4694 mStackSupervisor.dump(pw, " ");
4695 }
4696
4697 if (!printedAnything) {
4698 pw.println(" (nothing)");
4699 }
4700 }
4701
4702 void dumpActivityContainersLocked(PrintWriter pw) {
4703 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004704 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004705 pw.println(" ");
4706 }
4707
4708 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4709 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4710 getActivityStartController().dump(pw, "", dumpPackage);
4711 }
4712
4713 /**
4714 * There are three things that cmd can be:
4715 * - a flattened component name that matches an existing activity
4716 * - the cmd arg isn't the flattened component name of an existing activity:
4717 * dump all activity whose component contains the cmd as a substring
4718 * - A hex number of the ActivityRecord object instance.
4719 *
4720 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4721 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4722 */
4723 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4724 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4725 ArrayList<ActivityRecord> activities;
4726
4727 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004728 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004729 dumpFocusedStackOnly);
4730 }
4731
4732 if (activities.size() <= 0) {
4733 return false;
4734 }
4735
4736 String[] newArgs = new String[args.length - opti];
4737 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4738
4739 TaskRecord lastTask = null;
4740 boolean needSep = false;
4741 for (int i = activities.size() - 1; i >= 0; i--) {
4742 ActivityRecord r = activities.get(i);
4743 if (needSep) {
4744 pw.println();
4745 }
4746 needSep = true;
4747 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004748 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004749 if (lastTask != task) {
4750 lastTask = task;
4751 pw.print("TASK "); pw.print(lastTask.affinity);
4752 pw.print(" id="); pw.print(lastTask.taskId);
4753 pw.print(" userId="); pw.println(lastTask.userId);
4754 if (dumpAll) {
4755 lastTask.dump(pw, " ");
4756 }
4757 }
4758 }
4759 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4760 }
4761 return true;
4762 }
4763
4764 /**
4765 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4766 * there is a thread associated with the activity.
4767 */
4768 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4769 final ActivityRecord r, String[] args, boolean dumpAll) {
4770 String innerPrefix = prefix + " ";
4771 synchronized (mGlobalLock) {
4772 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4773 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4774 pw.print(" pid=");
4775 if (r.hasProcess()) pw.println(r.app.getPid());
4776 else pw.println("(not running)");
4777 if (dumpAll) {
4778 r.dump(pw, innerPrefix);
4779 }
4780 }
4781 if (r.attachedToProcess()) {
4782 // flush anything that is already in the PrintWriter since the thread is going
4783 // to write to the file descriptor directly
4784 pw.flush();
4785 try {
4786 TransferPipe tp = new TransferPipe();
4787 try {
4788 r.app.getThread().dumpActivity(tp.getWriteFd(),
4789 r.appToken, innerPrefix, args);
4790 tp.go(fd);
4791 } finally {
4792 tp.kill();
4793 }
4794 } catch (IOException e) {
4795 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4796 } catch (RemoteException e) {
4797 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4798 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004799 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004800 }
4801
sanryhuang498e77e2018-12-06 14:57:01 +08004802 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4803 boolean testPssMode) {
4804 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4805 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4806 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004807 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004808 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4809 st.toString());
4810 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004811 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4812 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4813 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004814 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4815 testPssMode);
4816 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004817 }
4818
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004819 int getCurrentUserId() {
4820 return mAmInternal.getCurrentUserId();
4821 }
4822
4823 private void enforceNotIsolatedCaller(String caller) {
4824 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4825 throw new SecurityException("Isolated process not allowed to call " + caller);
4826 }
4827 }
4828
Wale Ogunwalef6733932018-06-27 05:14:34 -07004829 public Configuration getConfiguration() {
4830 Configuration ci;
4831 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004832 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004833 ci.userSetLocale = false;
4834 }
4835 return ci;
4836 }
4837
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004838 /**
4839 * Current global configuration information. Contains general settings for the entire system,
4840 * also corresponds to the merged configuration of the default display.
4841 */
4842 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004843 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004844 }
4845
4846 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4847 boolean initLocale) {
4848 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4849 }
4850
4851 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4852 boolean initLocale, boolean deferResume) {
4853 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4854 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4855 UserHandle.USER_NULL, deferResume);
4856 }
4857
Wale Ogunwale59507092018-10-29 09:00:30 -07004858 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004859 final long origId = Binder.clearCallingIdentity();
4860 try {
4861 synchronized (mGlobalLock) {
4862 updateConfigurationLocked(values, null, false, true, userId,
4863 false /* deferResume */);
4864 }
4865 } finally {
4866 Binder.restoreCallingIdentity(origId);
4867 }
4868 }
4869
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004870 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4871 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4872 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4873 deferResume, null /* result */);
4874 }
4875
4876 /**
4877 * Do either or both things: (1) change the current configuration, and (2)
4878 * make sure the given activity is running with the (now) current
4879 * configuration. Returns true if the activity has been left running, or
4880 * false if <var>starting</var> is being destroyed to match the new
4881 * configuration.
4882 *
4883 * @param userId is only used when persistent parameter is set to true to persist configuration
4884 * for that particular user
4885 */
4886 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4887 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4888 ActivityTaskManagerService.UpdateConfigurationResult result) {
4889 int changes = 0;
4890 boolean kept = true;
4891
4892 if (mWindowManager != null) {
4893 mWindowManager.deferSurfaceLayout();
4894 }
4895 try {
4896 if (values != null) {
4897 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4898 deferResume);
4899 }
4900
4901 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4902 } finally {
4903 if (mWindowManager != null) {
4904 mWindowManager.continueSurfaceLayout();
4905 }
4906 }
4907
4908 if (result != null) {
4909 result.changes = changes;
4910 result.activityRelaunched = !kept;
4911 }
4912 return kept;
4913 }
4914
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004915 /** Update default (global) configuration and notify listeners about changes. */
4916 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4917 boolean persistent, int userId, boolean deferResume) {
4918 mTempConfig.setTo(getGlobalConfiguration());
4919 final int changes = mTempConfig.updateFrom(values);
4920 if (changes == 0) {
4921 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4922 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4923 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4924 // (even if there are no actual changes) to unfreeze the window.
4925 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4926 return 0;
4927 }
4928
4929 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4930 "Updating global configuration to: " + values);
4931
4932 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4933 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4934 values.colorMode,
4935 values.densityDpi,
4936 values.fontScale,
4937 values.hardKeyboardHidden,
4938 values.keyboard,
4939 values.keyboardHidden,
4940 values.mcc,
4941 values.mnc,
4942 values.navigation,
4943 values.navigationHidden,
4944 values.orientation,
4945 values.screenHeightDp,
4946 values.screenLayout,
4947 values.screenWidthDp,
4948 values.smallestScreenWidthDp,
4949 values.touchscreen,
4950 values.uiMode);
4951
4952
4953 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4954 final LocaleList locales = values.getLocales();
4955 int bestLocaleIndex = 0;
4956 if (locales.size() > 1) {
4957 if (mSupportedSystemLocales == null) {
4958 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4959 }
4960 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4961 }
4962 SystemProperties.set("persist.sys.locale",
4963 locales.get(bestLocaleIndex).toLanguageTag());
4964 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004965
4966 final Message m = PooledLambda.obtainMessage(
4967 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4968 locales.get(bestLocaleIndex));
4969 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004970 }
4971
Yunfan Chen75157d72018-07-27 14:47:21 +09004972 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004973
4974 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004975 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004976
4977 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4978 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004979 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004980
4981 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004982 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004983
4984 AttributeCache ac = AttributeCache.instance();
4985 if (ac != null) {
4986 ac.updateConfiguration(mTempConfig);
4987 }
4988
4989 // Make sure all resources in our process are updated right now, so that anyone who is going
4990 // to retrieve resource values after we return will be sure to get the new ones. This is
4991 // especially important during boot, where the first config change needs to guarantee all
4992 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004993 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004994
4995 // We need another copy of global config because we're scheduling some calls instead of
4996 // running them in place. We need to be sure that object we send will be handled unchanged.
4997 final Configuration configCopy = new Configuration(mTempConfig);
4998 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004999 final Message msg = PooledLambda.obtainMessage(
5000 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5001 this, userId, configCopy);
5002 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005003 }
5004
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005005 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005006 final int pid = mPidMap.keyAt(i);
5007 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005008 if (DEBUG_CONFIGURATION) {
5009 Slog.v(TAG_CONFIGURATION, "Update process config of "
5010 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005011 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005012 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005013 }
5014
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005015 final Message msg = PooledLambda.obtainMessage(
5016 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5017 mAmInternal, changes, initLocale);
5018 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005019
5020 // Override configuration of the default display duplicates global config, so we need to
5021 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005022 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005023 DEFAULT_DISPLAY);
5024
5025 return changes;
5026 }
5027
5028 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5029 boolean deferResume, int displayId) {
5030 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5031 displayId, null /* result */);
5032 }
5033
5034 /**
5035 * Updates override configuration specific for the selected display. If no config is provided,
5036 * new one will be computed in WM based on current display info.
5037 */
5038 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5039 ActivityRecord starting, boolean deferResume, int displayId,
5040 ActivityTaskManagerService.UpdateConfigurationResult result) {
5041 int changes = 0;
5042 boolean kept = true;
5043
5044 if (mWindowManager != null) {
5045 mWindowManager.deferSurfaceLayout();
5046 }
5047 try {
5048 if (values != null) {
5049 if (displayId == DEFAULT_DISPLAY) {
5050 // Override configuration of the default display duplicates global config, so
5051 // we're calling global config update instead for default display. It will also
5052 // apply the correct override config.
5053 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5054 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5055 } else {
5056 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5057 }
5058 }
5059
5060 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5061 } finally {
5062 if (mWindowManager != null) {
5063 mWindowManager.continueSurfaceLayout();
5064 }
5065 }
5066
5067 if (result != null) {
5068 result.changes = changes;
5069 result.activityRelaunched = !kept;
5070 }
5071 return kept;
5072 }
5073
5074 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5075 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005076 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005077 final int changes = mTempConfig.updateFrom(values);
5078 if (changes != 0) {
5079 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5080 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005081 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005082
5083 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5084 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005085 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005086
Wale Ogunwale5c918702018-10-18 11:06:33 -07005087 // Post message to start process to avoid possible deadlock of calling into AMS with
5088 // the ATMS lock held.
5089 final Message msg = PooledLambda.obtainMessage(
5090 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5091 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5092 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005093 }
5094 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005095 return changes;
5096 }
5097
Wale Ogunwalef6733932018-06-27 05:14:34 -07005098 private void updateEventDispatchingLocked(boolean booted) {
5099 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5100 }
5101
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005102 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5103 final ContentResolver resolver = mContext.getContentResolver();
5104 Settings.System.putConfigurationForUser(resolver, config, userId);
5105 }
5106
5107 private void sendLocaleToMountDaemonMsg(Locale l) {
5108 try {
5109 IBinder service = ServiceManager.getService("mount");
5110 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5111 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5112 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5113 } catch (RemoteException e) {
5114 Log.e(TAG, "Error storing locale for decryption UI", e);
5115 }
5116 }
5117
Alison Cichowlas3e340502018-08-07 17:15:01 -04005118 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5119 mStartActivitySources.remove(permissionToken);
5120 mExpiredStartAsCallerTokens.add(permissionToken);
5121 }
5122
5123 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5124 mExpiredStartAsCallerTokens.remove(permissionToken);
5125 }
5126
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005127 boolean isActivityStartsLoggingEnabled() {
5128 return mAmInternal.isActivityStartsLoggingEnabled();
5129 }
5130
Michal Karpinski8596ded2018-11-14 14:43:48 +00005131 boolean isBackgroundActivityStartsEnabled() {
5132 return mAmInternal.isBackgroundActivityStartsEnabled();
5133 }
5134
Wale Ogunwalef6733932018-06-27 05:14:34 -07005135 void enableScreenAfterBoot(boolean booted) {
5136 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5137 SystemClock.uptimeMillis());
5138 mWindowManager.enableScreenAfterBoot();
5139
5140 synchronized (mGlobalLock) {
5141 updateEventDispatchingLocked(booted);
5142 }
5143 }
5144
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005145 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5146 if (r == null || !r.hasProcess()) {
5147 return KEY_DISPATCHING_TIMEOUT_MS;
5148 }
5149 return getInputDispatchingTimeoutLocked(r.app);
5150 }
5151
5152 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005153 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005154 }
5155
Wale Ogunwalef6733932018-06-27 05:14:34 -07005156 /**
5157 * Decide based on the configuration whether we should show the ANR,
5158 * crash, etc dialogs. The idea is that if there is no affordance to
5159 * press the on-screen buttons, or the user experience would be more
5160 * greatly impacted than the crash itself, we shouldn't show the dialog.
5161 *
5162 * A thought: SystemUI might also want to get told about this, the Power
5163 * dialog / global actions also might want different behaviors.
5164 */
5165 private void updateShouldShowDialogsLocked(Configuration config) {
5166 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5167 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5168 && config.navigation == Configuration.NAVIGATION_NONAV);
5169 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5170 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5171 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5172 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5173 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5174 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5175 HIDE_ERROR_DIALOGS, 0) != 0;
5176 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5177 }
5178
5179 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5180 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5181 FONT_SCALE, 1.0f, userId);
5182
5183 synchronized (this) {
5184 if (getGlobalConfiguration().fontScale == scaleFactor) {
5185 return;
5186 }
5187
5188 final Configuration configuration
5189 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5190 configuration.fontScale = scaleFactor;
5191 updatePersistentConfiguration(configuration, userId);
5192 }
5193 }
5194
5195 // Actually is sleeping or shutting down or whatever else in the future
5196 // is an inactive state.
5197 boolean isSleepingOrShuttingDownLocked() {
5198 return isSleepingLocked() || mShuttingDown;
5199 }
5200
5201 boolean isSleepingLocked() {
5202 return mSleeping;
5203 }
5204
Riddle Hsu16567132018-08-16 21:37:47 +08005205 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005206 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005207 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005208 if (task.isActivityTypeStandard()) {
5209 if (mCurAppTimeTracker != r.appTimeTracker) {
5210 // We are switching app tracking. Complete the current one.
5211 if (mCurAppTimeTracker != null) {
5212 mCurAppTimeTracker.stop();
5213 mH.obtainMessage(
5214 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005215 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005216 mCurAppTimeTracker = null;
5217 }
5218 if (r.appTimeTracker != null) {
5219 mCurAppTimeTracker = r.appTimeTracker;
5220 startTimeTrackingFocusedActivityLocked();
5221 }
5222 } else {
5223 startTimeTrackingFocusedActivityLocked();
5224 }
5225 } else {
5226 r.appTimeTracker = null;
5227 }
5228 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5229 // TODO: Probably not, because we don't want to resume voice on switching
5230 // back to this activity
5231 if (task.voiceInteractor != null) {
5232 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5233 } else {
5234 finishRunningVoiceLocked();
5235
5236 if (mLastResumedActivity != null) {
5237 final IVoiceInteractionSession session;
5238
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005239 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005240 if (lastResumedActivityTask != null
5241 && lastResumedActivityTask.voiceSession != null) {
5242 session = lastResumedActivityTask.voiceSession;
5243 } else {
5244 session = mLastResumedActivity.voiceSession;
5245 }
5246
5247 if (session != null) {
5248 // We had been in a voice interaction session, but now focused has
5249 // move to something different. Just finish the session, we can't
5250 // return to it and retain the proper state and synchronization with
5251 // the voice interaction service.
5252 finishVoiceTask(session);
5253 }
5254 }
5255 }
5256
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005257 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5258 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005259 }
5260 updateResumedAppTrace(r);
5261 mLastResumedActivity = r;
5262
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005263 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005264
5265 applyUpdateLockStateLocked(r);
5266 applyUpdateVrModeLocked(r);
5267
5268 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005269 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005270 r == null ? "NULL" : r.shortComponentName,
5271 reason);
5272 }
5273
5274 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5275 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005276 final ActivityTaskManagerInternal.SleepToken token =
5277 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005278 updateSleepIfNeededLocked();
5279 return token;
5280 }
5281 }
5282
5283 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005284 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005285 final boolean wasSleeping = mSleeping;
5286 boolean updateOomAdj = false;
5287
5288 if (!shouldSleep) {
5289 // If wasSleeping is true, we need to wake up activity manager state from when
5290 // we started sleeping. In either case, we need to apply the sleep tokens, which
5291 // will wake up stacks or put them to sleep as appropriate.
5292 if (wasSleeping) {
5293 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005294 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5295 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005296 startTimeTrackingFocusedActivityLocked();
5297 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5298 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5299 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005300 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005301 if (wasSleeping) {
5302 updateOomAdj = true;
5303 }
5304 } else if (!mSleeping && shouldSleep) {
5305 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005306 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5307 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308 if (mCurAppTimeTracker != null) {
5309 mCurAppTimeTracker.stop();
5310 }
5311 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5312 mStackSupervisor.goingToSleepLocked();
5313 updateResumedAppTrace(null /* resumed */);
5314 updateOomAdj = true;
5315 }
5316 if (updateOomAdj) {
5317 mH.post(mAmInternal::updateOomAdj);
5318 }
5319 }
5320
5321 void updateOomAdj() {
5322 mH.post(mAmInternal::updateOomAdj);
5323 }
5324
Wale Ogunwale53783742018-09-16 10:21:51 -07005325 void updateCpuStats() {
5326 mH.post(mAmInternal::updateCpuStats);
5327 }
5328
Hui Yu03d12402018-12-06 18:00:37 -08005329 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5330 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005331 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5332 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005333 mH.sendMessage(m);
5334 }
5335
Hui Yu03d12402018-12-06 18:00:37 -08005336 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005337 ComponentName taskRoot = null;
5338 final TaskRecord task = activity.getTaskRecord();
5339 if (task != null) {
5340 final ActivityRecord rootActivity = task.getRootActivity();
5341 if (rootActivity != null) {
5342 taskRoot = rootActivity.mActivityComponent;
5343 }
5344 }
5345
Hui Yu03d12402018-12-06 18:00:37 -08005346 final Message m = PooledLambda.obtainMessage(
5347 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005348 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005349 mH.sendMessage(m);
5350 }
5351
Wale Ogunwale53783742018-09-16 10:21:51 -07005352 void setBooting(boolean booting) {
5353 mAmInternal.setBooting(booting);
5354 }
5355
5356 boolean isBooting() {
5357 return mAmInternal.isBooting();
5358 }
5359
5360 void setBooted(boolean booted) {
5361 mAmInternal.setBooted(booted);
5362 }
5363
5364 boolean isBooted() {
5365 return mAmInternal.isBooted();
5366 }
5367
5368 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5369 mH.post(() -> {
5370 if (finishBooting) {
5371 mAmInternal.finishBooting();
5372 }
5373 if (enableScreen) {
5374 mInternal.enableScreenAfterBoot(isBooted());
5375 }
5376 });
5377 }
5378
5379 void setHeavyWeightProcess(ActivityRecord root) {
5380 mHeavyWeightProcess = root.app;
5381 final Message m = PooledLambda.obtainMessage(
5382 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005383 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005384 mH.sendMessage(m);
5385 }
5386
5387 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5388 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5389 return;
5390 }
5391
5392 mHeavyWeightProcess = null;
5393 final Message m = PooledLambda.obtainMessage(
5394 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5395 proc.mUserId);
5396 mH.sendMessage(m);
5397 }
5398
5399 private void cancelHeavyWeightProcessNotification(int userId) {
5400 final INotificationManager inm = NotificationManager.getService();
5401 if (inm == null) {
5402 return;
5403 }
5404 try {
5405 inm.cancelNotificationWithTag("android", null,
5406 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5407 } catch (RuntimeException e) {
5408 Slog.w(TAG, "Error canceling notification for service", e);
5409 } catch (RemoteException e) {
5410 }
5411
5412 }
5413
5414 private void postHeavyWeightProcessNotification(
5415 WindowProcessController proc, Intent intent, int userId) {
5416 if (proc == null) {
5417 return;
5418 }
5419
5420 final INotificationManager inm = NotificationManager.getService();
5421 if (inm == null) {
5422 return;
5423 }
5424
5425 try {
5426 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5427 String text = mContext.getString(R.string.heavy_weight_notification,
5428 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5429 Notification notification =
5430 new Notification.Builder(context,
5431 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5432 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5433 .setWhen(0)
5434 .setOngoing(true)
5435 .setTicker(text)
5436 .setColor(mContext.getColor(
5437 com.android.internal.R.color.system_notification_accent_color))
5438 .setContentTitle(text)
5439 .setContentText(
5440 mContext.getText(R.string.heavy_weight_notification_detail))
5441 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5442 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5443 new UserHandle(userId)))
5444 .build();
5445 try {
5446 inm.enqueueNotificationWithTag("android", "android", null,
5447 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5448 } catch (RuntimeException e) {
5449 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5450 } catch (RemoteException e) {
5451 }
5452 } catch (PackageManager.NameNotFoundException e) {
5453 Slog.w(TAG, "Unable to create context for heavy notification", e);
5454 }
5455
5456 }
5457
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005458 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5459 IBinder token, String resultWho, int requestCode, Intent[] intents,
5460 String[] resolvedTypes, int flags, Bundle bOptions) {
5461
5462 ActivityRecord activity = null;
5463 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5464 activity = ActivityRecord.isInStackLocked(token);
5465 if (activity == null) {
5466 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5467 return null;
5468 }
5469 if (activity.finishing) {
5470 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5471 return null;
5472 }
5473 }
5474
5475 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5476 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5477 bOptions);
5478 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5479 if (noCreate) {
5480 return rec;
5481 }
5482 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5483 if (activity.pendingResults == null) {
5484 activity.pendingResults = new HashSet<>();
5485 }
5486 activity.pendingResults.add(rec.ref);
5487 }
5488 return rec;
5489 }
5490
Andrii Kulian52d255c2018-07-13 11:32:19 -07005491 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005492 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005493 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005494 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5495 mCurAppTimeTracker.start(resumedActivity.packageName);
5496 }
5497 }
5498
5499 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5500 if (mTracedResumedActivity != null) {
5501 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5502 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5503 }
5504 if (resumed != null) {
5505 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5506 constructResumedTraceName(resumed.packageName), 0);
5507 }
5508 mTracedResumedActivity = resumed;
5509 }
5510
5511 private String constructResumedTraceName(String packageName) {
5512 return "focused app: " + packageName;
5513 }
5514
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005515 /** Applies latest configuration and/or visibility updates if needed. */
5516 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5517 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005518 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005519 // mainStack is null during startup.
5520 if (mainStack != null) {
5521 if (changes != 0 && starting == null) {
5522 // If the configuration changed, and the caller is not already
5523 // in the process of starting an activity, then find the top
5524 // activity to check if its configuration needs to change.
5525 starting = mainStack.topRunningActivityLocked();
5526 }
5527
5528 if (starting != null) {
5529 kept = starting.ensureActivityConfiguration(changes,
5530 false /* preserveWindow */);
5531 // And we need to make sure at this point that all other activities
5532 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005533 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005534 !PRESERVE_WINDOWS);
5535 }
5536 }
5537
5538 return kept;
5539 }
5540
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005541 void scheduleAppGcsLocked() {
5542 mH.post(() -> mAmInternal.scheduleAppGcs());
5543 }
5544
Wale Ogunwale53783742018-09-16 10:21:51 -07005545 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5546 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5547 }
5548
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005549 /**
5550 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5551 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5552 * on demand.
5553 */
5554 IPackageManager getPackageManager() {
5555 return AppGlobals.getPackageManager();
5556 }
5557
5558 PackageManagerInternal getPackageManagerInternalLocked() {
5559 if (mPmInternal == null) {
5560 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5561 }
5562 return mPmInternal;
5563 }
5564
Wale Ogunwale008163e2018-07-23 23:11:08 -07005565 AppWarnings getAppWarningsLocked() {
5566 return mAppWarnings;
5567 }
5568
Wale Ogunwale214f3482018-10-04 11:00:47 -07005569 Intent getHomeIntent() {
5570 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5571 intent.setComponent(mTopComponent);
5572 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5573 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5574 intent.addCategory(Intent.CATEGORY_HOME);
5575 }
5576 return intent;
5577 }
5578
Chilun2ef71f72018-11-16 17:57:15 +08005579 /**
5580 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5581 * activities.
5582 *
5583 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5584 * component defined in config_secondaryHomeComponent.
5585 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5586 */
5587 Intent getSecondaryHomeIntent(String preferredPackage) {
5588 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5589 if (preferredPackage == null) {
5590 // Using the component stored in config if no package name.
5591 final String secondaryHomeComponent = mContext.getResources().getString(
5592 com.android.internal.R.string.config_secondaryHomeComponent);
5593 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5594 } else {
5595 intent.setPackage(preferredPackage);
5596 }
5597 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5598 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5599 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5600 }
5601 return intent;
5602 }
5603
Wale Ogunwale214f3482018-10-04 11:00:47 -07005604 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5605 if (info == null) return null;
5606 ApplicationInfo newInfo = new ApplicationInfo(info);
5607 newInfo.initForUser(userId);
5608 return newInfo;
5609 }
5610
Wale Ogunwale9c103022018-10-18 07:44:54 -07005611 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005612 if (uid == SYSTEM_UID) {
5613 // The system gets to run in any process. If there are multiple processes with the same
5614 // uid, just pick the first (this should never happen).
5615 final SparseArray<WindowProcessController> procs =
5616 mProcessNames.getMap().get(processName);
5617 if (procs == null) return null;
5618 final int procCount = procs.size();
5619 for (int i = 0; i < procCount; i++) {
5620 final int procUid = procs.keyAt(i);
5621 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5622 // Don't use an app process or different user process for system component.
5623 continue;
5624 }
5625 return procs.valueAt(i);
5626 }
5627 }
5628
5629 return mProcessNames.get(processName, uid);
5630 }
5631
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005632 WindowProcessController getProcessController(IApplicationThread thread) {
5633 if (thread == null) {
5634 return null;
5635 }
5636
5637 final IBinder threadBinder = thread.asBinder();
5638 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5639 for (int i = pmap.size()-1; i >= 0; i--) {
5640 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5641 for (int j = procs.size() - 1; j >= 0; j--) {
5642 final WindowProcessController proc = procs.valueAt(j);
5643 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5644 return proc;
5645 }
5646 }
5647 }
5648
5649 return null;
5650 }
5651
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005652 int getUidStateLocked(int uid) {
5653 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5654 }
5655
Wale Ogunwale9de19442018-10-18 19:05:03 -07005656 /**
5657 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5658 * the whitelist
5659 */
5660 String getPendingTempWhitelistTagForUidLocked(int uid) {
5661 return mPendingTempWhitelist.get(uid);
5662 }
5663
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005664 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5665 if (true || Build.IS_USER) {
5666 return;
5667 }
5668
5669 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5670 StrictMode.allowThreadDiskWrites();
5671 try {
5672 File tracesDir = new File("/data/anr");
5673 File tracesFile = null;
5674 try {
5675 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5676
5677 StringBuilder sb = new StringBuilder();
5678 Time tobj = new Time();
5679 tobj.set(System.currentTimeMillis());
5680 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5681 sb.append(": ");
5682 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5683 sb.append(" since ");
5684 sb.append(msg);
5685 FileOutputStream fos = new FileOutputStream(tracesFile);
5686 fos.write(sb.toString().getBytes());
5687 if (app == null) {
5688 fos.write("\n*** No application process!".getBytes());
5689 }
5690 fos.close();
5691 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5692 } catch (IOException e) {
5693 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5694 return;
5695 }
5696
5697 if (app != null && app.getPid() > 0) {
5698 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5699 firstPids.add(app.getPid());
5700 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5701 }
5702
5703 File lastTracesFile = null;
5704 File curTracesFile = null;
5705 for (int i=9; i>=0; i--) {
5706 String name = String.format(Locale.US, "slow%02d.txt", i);
5707 curTracesFile = new File(tracesDir, name);
5708 if (curTracesFile.exists()) {
5709 if (lastTracesFile != null) {
5710 curTracesFile.renameTo(lastTracesFile);
5711 } else {
5712 curTracesFile.delete();
5713 }
5714 }
5715 lastTracesFile = curTracesFile;
5716 }
5717 tracesFile.renameTo(curTracesFile);
5718 } finally {
5719 StrictMode.setThreadPolicy(oldPolicy);
5720 }
5721 }
5722
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005723 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005724 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005725
5726
Wale Ogunwale98875612018-10-12 07:53:02 -07005727 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5728 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005729
Riddle Hsud93a6c42018-11-29 21:50:06 +08005730 H(Looper looper) {
5731 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005732 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005733
5734 @Override
5735 public void handleMessage(Message msg) {
5736 switch (msg.what) {
5737 case REPORT_TIME_TRACKER_MSG: {
5738 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5739 tracker.deliverResult(mContext);
5740 } break;
5741 }
5742 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005743 }
5744
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005745 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005746 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005747
5748 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005749 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005750 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005751
5752 @Override
5753 public void handleMessage(Message msg) {
5754 switch (msg.what) {
5755 case DISMISS_DIALOG_UI_MSG: {
5756 final Dialog d = (Dialog) msg.obj;
5757 d.dismiss();
5758 break;
5759 }
5760 }
5761 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005762 }
5763
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005764 final class LocalService extends ActivityTaskManagerInternal {
5765 @Override
5766 public SleepToken acquireSleepToken(String tag, int displayId) {
5767 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005768 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005769 }
5770
5771 @Override
5772 public ComponentName getHomeActivityForUser(int userId) {
5773 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005774 final ActivityRecord homeActivity =
5775 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005776 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005777 }
5778 }
5779
5780 @Override
5781 public void onLocalVoiceInteractionStarted(IBinder activity,
5782 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5783 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005784 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005785 }
5786 }
5787
5788 @Override
5789 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5790 synchronized (mGlobalLock) {
5791 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5792 reasons, timestamp);
5793 }
5794 }
5795
5796 @Override
5797 public void notifyAppTransitionFinished() {
5798 synchronized (mGlobalLock) {
5799 mStackSupervisor.notifyAppTransitionDone();
5800 }
5801 }
5802
5803 @Override
5804 public void notifyAppTransitionCancelled() {
5805 synchronized (mGlobalLock) {
5806 mStackSupervisor.notifyAppTransitionDone();
5807 }
5808 }
5809
5810 @Override
5811 public List<IBinder> getTopVisibleActivities() {
5812 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005813 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005814 }
5815 }
5816
5817 @Override
5818 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5819 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005820 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005821 }
5822 }
5823
5824 @Override
5825 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5826 Bundle bOptions) {
5827 Preconditions.checkNotNull(intents, "intents");
5828 final String[] resolvedTypes = new String[intents.length];
5829
5830 // UID of the package on user userId.
5831 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5832 // packageUid may not be initialized.
5833 int packageUid = 0;
5834 final long ident = Binder.clearCallingIdentity();
5835
5836 try {
5837 for (int i = 0; i < intents.length; i++) {
5838 resolvedTypes[i] =
5839 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5840 }
5841
5842 packageUid = AppGlobals.getPackageManager().getPackageUid(
5843 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5844 } catch (RemoteException e) {
5845 // Shouldn't happen.
5846 } finally {
5847 Binder.restoreCallingIdentity(ident);
5848 }
5849
5850 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005851 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005852 packageUid, packageName,
5853 intents, resolvedTypes, null /* resultTo */,
5854 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005855 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5856 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005857 }
5858 }
5859
5860 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005861 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5862 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5863 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5864 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005865 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005866 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005867 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5868 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5869 userId, validateIncomingUser, originatingPendingIntent,
5870 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005871 }
5872 }
5873
5874 @Override
5875 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5876 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5877 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5878 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005879 PendingIntentRecord originatingPendingIntent,
5880 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005881 synchronized (mGlobalLock) {
5882 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5883 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5884 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005885 validateIncomingUser, originatingPendingIntent,
5886 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005887 }
5888 }
5889
5890 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005891 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5892 Intent intent, Bundle options, int userId) {
5893 return ActivityTaskManagerService.this.startActivityAsUser(
5894 caller, callerPacakge, intent,
5895 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5896 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5897 false /*validateIncomingUser*/);
5898 }
5899
5900 @Override
lumark588a3e82018-07-20 18:53:54 +08005901 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005902 synchronized (mGlobalLock) {
5903
5904 // We might change the visibilities here, so prepare an empty app transition which
5905 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005906 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005907 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005908 if (activityDisplay == null) {
5909 return;
5910 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005911 final DisplayContent dc = activityDisplay.mDisplayContent;
5912 final boolean wasTransitionSet =
5913 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005914 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005915 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005916 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005917 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005918
5919 // If there was a transition set already we don't want to interfere with it as we
5920 // might be starting it too early.
5921 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005922 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005923 }
5924 }
5925 if (callback != null) {
5926 callback.run();
5927 }
5928 }
5929
5930 @Override
5931 public void notifyKeyguardTrustedChanged() {
5932 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005933 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005934 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005935 }
5936 }
5937 }
5938
5939 /**
5940 * Called after virtual display Id is updated by
5941 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5942 * {@param vrVr2dDisplayId}.
5943 */
5944 @Override
5945 public void setVr2dDisplayId(int vr2dDisplayId) {
5946 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5947 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005948 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005949 }
5950 }
5951
5952 @Override
5953 public void setFocusedActivity(IBinder token) {
5954 synchronized (mGlobalLock) {
5955 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5956 if (r == null) {
5957 throw new IllegalArgumentException(
5958 "setFocusedActivity: No activity record matching token=" + token);
5959 }
Louis Chang19443452018-10-09 12:10:21 +08005960 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005961 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005962 }
5963 }
5964 }
5965
5966 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005967 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005968 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005969 }
5970
5971 @Override
5972 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005973 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005974 }
5975
5976 @Override
5977 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005978 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005979 }
5980
5981 @Override
5982 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5983 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5984 }
5985
5986 @Override
5987 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005988 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005989 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005990
5991 @Override
5992 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5993 synchronized (mGlobalLock) {
5994 mActiveVoiceInteractionServiceComponent = component;
5995 }
5996 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005997
5998 @Override
5999 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6000 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6001 return;
6002 }
6003 synchronized (mGlobalLock) {
6004 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6005 if (types == null) {
6006 if (uid < 0) {
6007 return;
6008 }
6009 types = new ArrayMap<>();
6010 mAllowAppSwitchUids.put(userId, types);
6011 }
6012 if (uid < 0) {
6013 types.remove(type);
6014 } else {
6015 types.put(type, uid);
6016 }
6017 }
6018 }
6019
6020 @Override
6021 public void onUserStopped(int userId) {
6022 synchronized (mGlobalLock) {
6023 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6024 mAllowAppSwitchUids.remove(userId);
6025 }
6026 }
6027
6028 @Override
6029 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6030 synchronized (mGlobalLock) {
6031 return ActivityTaskManagerService.this.isGetTasksAllowed(
6032 caller, callingPid, callingUid);
6033 }
6034 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006035
6036 @Override
6037 public void onProcessAdded(WindowProcessController proc) {
6038 synchronized (mGlobalLock) {
6039 mProcessNames.put(proc.mName, proc.mUid, proc);
6040 }
6041 }
6042
6043 @Override
6044 public void onProcessRemoved(String name, int uid) {
6045 synchronized (mGlobalLock) {
6046 mProcessNames.remove(name, uid);
6047 }
6048 }
6049
6050 @Override
6051 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6052 synchronized (mGlobalLock) {
6053 if (proc == mHomeProcess) {
6054 mHomeProcess = null;
6055 }
6056 if (proc == mPreviousProcess) {
6057 mPreviousProcess = null;
6058 }
6059 }
6060 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006061
6062 @Override
6063 public int getTopProcessState() {
6064 synchronized (mGlobalLock) {
6065 return mTopProcessState;
6066 }
6067 }
6068
6069 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006070 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6071 synchronized (mGlobalLock) {
6072 return proc == mHeavyWeightProcess;
6073 }
6074 }
6075
6076 @Override
6077 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6078 synchronized (mGlobalLock) {
6079 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6080 }
6081 }
6082
6083 @Override
6084 public void finishHeavyWeightApp() {
6085 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006086 if (mHeavyWeightProcess != null) {
6087 mHeavyWeightProcess.finishActivities();
6088 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006089 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6090 mHeavyWeightProcess);
6091 }
6092 }
6093
6094 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006095 public boolean isSleeping() {
6096 synchronized (mGlobalLock) {
6097 return isSleepingLocked();
6098 }
6099 }
6100
6101 @Override
6102 public boolean isShuttingDown() {
6103 synchronized (mGlobalLock) {
6104 return mShuttingDown;
6105 }
6106 }
6107
6108 @Override
6109 public boolean shuttingDown(boolean booted, int timeout) {
6110 synchronized (mGlobalLock) {
6111 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006112 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006113 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006114 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006115 return mStackSupervisor.shutdownLocked(timeout);
6116 }
6117 }
6118
6119 @Override
6120 public void enableScreenAfterBoot(boolean booted) {
6121 synchronized (mGlobalLock) {
6122 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6123 SystemClock.uptimeMillis());
6124 mWindowManager.enableScreenAfterBoot();
6125 updateEventDispatchingLocked(booted);
6126 }
6127 }
6128
6129 @Override
6130 public boolean showStrictModeViolationDialog() {
6131 synchronized (mGlobalLock) {
6132 return mShowDialogs && !mSleeping && !mShuttingDown;
6133 }
6134 }
6135
6136 @Override
6137 public void showSystemReadyErrorDialogsIfNeeded() {
6138 synchronized (mGlobalLock) {
6139 try {
6140 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6141 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6142 + " data partition or your device will be unstable.");
6143 mUiHandler.post(() -> {
6144 if (mShowDialogs) {
6145 AlertDialog d = new BaseErrorDialog(mUiContext);
6146 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6147 d.setCancelable(false);
6148 d.setTitle(mUiContext.getText(R.string.android_system_label));
6149 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6150 d.setButton(DialogInterface.BUTTON_POSITIVE,
6151 mUiContext.getText(R.string.ok),
6152 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6153 d.show();
6154 }
6155 });
6156 }
6157 } catch (RemoteException e) {
6158 }
6159
6160 if (!Build.isBuildConsistent()) {
6161 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6162 mUiHandler.post(() -> {
6163 if (mShowDialogs) {
6164 AlertDialog d = new BaseErrorDialog(mUiContext);
6165 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6166 d.setCancelable(false);
6167 d.setTitle(mUiContext.getText(R.string.android_system_label));
6168 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6169 d.setButton(DialogInterface.BUTTON_POSITIVE,
6170 mUiContext.getText(R.string.ok),
6171 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6172 d.show();
6173 }
6174 });
6175 }
6176 }
6177 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006178
6179 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006180 public void onProcessMapped(int pid, WindowProcessController proc) {
6181 synchronized (mGlobalLock) {
6182 mPidMap.put(pid, proc);
6183 }
6184 }
6185
6186 @Override
6187 public void onProcessUnMapped(int pid) {
6188 synchronized (mGlobalLock) {
6189 mPidMap.remove(pid);
6190 }
6191 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006192
6193 @Override
6194 public void onPackageDataCleared(String name) {
6195 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006196 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006197 mAppWarnings.onPackageDataCleared(name);
6198 }
6199 }
6200
6201 @Override
6202 public void onPackageUninstalled(String name) {
6203 synchronized (mGlobalLock) {
6204 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006205 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006206 }
6207 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006208
6209 @Override
6210 public void onPackageAdded(String name, boolean replacing) {
6211 synchronized (mGlobalLock) {
6212 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6213 }
6214 }
6215
6216 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006217 public void onPackageReplaced(ApplicationInfo aInfo) {
6218 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006219 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006220 }
6221 }
6222
6223 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006224 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6225 synchronized (mGlobalLock) {
6226 return compatibilityInfoForPackageLocked(ai);
6227 }
6228 }
6229
Yunfan Chen75157d72018-07-27 14:47:21 +09006230 /**
6231 * Set the corresponding display information for the process global configuration. To be
6232 * called when we need to show IME on a different display.
6233 *
6234 * @param pid The process id associated with the IME window.
6235 * @param displayId The ID of the display showing the IME.
6236 */
6237 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006238 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006239 if (pid == MY_PID || pid < 0) {
6240 if (DEBUG_CONFIGURATION) {
6241 Slog.w(TAG,
6242 "Trying to update display configuration for system/invalid process.");
6243 }
6244 return;
6245 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006246 synchronized (mGlobalLock) {
6247 final ActivityDisplay activityDisplay =
6248 mRootActivityContainer.getActivityDisplay(displayId);
6249 if (activityDisplay == null) {
6250 // Call might come when display is not yet added or has been removed.
6251 if (DEBUG_CONFIGURATION) {
6252 Slog.w(TAG, "Trying to update display configuration for non-existing "
6253 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006254 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006255 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006256 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006257 final WindowProcessController process = mPidMap.get(pid);
6258 if (process == null) {
6259 if (DEBUG_CONFIGURATION) {
6260 Slog.w(TAG, "Trying to update display configuration for invalid "
6261 + "process, pid=" + pid);
6262 }
6263 return;
6264 }
6265 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6266 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006267 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006268
6269 @Override
6270 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6271 int requestCode, int resultCode, Intent data) {
6272 synchronized (mGlobalLock) {
6273 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006274 if (r != null && r.getActivityStack() != null) {
6275 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6276 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006277 }
6278 }
6279 }
6280
6281 @Override
6282 public void clearPendingResultForActivity(IBinder activityToken,
6283 WeakReference<PendingIntentRecord> pir) {
6284 synchronized (mGlobalLock) {
6285 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6286 if (r != null && r.pendingResults != null) {
6287 r.pendingResults.remove(pir);
6288 }
6289 }
6290 }
6291
6292 @Override
6293 public IIntentSender getIntentSender(int type, String packageName,
6294 int callingUid, int userId, IBinder token, String resultWho,
6295 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6296 Bundle bOptions) {
6297 synchronized (mGlobalLock) {
6298 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6299 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6300 }
6301 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006302
6303 @Override
6304 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6305 synchronized (mGlobalLock) {
6306 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6307 if (r == null) {
6308 return null;
6309 }
6310 if (r.mServiceConnectionsHolder == null) {
6311 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6312 ActivityTaskManagerService.this, r);
6313 }
6314
6315 return r.mServiceConnectionsHolder;
6316 }
6317 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006318
6319 @Override
6320 public Intent getHomeIntent() {
6321 synchronized (mGlobalLock) {
6322 return ActivityTaskManagerService.this.getHomeIntent();
6323 }
6324 }
6325
6326 @Override
6327 public boolean startHomeActivity(int userId, String reason) {
6328 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006329 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006330 }
6331 }
6332
6333 @Override
6334 public boolean startHomeOnAllDisplays(int userId, String reason) {
6335 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006336 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006337 }
6338 }
6339
6340 @Override
6341 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6342 synchronized (mGlobalLock) {
6343 if (mFactoryTest == FACTORY_TEST_OFF) {
6344 return false;
6345 }
6346 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6347 && wpc.mName.equals(mTopComponent.getPackageName())) {
6348 return true;
6349 }
6350 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6351 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6352 }
6353 }
6354
6355 @Override
6356 public void updateTopComponentForFactoryTest() {
6357 synchronized (mGlobalLock) {
6358 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6359 return;
6360 }
6361 final ResolveInfo ri = mContext.getPackageManager()
6362 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6363 final CharSequence errorMsg;
6364 if (ri != null) {
6365 final ActivityInfo ai = ri.activityInfo;
6366 final ApplicationInfo app = ai.applicationInfo;
6367 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6368 mTopAction = Intent.ACTION_FACTORY_TEST;
6369 mTopData = null;
6370 mTopComponent = new ComponentName(app.packageName, ai.name);
6371 errorMsg = null;
6372 } else {
6373 errorMsg = mContext.getResources().getText(
6374 com.android.internal.R.string.factorytest_not_system);
6375 }
6376 } else {
6377 errorMsg = mContext.getResources().getText(
6378 com.android.internal.R.string.factorytest_no_action);
6379 }
6380 if (errorMsg == null) {
6381 return;
6382 }
6383
6384 mTopAction = null;
6385 mTopData = null;
6386 mTopComponent = null;
6387 mUiHandler.post(() -> {
6388 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6389 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006390 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006391 });
6392 }
6393 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006394
6395 @Override
6396 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6397 Runnable finishInstrumentationCallback) {
6398 synchronized (mGlobalLock) {
6399 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006400 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006401
6402 wpc.clearRecentTasks();
6403 wpc.clearActivities();
6404
6405 if (wpc.isInstrumenting()) {
6406 finishInstrumentationCallback.run();
6407 }
6408
Jorim Jaggid0752812018-10-16 16:07:20 +02006409 if (!restarting && hasVisibleActivities) {
6410 mWindowManager.deferSurfaceLayout();
6411 try {
6412 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6413 // If there was nothing to resume, and we are not already restarting
6414 // this process, but there is a visible activity that is hosted by the
6415 // process...then make sure all visible activities are running, taking
6416 // care of restarting this process.
6417 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6418 !PRESERVE_WINDOWS);
6419 }
6420 } finally {
6421 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006422 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006423 }
6424 }
6425 }
6426
6427 @Override
6428 public void closeSystemDialogs(String reason) {
6429 enforceNotIsolatedCaller("closeSystemDialogs");
6430
6431 final int pid = Binder.getCallingPid();
6432 final int uid = Binder.getCallingUid();
6433 final long origId = Binder.clearCallingIdentity();
6434 try {
6435 synchronized (mGlobalLock) {
6436 // Only allow this from foreground processes, so that background
6437 // applications can't abuse it to prevent system UI from being shown.
6438 if (uid >= FIRST_APPLICATION_UID) {
6439 final WindowProcessController proc = mPidMap.get(pid);
6440 if (!proc.isPerceptible()) {
6441 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6442 + " from background process " + proc);
6443 return;
6444 }
6445 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006446 mWindowManager.closeSystemDialogs(reason);
6447
Wale Ogunwaled32da472018-11-16 07:19:28 -08006448 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006449 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006450 // Call into AM outside the synchronized block.
6451 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006452 } finally {
6453 Binder.restoreCallingIdentity(origId);
6454 }
6455 }
6456
6457 @Override
6458 public void cleanupDisabledPackageComponents(
6459 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6460 synchronized (mGlobalLock) {
6461 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006462 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006463 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006464 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006465 mStackSupervisor.scheduleIdleLocked();
6466 }
6467
6468 // Clean-up disabled tasks
6469 getRecentTasks().cleanupDisabledPackageTasksLocked(
6470 packageName, disabledClasses, userId);
6471 }
6472 }
6473
6474 @Override
6475 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6476 int userId) {
6477 synchronized (mGlobalLock) {
6478
6479 boolean didSomething =
6480 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006481 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006482 null, doit, evenPersistent, userId);
6483 return didSomething;
6484 }
6485 }
6486
6487 @Override
6488 public void resumeTopActivities(boolean scheduleIdle) {
6489 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006490 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006491 if (scheduleIdle) {
6492 mStackSupervisor.scheduleIdleLocked();
6493 }
6494 }
6495 }
6496
6497 @Override
6498 public void preBindApplication(WindowProcessController wpc) {
6499 synchronized (mGlobalLock) {
6500 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6501 }
6502 }
6503
6504 @Override
6505 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6506 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006507 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006508 }
6509 }
6510
6511 @Override
6512 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6513 try {
6514 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6515 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6516 }
6517 } catch (RemoteException ex) {
6518 throw new SecurityException("Fail to check is caller a privileged app", ex);
6519 }
6520
6521 synchronized (mGlobalLock) {
6522 final long ident = Binder.clearCallingIdentity();
6523 try {
6524 if (mAmInternal.shouldConfirmCredentials(userId)) {
6525 if (mKeyguardController.isKeyguardLocked()) {
6526 // Showing launcher to avoid user entering credential twice.
6527 startHomeActivity(currentUserId, "notifyLockedProfile");
6528 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006529 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006530 }
6531 } finally {
6532 Binder.restoreCallingIdentity(ident);
6533 }
6534 }
6535 }
6536
6537 @Override
6538 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6539 mAmInternal.enforceCallingPermission(
6540 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6541
6542 synchronized (mGlobalLock) {
6543 final long ident = Binder.clearCallingIdentity();
6544 try {
6545 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6546 FLAG_ACTIVITY_TASK_ON_HOME);
6547 ActivityOptions activityOptions = options != null
6548 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006549 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006550 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006551 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006552 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006553 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006554 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6555 UserHandle.CURRENT);
6556 } finally {
6557 Binder.restoreCallingIdentity(ident);
6558 }
6559 }
6560 }
6561
6562 @Override
6563 public void writeActivitiesToProto(ProtoOutputStream proto) {
6564 synchronized (mGlobalLock) {
6565 // The output proto of "activity --proto activities"
6566 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006567 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006568 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6569 }
6570 }
6571
6572 @Override
6573 public void saveANRState(String reason) {
6574 synchronized (mGlobalLock) {
6575 final StringWriter sw = new StringWriter();
6576 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6577 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6578 if (reason != null) {
6579 pw.println(" Reason: " + reason);
6580 }
6581 pw.println();
6582 getActivityStartController().dump(pw, " ", null);
6583 pw.println();
6584 pw.println("-------------------------------------------------------------------------------");
6585 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6586 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6587 "" /* header */);
6588 pw.println();
6589 pw.close();
6590
6591 mLastANRState = sw.toString();
6592 }
6593 }
6594
6595 @Override
6596 public void clearSavedANRState() {
6597 synchronized (mGlobalLock) {
6598 mLastANRState = null;
6599 }
6600 }
6601
6602 @Override
6603 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6604 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6605 synchronized (mGlobalLock) {
6606 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6607 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6608 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6609 dumpLastANRLocked(pw);
6610 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6611 dumpLastANRTracesLocked(pw);
6612 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6613 dumpActivityStarterLocked(pw, dumpPackage);
6614 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6615 dumpActivityContainersLocked(pw);
6616 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6617 if (getRecentTasks() != null) {
6618 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6619 }
6620 }
6621 }
6622 }
6623
6624 @Override
6625 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6626 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6627 int wakefulness) {
6628 synchronized (mGlobalLock) {
6629 if (mHomeProcess != null && (dumpPackage == null
6630 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6631 if (needSep) {
6632 pw.println();
6633 needSep = false;
6634 }
6635 pw.println(" mHomeProcess: " + mHomeProcess);
6636 }
6637 if (mPreviousProcess != null && (dumpPackage == null
6638 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6639 if (needSep) {
6640 pw.println();
6641 needSep = false;
6642 }
6643 pw.println(" mPreviousProcess: " + mPreviousProcess);
6644 }
6645 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6646 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6647 StringBuilder sb = new StringBuilder(128);
6648 sb.append(" mPreviousProcessVisibleTime: ");
6649 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6650 pw.println(sb);
6651 }
6652 if (mHeavyWeightProcess != null && (dumpPackage == null
6653 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6654 if (needSep) {
6655 pw.println();
6656 needSep = false;
6657 }
6658 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6659 }
6660 if (dumpPackage == null) {
6661 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006662 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006663 }
6664 if (dumpAll) {
6665 if (dumpPackage == null) {
6666 pw.println(" mConfigWillChange: "
6667 + getTopDisplayFocusedStack().mConfigWillChange);
6668 }
6669 if (mCompatModePackages.getPackages().size() > 0) {
6670 boolean printed = false;
6671 for (Map.Entry<String, Integer> entry
6672 : mCompatModePackages.getPackages().entrySet()) {
6673 String pkg = entry.getKey();
6674 int mode = entry.getValue();
6675 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6676 continue;
6677 }
6678 if (!printed) {
6679 pw.println(" mScreenCompatPackages:");
6680 printed = true;
6681 }
6682 pw.println(" " + pkg + ": " + mode);
6683 }
6684 }
6685 }
6686
6687 if (dumpPackage == null) {
6688 pw.println(" mWakefulness="
6689 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006690 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006691 if (mRunningVoice != null) {
6692 pw.println(" mRunningVoice=" + mRunningVoice);
6693 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6694 }
6695 pw.println(" mSleeping=" + mSleeping);
6696 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6697 pw.println(" mVrController=" + mVrController);
6698 }
6699 if (mCurAppTimeTracker != null) {
6700 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6701 }
6702 if (mAllowAppSwitchUids.size() > 0) {
6703 boolean printed = false;
6704 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6705 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6706 for (int j = 0; j < types.size(); j++) {
6707 if (dumpPackage == null ||
6708 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6709 if (needSep) {
6710 pw.println();
6711 needSep = false;
6712 }
6713 if (!printed) {
6714 pw.println(" mAllowAppSwitchUids:");
6715 printed = true;
6716 }
6717 pw.print(" User ");
6718 pw.print(mAllowAppSwitchUids.keyAt(i));
6719 pw.print(": Type ");
6720 pw.print(types.keyAt(j));
6721 pw.print(" = ");
6722 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6723 pw.println();
6724 }
6725 }
6726 }
6727 }
6728 if (dumpPackage == null) {
6729 if (mController != null) {
6730 pw.println(" mController=" + mController
6731 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6732 }
6733 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6734 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6735 }
6736
6737 return needSep;
6738 }
6739 }
6740
6741 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006742 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6743 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006744 synchronized (mGlobalLock) {
6745 if (dumpPackage == null) {
6746 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6747 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006748 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6749 if (mRunningVoice != null) {
6750 final long vrToken = proto.start(
6751 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6752 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6753 mRunningVoice.toString());
6754 mVoiceWakeLock.writeToProto(
6755 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6756 proto.end(vrToken);
6757 }
6758 mVrController.writeToProto(proto,
6759 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006760 if (mController != null) {
6761 final long token = proto.start(CONTROLLER);
6762 proto.write(CONTROLLER, mController.toString());
6763 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6764 proto.end(token);
6765 }
6766 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6767 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6768 }
6769
6770 if (mHomeProcess != null && (dumpPackage == null
6771 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006772 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006773 }
6774
6775 if (mPreviousProcess != null && (dumpPackage == null
6776 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006777 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006778 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6779 }
6780
6781 if (mHeavyWeightProcess != null && (dumpPackage == null
6782 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006783 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006784 }
6785
6786 for (Map.Entry<String, Integer> entry
6787 : mCompatModePackages.getPackages().entrySet()) {
6788 String pkg = entry.getKey();
6789 int mode = entry.getValue();
6790 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6791 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6792 proto.write(PACKAGE, pkg);
6793 proto.write(MODE, mode);
6794 proto.end(compatToken);
6795 }
6796 }
6797
6798 if (mCurAppTimeTracker != null) {
6799 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6800 }
6801
6802 }
6803 }
6804
6805 @Override
6806 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6807 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6808 boolean dumpFocusedStackOnly) {
6809 synchronized (mGlobalLock) {
6810 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6811 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6812 }
6813 }
6814
6815 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006816 public void dumpForOom(PrintWriter pw) {
6817 synchronized (mGlobalLock) {
6818 pw.println(" mHomeProcess: " + mHomeProcess);
6819 pw.println(" mPreviousProcess: " + mPreviousProcess);
6820 if (mHeavyWeightProcess != null) {
6821 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6822 }
6823 }
6824 }
6825
6826 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 public boolean canGcNow() {
6828 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006829 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 }
6831 }
6832
6833 @Override
6834 public WindowProcessController getTopApp() {
6835 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006836 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006837 return top != null ? top.app : null;
6838 }
6839 }
6840
6841 @Override
6842 public void rankTaskLayersIfNeeded() {
6843 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006844 if (mRootActivityContainer != null) {
6845 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 }
6847 }
6848 }
6849
6850 @Override
6851 public void scheduleDestroyAllActivities(String reason) {
6852 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006853 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006854 }
6855 }
6856
6857 @Override
6858 public void removeUser(int userId) {
6859 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006860 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 }
6862 }
6863
6864 @Override
6865 public boolean switchUser(int userId, UserState userState) {
6866 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006867 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006868 }
6869 }
6870
6871 @Override
6872 public void onHandleAppCrash(WindowProcessController wpc) {
6873 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006874 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006875 }
6876 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006877
6878 @Override
6879 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6880 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006881 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006882 }
6883 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006884
6885 @Override
6886 public void onUidActive(int uid, int procState) {
6887 synchronized (mGlobalLock) {
6888 mActiveUids.put(uid, procState);
6889 }
6890 }
6891
6892 @Override
6893 public void onUidInactive(int uid) {
6894 synchronized (mGlobalLock) {
6895 mActiveUids.remove(uid);
6896 }
6897 }
6898
6899 @Override
6900 public void onActiveUidsCleared() {
6901 synchronized (mGlobalLock) {
6902 mActiveUids.clear();
6903 }
6904 }
6905
6906 @Override
6907 public void onUidProcStateChanged(int uid, int procState) {
6908 synchronized (mGlobalLock) {
6909 if (mActiveUids.get(uid) != null) {
6910 mActiveUids.put(uid, procState);
6911 }
6912 }
6913 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006914
6915 @Override
6916 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6917 synchronized (mGlobalLock) {
6918 mPendingTempWhitelist.put(uid, tag);
6919 }
6920 }
6921
6922 @Override
6923 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6924 synchronized (mGlobalLock) {
6925 mPendingTempWhitelist.remove(uid);
6926 }
6927 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006928
6929 @Override
6930 public boolean handleAppCrashInActivityController(String processName, int pid,
6931 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6932 Runnable killCrashingAppCallback) {
6933 synchronized (mGlobalLock) {
6934 if (mController == null) {
6935 return false;
6936 }
6937
6938 try {
6939 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6940 stackTrace)) {
6941 killCrashingAppCallback.run();
6942 return true;
6943 }
6944 } catch (RemoteException e) {
6945 mController = null;
6946 Watchdog.getInstance().setActivityController(null);
6947 }
6948 return false;
6949 }
6950 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006951
6952 @Override
6953 public void removeRecentTasksByPackageName(String packageName, int userId) {
6954 synchronized (mGlobalLock) {
6955 mRecentTasks.removeTasksByPackageName(packageName, userId);
6956 }
6957 }
6958
6959 @Override
6960 public void cleanupRecentTasksForUser(int userId) {
6961 synchronized (mGlobalLock) {
6962 mRecentTasks.cleanupLocked(userId);
6963 }
6964 }
6965
6966 @Override
6967 public void loadRecentTasksForUser(int userId) {
6968 synchronized (mGlobalLock) {
6969 mRecentTasks.loadUserRecentsLocked(userId);
6970 }
6971 }
6972
6973 @Override
6974 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6975 synchronized (mGlobalLock) {
6976 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6977 }
6978 }
6979
6980 @Override
6981 public void flushRecentTasks() {
6982 mRecentTasks.flush();
6983 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006984
6985 @Override
6986 public WindowProcessController getHomeProcess() {
6987 synchronized (mGlobalLock) {
6988 return mHomeProcess;
6989 }
6990 }
6991
6992 @Override
6993 public WindowProcessController getPreviousProcess() {
6994 synchronized (mGlobalLock) {
6995 return mPreviousProcess;
6996 }
6997 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006998
6999 @Override
7000 public void clearLockedTasks(String reason) {
7001 synchronized (mGlobalLock) {
7002 getLockTaskController().clearLockedTasks(reason);
7003 }
7004 }
7005
7006 @Override
7007 public void updateUserConfiguration() {
7008 synchronized (mGlobalLock) {
7009 final Configuration configuration = new Configuration(getGlobalConfiguration());
7010 final int currentUserId = mAmInternal.getCurrentUserId();
7011 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7012 configuration, currentUserId, Settings.System.canWrite(mContext));
7013 updateConfigurationLocked(configuration, null /* starting */,
7014 false /* initLocale */, false /* persistent */, currentUserId,
7015 false /* deferResume */);
7016 }
7017 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007018
7019 @Override
7020 public boolean canShowErrorDialogs() {
7021 synchronized (mGlobalLock) {
7022 return mShowDialogs && !mSleeping && !mShuttingDown
7023 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7024 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7025 mAmInternal.getCurrentUserId())
7026 && !(UserManager.isDeviceInDemoMode(mContext)
7027 && mAmInternal.getCurrentUser().isDemo());
7028 }
7029 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007030
7031 @Override
7032 public void setProfileApp(String profileApp) {
7033 synchronized (mGlobalLock) {
7034 mProfileApp = profileApp;
7035 }
7036 }
7037
7038 @Override
7039 public void setProfileProc(WindowProcessController wpc) {
7040 synchronized (mGlobalLock) {
7041 mProfileProc = wpc;
7042 }
7043 }
7044
7045 @Override
7046 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7047 synchronized (mGlobalLock) {
7048 mProfilerInfo = profilerInfo;
7049 }
7050 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007051
7052 @Override
7053 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7054 synchronized (mGlobalLock) {
7055 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7056 }
7057 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007058
7059 @Override
7060 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7061 synchronized (mGlobalLock) {
7062 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7063 }
7064 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007065 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007066}