blob: a0c71d4fb1a801e84e12bf1ec00e83a312fbc8dc [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();
Riddle Hsud7088f82019-01-30 13:04:50 +0800352 /**
353 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
354 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
355 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
356 *
357 * @see WindowManagerThreadPriorityBooster
358 */
359 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700360 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800361 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700362 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700363 private UserManagerService mUserManager;
364 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700365 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700366 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
367 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700368 /** All processes currently running that might have a window organized by name. */
369 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700370 /** All processes we currently have running mapped by pid */
371 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700372 /** This is the process holding what we currently consider to be the "home" activity. */
373 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700374 /** The currently running heavy-weight process, if any. */
375 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700376 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /**
378 * This is the process holding the activity the user last visited that is in a different process
379 * from the one they are currently in.
380 */
381 WindowProcessController mPreviousProcess;
382 /** The time at which the previous process was last visible. */
383 long mPreviousProcessVisibleTime;
384
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700385 /** List of intents that were used to start the most recent tasks. */
386 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700387 /** State of external calls telling us if the device is awake or asleep. */
388 private boolean mKeyguardShown = false;
389
390 // Wrapper around VoiceInteractionServiceManager
391 private AssistUtils mAssistUtils;
392
393 // VoiceInteraction session ID that changes for each new request except when
394 // being called for multi-window assist in a single session.
395 private int mViSessionId = 1000;
396
397 // How long to wait in getAssistContextExtras for the activity and foreground services
398 // to respond with the result.
399 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
400
401 // How long top wait when going through the modern assist (which doesn't need to block
402 // on getting this result before starting to launch its UI).
403 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
404
405 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
406 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
407
Alison Cichowlas3e340502018-08-07 17:15:01 -0400408 // Permission tokens are used to temporarily granted a trusted app the ability to call
409 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
410 // showing any appropriate error messages to the user.
411 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
412 10 * MINUTE_IN_MILLIS;
413
414 // How long before the service actually expires a token. This is slightly longer than
415 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
416 // expiration exception.
417 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
418 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
419
420 // How long the service will remember expired tokens, for the purpose of providing error
421 // messaging when a client uses an expired token.
422 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
423 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
424
425 // Activity tokens of system activities that are delegating their call to
426 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
427 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
428
429 // Permission tokens that have expired, but we remember for error reporting.
430 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
431
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700432 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
433
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700434 // Keeps track of the active voice interaction service component, notified from
435 // VoiceInteractionManagerService
436 ComponentName mActiveVoiceInteractionServiceComponent;
437
Wale Ogunwalee2172292018-10-25 10:11:10 -0700438 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700439 KeyguardController mKeyguardController;
440 private final ClientLifecycleManager mLifecycleManager;
441 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700442 /** The controller for all operations related to locktask. */
443 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700444 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700446 boolean mSuppressResizeConfigChanges;
447
448 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
449 new UpdateConfigurationResult();
450
451 static final class UpdateConfigurationResult {
452 // Configuration changes that were updated.
453 int changes;
454 // If the activity was relaunched to match the new configuration.
455 boolean activityRelaunched;
456
457 void reset() {
458 changes = 0;
459 activityRelaunched = false;
460 }
461 }
462
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700463 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700464 private int mConfigurationSeq;
465 // To cache the list of supported system locales
466 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700467
468 /**
469 * Temp object used when global and/or display override configuration is updated. It is also
470 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
471 * anyone...
472 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700473 private Configuration mTempConfig = new Configuration();
474
Wale Ogunwalef6733932018-06-27 05:14:34 -0700475 /** Temporary to avoid allocations. */
476 final StringBuilder mStringBuilder = new StringBuilder(256);
477
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 // Amount of time after a call to stopAppSwitches() during which we will
479 // prevent further untrusted switches from happening.
480 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
481
482 /**
483 * The time at which we will allow normal application switches again,
484 * after a call to {@link #stopAppSwitches()}.
485 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700486 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 /**
488 * This is set to true after the first switch after mAppSwitchesAllowedTime
489 * is set; any switches after that will clear the time.
490 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492
493 IActivityController mController = null;
494 boolean mControllerIsAMonkey = false;
495
Wale Ogunwale214f3482018-10-04 11:00:47 -0700496 final int mFactoryTest;
497
498 /** Used to control how we initialize the service. */
499 ComponentName mTopComponent;
500 String mTopAction = Intent.ACTION_MAIN;
501 String mTopData;
502
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800503 /** Profiling app information. */
504 String mProfileApp = null;
505 WindowProcessController mProfileProc = null;
506 ProfilerInfo mProfilerInfo = null;
507
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700509 * Dump of the activity state at the time of the last ANR. Cleared after
510 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
511 */
512 String mLastANRState;
513
514 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515 * Used to retain an update lock when the foreground activity is in
516 * immersive mode.
517 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700518 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519
520 /**
521 * Packages that are being allowed to perform unrestricted app switches. Mapping is
522 * User -> Type -> uid.
523 */
524 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
525
526 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700527 private int mThumbnailWidth;
528 private int mThumbnailHeight;
529 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530
531 /**
532 * Flag that indicates if multi-window is enabled.
533 *
534 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
535 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
536 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
537 * At least one of the forms of multi-window must be enabled in order for this flag to be
538 * initialized to 'true'.
539 *
540 * @see #mSupportsSplitScreenMultiWindow
541 * @see #mSupportsFreeformWindowManagement
542 * @see #mSupportsPictureInPicture
543 * @see #mSupportsMultiDisplay
544 */
545 boolean mSupportsMultiWindow;
546 boolean mSupportsSplitScreenMultiWindow;
547 boolean mSupportsFreeformWindowManagement;
548 boolean mSupportsPictureInPicture;
549 boolean mSupportsMultiDisplay;
550 boolean mForceResizableActivities;
551
552 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
553
554 // VR Vr2d Display Id.
555 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700556
Wale Ogunwalef6733932018-06-27 05:14:34 -0700557 /**
558 * Set while we are wanting to sleep, to prevent any
559 * activities from being started/resumed.
560 *
561 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
562 *
563 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
564 * while in the sleep state until there is a pending transition out of sleep, in which case
565 * mSleeping is set to false, and remains false while awake.
566 *
567 * Whether mSleeping can quickly toggled between true/false without the device actually
568 * display changing states is undefined.
569 */
570 private boolean mSleeping = false;
571
572 /**
573 * The process state used for processes that are running the top activities.
574 * This changes between TOP and TOP_SLEEPING to following mSleeping.
575 */
576 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
577
578 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
579 // automatically. Important for devices without direct input devices.
580 private boolean mShowDialogs = true;
581
582 /** Set if we are shutting down the system, similar to sleeping. */
583 boolean mShuttingDown = false;
584
585 /**
586 * We want to hold a wake lock while running a voice interaction session, since
587 * this may happen with the screen off and we need to keep the CPU running to
588 * be able to continue to interact with the user.
589 */
590 PowerManager.WakeLock mVoiceWakeLock;
591
592 /**
593 * Set while we are running a voice interaction. This overrides sleeping while it is active.
594 */
595 IVoiceInteractionSession mRunningVoice;
596
597 /**
598 * The last resumed activity. This is identical to the current resumed activity most
599 * of the time but could be different when we're pausing one activity before we resume
600 * another activity.
601 */
602 ActivityRecord mLastResumedActivity;
603
604 /**
605 * The activity that is currently being traced as the active resumed activity.
606 *
607 * @see #updateResumedAppTrace
608 */
609 private @Nullable ActivityRecord mTracedResumedActivity;
610
611 /** If non-null, we are tracking the time the user spends in the currently focused app. */
612 AppTimeTracker mCurAppTimeTracker;
613
Wale Ogunwale008163e2018-07-23 23:11:08 -0700614 private AppWarnings mAppWarnings;
615
Wale Ogunwale53783742018-09-16 10:21:51 -0700616 /**
617 * Packages that the user has asked to have run in screen size
618 * compatibility mode instead of filling the screen.
619 */
620 CompatModePackages mCompatModePackages;
621
Wale Ogunwalef6733932018-06-27 05:14:34 -0700622 private FontScaleSettingObserver mFontScaleSettingObserver;
623
Michal Karpinski4026cae2019-02-12 11:51:47 +0000624 private String mDeviceOwnerPackageName;
625
Wale Ogunwalef6733932018-06-27 05:14:34 -0700626 private final class FontScaleSettingObserver extends ContentObserver {
627 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
628 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
629
630 public FontScaleSettingObserver() {
631 super(mH);
632 final ContentResolver resolver = mContext.getContentResolver();
633 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
634 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
635 UserHandle.USER_ALL);
636 }
637
638 @Override
639 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
640 if (mFontScaleUri.equals(uri)) {
641 updateFontScaleIfNeeded(userId);
642 } else if (mHideErrorDialogsUri.equals(uri)) {
643 synchronized (mGlobalLock) {
644 updateShouldShowDialogsLocked(getGlobalConfiguration());
645 }
646 }
647 }
648 }
649
Charles Chen8d98dd22018-12-26 17:36:54 +0800650 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
651 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700652 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700653 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700654 mSystemThread = ActivityThread.currentActivityThread();
655 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700656 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800657 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700658 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700659 }
660
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700661 public void onSystemReady() {
662 synchronized (mGlobalLock) {
663 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
664 PackageManager.FEATURE_CANT_SAVE_STATE);
665 mAssistUtils = new AssistUtils(mContext);
666 mVrController.onSystemReady();
667 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700668 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700669 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void onInitPowerManagement() {
673 synchronized (mGlobalLock) {
674 mStackSupervisor.initPowerManagement();
675 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
676 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
677 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
678 mVoiceWakeLock.setReferenceCounted(false);
679 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700680 }
681
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700682 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700683 mFontScaleSettingObserver = new FontScaleSettingObserver();
684 }
685
Wale Ogunwale59507092018-10-29 09:00:30 -0700686 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700687 final boolean freeformWindowManagement =
688 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
689 || Settings.Global.getInt(
690 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
691
692 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
693 final boolean supportsPictureInPicture = supportsMultiWindow &&
694 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
695 final boolean supportsSplitScreenMultiWindow =
696 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
697 final boolean supportsMultiDisplay = mContext.getPackageManager()
698 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700699 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
700 final boolean forceResizable = Settings.Global.getInt(
701 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700702 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700703
704 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900705 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700706
707 final Configuration configuration = new Configuration();
708 Settings.System.getConfiguration(resolver, configuration);
709 if (forceRtl) {
710 // This will take care of setting the correct layout direction flags
711 configuration.setLayoutDirection(configuration.locale);
712 }
713
714 synchronized (mGlobalLock) {
715 mForceResizableActivities = forceResizable;
716 final boolean multiWindowFormEnabled = freeformWindowManagement
717 || supportsSplitScreenMultiWindow
718 || supportsPictureInPicture
719 || supportsMultiDisplay;
720 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
721 mSupportsMultiWindow = true;
722 mSupportsFreeformWindowManagement = freeformWindowManagement;
723 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
724 mSupportsPictureInPicture = supportsPictureInPicture;
725 mSupportsMultiDisplay = supportsMultiDisplay;
726 } else {
727 mSupportsMultiWindow = false;
728 mSupportsFreeformWindowManagement = false;
729 mSupportsSplitScreenMultiWindow = false;
730 mSupportsPictureInPicture = false;
731 mSupportsMultiDisplay = false;
732 }
733 mWindowManager.setForceResizableTasks(mForceResizableActivities);
734 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700735 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
736 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737 // This happens before any activities are started, so we can change global configuration
738 // in-place.
739 updateConfigurationLocked(configuration, null, true);
740 final Configuration globalConfig = getGlobalConfiguration();
741 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
742
743 // Load resources only after the current configuration has been set.
744 final Resources res = mContext.getResources();
745 mThumbnailWidth = res.getDimensionPixelSize(
746 com.android.internal.R.dimen.thumbnail_width);
747 mThumbnailHeight = res.getDimensionPixelSize(
748 com.android.internal.R.dimen.thumbnail_height);
749
750 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
751 mFullscreenThumbnailScale = (float) res
752 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
753 (float) globalConfig.screenWidthDp;
754 } else {
755 mFullscreenThumbnailScale = res.getFraction(
756 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
757 }
758 }
759 }
760
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800761 public WindowManagerGlobalLock getGlobalLock() {
762 return mGlobalLock;
763 }
764
Riddle Hsud93a6c42018-11-29 21:50:06 +0800765 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
766 Looper looper) {
767 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700769 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700770 final File systemDir = SystemServiceManager.ensureSystemDir();
771 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
772 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700773 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774
775 mTempConfig.setToDefaults();
776 mTempConfig.setLocales(LocaleList.getDefault());
777 mConfigurationSeq = mTempConfig.seq = 1;
778 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800779 mRootActivityContainer = new RootActivityContainer(this);
780 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700781
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700782 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700784 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700785 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700786 mRecentTasks = createRecentTasks();
787 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700788 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700789 mKeyguardController = mStackSupervisor.getKeyguardController();
790 }
791
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700792 public void onActivityManagerInternalAdded() {
793 synchronized (mGlobalLock) {
794 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
795 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
796 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700797 }
798
Yunfan Chen75157d72018-07-27 14:47:21 +0900799 int increaseConfigurationSeqLocked() {
800 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
801 return mConfigurationSeq;
802 }
803
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700804 protected ActivityStackSupervisor createStackSupervisor() {
805 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
806 supervisor.initialize();
807 return supervisor;
808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setWindowManager(WindowManagerService wm) {
811 synchronized (mGlobalLock) {
812 mWindowManager = wm;
813 mLockTaskController.setWindowManager(wm);
814 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800815 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700816 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700817 }
818
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700819 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
820 synchronized (mGlobalLock) {
821 mUsageStatsInternal = usageStatsManager;
822 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 }
824
Wale Ogunwalef6733932018-06-27 05:14:34 -0700825 UserManagerService getUserManager() {
826 if (mUserManager == null) {
827 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
828 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
829 }
830 return mUserManager;
831 }
832
833 AppOpsService getAppOpsService() {
834 if (mAppOpsService == null) {
835 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
836 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
837 }
838 return mAppOpsService;
839 }
840
841 boolean hasUserRestriction(String restriction, int userId) {
842 return getUserManager().hasUserRestriction(restriction, userId);
843 }
844
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700845 protected RecentTasks createRecentTasks() {
846 return new RecentTasks(this, mStackSupervisor);
847 }
848
849 RecentTasks getRecentTasks() {
850 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700851 }
852
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700853 ClientLifecycleManager getLifecycleManager() {
854 return mLifecycleManager;
855 }
856
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700857 ActivityStartController getActivityStartController() {
858 return mActivityStartController;
859 }
860
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700861 TaskChangeNotificationController getTaskChangeNotificationController() {
862 return mTaskChangeNotificationController;
863 }
864
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700865 LockTaskController getLockTaskController() {
866 return mLockTaskController;
867 }
868
Yunfan Chen75157d72018-07-27 14:47:21 +0900869 /**
870 * Return the global configuration used by the process corresponding to the input pid. This is
871 * usually the global configuration with some overrides specific to that process.
872 */
873 Configuration getGlobalConfigurationForCallingPid() {
874 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800875 return getGlobalConfigurationForPid(pid);
876 }
877
878 /**
879 * Return the global configuration used by the process corresponding to the given pid.
880 */
881 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900882 if (pid == MY_PID || pid < 0) {
883 return getGlobalConfiguration();
884 }
885 synchronized (mGlobalLock) {
886 final WindowProcessController app = mPidMap.get(pid);
887 return app != null ? app.getConfiguration() : getGlobalConfiguration();
888 }
889 }
890
891 /**
892 * Return the device configuration info used by the process corresponding to the input pid.
893 * The value is consistent with the global configuration for the process.
894 */
895 @Override
896 public ConfigurationInfo getDeviceConfigurationInfo() {
897 ConfigurationInfo config = new ConfigurationInfo();
898 synchronized (mGlobalLock) {
899 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
900 config.reqTouchScreen = globalConfig.touchscreen;
901 config.reqKeyboardType = globalConfig.keyboard;
902 config.reqNavigation = globalConfig.navigation;
903 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
904 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
905 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
906 }
907 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
908 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
909 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
910 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700911 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 }
913 return config;
914 }
915
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700916 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700917 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700918 }
919
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700920 public static final class Lifecycle extends SystemService {
921 private final ActivityTaskManagerService mService;
922
923 public Lifecycle(Context context) {
924 super(context);
925 mService = new ActivityTaskManagerService(context);
926 }
927
928 @Override
929 public void onStart() {
930 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700931 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700932 }
933
Garfield Tan891146c2018-10-09 12:14:00 -0700934 @Override
935 public void onUnlockUser(int userId) {
936 synchronized (mService.getGlobalLock()) {
937 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
938 }
939 }
940
941 @Override
942 public void onCleanupUser(int userId) {
943 synchronized (mService.getGlobalLock()) {
944 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
945 }
946 }
947
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700948 public ActivityTaskManagerService getService() {
949 return mService;
950 }
951 }
952
953 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700954 public final int startActivity(IApplicationThread caller, String callingPackage,
955 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
956 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
957 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
958 resultWho, requestCode, startFlags, profilerInfo, bOptions,
959 UserHandle.getCallingUserId());
960 }
961
962 @Override
963 public final int startActivities(IApplicationThread caller, String callingPackage,
964 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
965 int userId) {
966 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700967 enforceNotIsolatedCaller(reason);
968 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700969 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000970 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
971 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
972 reason, null /* originatingPendingIntent */,
973 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700974 }
975
976 @Override
977 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
978 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
979 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
980 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
981 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
982 true /*validateIncomingUser*/);
983 }
984
985 int startActivityAsUser(IApplicationThread caller, String callingPackage,
986 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
987 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
988 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700989 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700990
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700991 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700992 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
993
994 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700995 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996 .setCaller(caller)
997 .setCallingPackage(callingPackage)
998 .setResolvedType(resolvedType)
999 .setResultTo(resultTo)
1000 .setResultWho(resultWho)
1001 .setRequestCode(requestCode)
1002 .setStartFlags(startFlags)
1003 .setProfilerInfo(profilerInfo)
1004 .setActivityOptions(bOptions)
1005 .setMayWait(userId)
1006 .execute();
1007
1008 }
1009
1010 @Override
1011 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1012 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001013 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1014 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 // Refuse possible leaked file descriptors
1016 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1017 throw new IllegalArgumentException("File descriptors passed in Intent");
1018 }
1019
1020 if (!(target instanceof PendingIntentRecord)) {
1021 throw new IllegalArgumentException("Bad PendingIntent object");
1022 }
1023
1024 PendingIntentRecord pir = (PendingIntentRecord)target;
1025
1026 synchronized (mGlobalLock) {
1027 // If this is coming from the currently resumed activity, it is
1028 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001029 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 if (stack.mResumedActivity != null &&
1031 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 }
1034 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 }
1038
1039 @Override
1040 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1041 Bundle bOptions) {
1042 // Refuse possible leaked file descriptors
1043 if (intent != null && intent.hasFileDescriptors()) {
1044 throw new IllegalArgumentException("File descriptors passed in Intent");
1045 }
1046 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1047
1048 synchronized (mGlobalLock) {
1049 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1050 if (r == null) {
1051 SafeActivityOptions.abort(options);
1052 return false;
1053 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001054 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 // The caller is not running... d'oh!
1056 SafeActivityOptions.abort(options);
1057 return false;
1058 }
1059 intent = new Intent(intent);
1060 // The caller is not allowed to change the data.
1061 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1062 // And we are resetting to find the next component...
1063 intent.setComponent(null);
1064
1065 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1066
1067 ActivityInfo aInfo = null;
1068 try {
1069 List<ResolveInfo> resolves =
1070 AppGlobals.getPackageManager().queryIntentActivities(
1071 intent, r.resolvedType,
1072 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1073 UserHandle.getCallingUserId()).getList();
1074
1075 // Look for the original activity in the list...
1076 final int N = resolves != null ? resolves.size() : 0;
1077 for (int i=0; i<N; i++) {
1078 ResolveInfo rInfo = resolves.get(i);
1079 if (rInfo.activityInfo.packageName.equals(r.packageName)
1080 && rInfo.activityInfo.name.equals(r.info.name)) {
1081 // We found the current one... the next matching is
1082 // after it.
1083 i++;
1084 if (i<N) {
1085 aInfo = resolves.get(i).activityInfo;
1086 }
1087 if (debug) {
1088 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1089 + "/" + r.info.name);
1090 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1091 ? "null" : aInfo.packageName + "/" + aInfo.name));
1092 }
1093 break;
1094 }
1095 }
1096 } catch (RemoteException e) {
1097 }
1098
1099 if (aInfo == null) {
1100 // Nobody who is next!
1101 SafeActivityOptions.abort(options);
1102 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1103 return false;
1104 }
1105
1106 intent.setComponent(new ComponentName(
1107 aInfo.applicationInfo.packageName, aInfo.name));
1108 intent.setFlags(intent.getFlags()&~(
1109 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1110 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1111 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1112 FLAG_ACTIVITY_NEW_TASK));
1113
1114 // Okay now we need to start the new activity, replacing the currently running activity.
1115 // This is a little tricky because we want to start the new one as if the current one is
1116 // finished, but not finish the current one first so that there is no flicker.
1117 // And thus...
1118 final boolean wasFinishing = r.finishing;
1119 r.finishing = true;
1120
1121 // Propagate reply information over to the new activity.
1122 final ActivityRecord resultTo = r.resultTo;
1123 final String resultWho = r.resultWho;
1124 final int requestCode = r.requestCode;
1125 r.resultTo = null;
1126 if (resultTo != null) {
1127 resultTo.removeResultsLocked(r, resultWho, requestCode);
1128 }
1129
1130 final long origId = Binder.clearCallingIdentity();
1131 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001132 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001133 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001134 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001135 .setResolvedType(r.resolvedType)
1136 .setActivityInfo(aInfo)
1137 .setResultTo(resultTo != null ? resultTo.appToken : null)
1138 .setResultWho(resultWho)
1139 .setRequestCode(requestCode)
1140 .setCallingPid(-1)
1141 .setCallingUid(r.launchedFromUid)
1142 .setCallingPackage(r.launchedFromPackage)
1143 .setRealCallingPid(-1)
1144 .setRealCallingUid(r.launchedFromUid)
1145 .setActivityOptions(options)
1146 .execute();
1147 Binder.restoreCallingIdentity(origId);
1148
1149 r.finishing = wasFinishing;
1150 if (res != ActivityManager.START_SUCCESS) {
1151 return false;
1152 }
1153 return true;
1154 }
1155 }
1156
1157 @Override
1158 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1159 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1160 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1161 final WaitResult res = new WaitResult();
1162 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001163 enforceNotIsolatedCaller("startActivityAndWait");
1164 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1165 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001166 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001167 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001168 .setCaller(caller)
1169 .setCallingPackage(callingPackage)
1170 .setResolvedType(resolvedType)
1171 .setResultTo(resultTo)
1172 .setResultWho(resultWho)
1173 .setRequestCode(requestCode)
1174 .setStartFlags(startFlags)
1175 .setActivityOptions(bOptions)
1176 .setMayWait(userId)
1177 .setProfilerInfo(profilerInfo)
1178 .setWaitResult(res)
1179 .execute();
1180 }
1181 return res;
1182 }
1183
1184 @Override
1185 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1186 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1187 int startFlags, Configuration config, Bundle bOptions, int userId) {
1188 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001189 enforceNotIsolatedCaller("startActivityWithConfig");
1190 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1191 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001192 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001193 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .setCaller(caller)
1195 .setCallingPackage(callingPackage)
1196 .setResolvedType(resolvedType)
1197 .setResultTo(resultTo)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setStartFlags(startFlags)
1201 .setGlobalConfiguration(config)
1202 .setActivityOptions(bOptions)
1203 .setMayWait(userId)
1204 .execute();
1205 }
1206 }
1207
Alison Cichowlas3e340502018-08-07 17:15:01 -04001208
1209 @Override
1210 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1211 int callingUid = Binder.getCallingUid();
1212 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1213 throw new SecurityException("Only the system process can request a permission token, "
1214 + "received request from uid: " + callingUid);
1215 }
1216 IBinder permissionToken = new Binder();
1217 synchronized (mGlobalLock) {
1218 mStartActivitySources.put(permissionToken, delegatorToken);
1219 }
1220
1221 Message expireMsg = PooledLambda.obtainMessage(
1222 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1223 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1224
1225 Message forgetMsg = PooledLambda.obtainMessage(
1226 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1227 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1228
1229 return permissionToken;
1230 }
1231
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001232 @Override
1233 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001235 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1236 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001238 // permission grants) as any app that may launch one of your own activities. So we only
1239 // allow this in two cases:
1240 // 1) The caller is an activity that is part of the core framework, and then only when it
1241 // is running as the system.
1242 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1243 // can only be requested by a system activity, which may then delegate this call to
1244 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001245 final ActivityRecord sourceRecord;
1246 final int targetUid;
1247 final String targetPackage;
1248 final boolean isResolver;
1249 synchronized (mGlobalLock) {
1250 if (resultTo == null) {
1251 throw new SecurityException("Must be called from an activity");
1252 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001253 final IBinder sourceToken;
1254 if (permissionToken != null) {
1255 // To even attempt to use a permissionToken, an app must also have this signature
1256 // permission.
1257 mAmInternal.enforceCallingPermission(
1258 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1259 "startActivityAsCaller");
1260 // If called with a permissionToken, we want the sourceRecord from the delegator
1261 // activity that requested this token.
1262 sourceToken = mStartActivitySources.remove(permissionToken);
1263 if (sourceToken == null) {
1264 // Invalid permissionToken, check if it recently expired.
1265 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1266 throw new SecurityException("Called with expired permission token: "
1267 + permissionToken);
1268 } else {
1269 throw new SecurityException("Called with invalid permission token: "
1270 + permissionToken);
1271 }
1272 }
1273 } else {
1274 // This method was called directly by the source.
1275 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277
Wale Ogunwaled32da472018-11-16 07:19:28 -08001278 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 if (sourceRecord == null) {
1280 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281 }
1282 if (sourceRecord.app == null) {
1283 throw new SecurityException("Called without a process attached to activity");
1284 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285
1286 // Whether called directly or from a delegate, the source activity must be from the
1287 // android package.
1288 if (!sourceRecord.info.packageName.equals("android")) {
1289 throw new SecurityException("Must be called from an activity that is "
1290 + "declared in the android package");
1291 }
1292
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001293 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001294 // This is still okay, as long as this activity is running under the
1295 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001296 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001298 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 + " must be system uid or original calling uid "
1300 + sourceRecord.launchedFromUid);
1301 }
1302 }
1303 if (ignoreTargetSecurity) {
1304 if (intent.getComponent() == null) {
1305 throw new SecurityException(
1306 "Component must be specified with ignoreTargetSecurity");
1307 }
1308 if (intent.getSelector() != null) {
1309 throw new SecurityException(
1310 "Selector not allowed with ignoreTargetSecurity");
1311 }
1312 }
1313 targetUid = sourceRecord.launchedFromUid;
1314 targetPackage = sourceRecord.launchedFromPackage;
1315 isResolver = sourceRecord.isResolverOrChildActivity();
1316 }
1317
1318 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001319 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 }
1321
1322 // TODO: Switch to user app stacks here.
1323 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001324 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 .setCallingUid(targetUid)
1326 .setCallingPackage(targetPackage)
1327 .setResolvedType(resolvedType)
1328 .setResultTo(resultTo)
1329 .setResultWho(resultWho)
1330 .setRequestCode(requestCode)
1331 .setStartFlags(startFlags)
1332 .setActivityOptions(bOptions)
1333 .setMayWait(userId)
1334 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1335 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1336 .execute();
1337 } catch (SecurityException e) {
1338 // XXX need to figure out how to propagate to original app.
1339 // A SecurityException here is generally actually a fault of the original
1340 // calling activity (such as a fairly granting permissions), so propagate it
1341 // back to them.
1342 /*
1343 StringBuilder msg = new StringBuilder();
1344 msg.append("While launching");
1345 msg.append(intent.toString());
1346 msg.append(": ");
1347 msg.append(e.getMessage());
1348 */
1349 throw e;
1350 }
1351 }
1352
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1354 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1355 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1356 }
1357
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 @Override
1359 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1360 Intent intent, String resolvedType, IVoiceInteractionSession session,
1361 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1362 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001363 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 if (session == null || interactor == null) {
1365 throw new NullPointerException("null session or interactor");
1366 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001367 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001369 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 .setCallingUid(callingUid)
1371 .setCallingPackage(callingPackage)
1372 .setResolvedType(resolvedType)
1373 .setVoiceSession(session)
1374 .setVoiceInteractor(interactor)
1375 .setStartFlags(startFlags)
1376 .setProfilerInfo(profilerInfo)
1377 .setActivityOptions(bOptions)
1378 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001379 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 .execute();
1381 }
1382
1383 @Override
1384 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1385 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001386 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1387 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001388
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001389 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 .setCallingUid(callingUid)
1391 .setCallingPackage(callingPackage)
1392 .setResolvedType(resolvedType)
1393 .setActivityOptions(bOptions)
1394 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001395 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .execute();
1397 }
1398
1399 @Override
1400 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1401 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001402 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 final int callingPid = Binder.getCallingPid();
1404 final long origId = Binder.clearCallingIdentity();
1405 try {
1406 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001407 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1408 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409
1410 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1412 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1414 recentsUid, assistDataReceiver);
1415 }
1416 } finally {
1417 Binder.restoreCallingIdentity(origId);
1418 }
1419 }
1420
1421 @Override
1422 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001423 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 "startActivityFromRecents()");
1425
1426 final int callingPid = Binder.getCallingPid();
1427 final int callingUid = Binder.getCallingUid();
1428 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1429 final long origId = Binder.clearCallingIdentity();
1430 try {
1431 synchronized (mGlobalLock) {
1432 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1433 safeOptions);
1434 }
1435 } finally {
1436 Binder.restoreCallingIdentity(origId);
1437 }
1438 }
1439
1440 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001441 * Public API to check if the client is allowed to start an activity on specified display.
1442 *
1443 * If the target display is private or virtual, some restrictions will apply.
1444 *
1445 * @param displayId Target display id.
1446 * @param intent Intent used to launch the activity.
1447 * @param resolvedType The MIME type of the intent.
1448 * @param userId The id of the user for whom the call is made.
1449 * @return {@code true} if a call to start an activity on the target display should succeed and
1450 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1451 */
1452 @Override
1453 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1454 String resolvedType, int userId) {
1455 final int callingUid = Binder.getCallingUid();
1456 final int callingPid = Binder.getCallingPid();
1457 final long origId = Binder.clearCallingIdentity();
1458
1459 try {
1460 // Collect information about the target of the Intent.
1461 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1462 0 /* startFlags */, null /* profilerInfo */, userId,
1463 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1464 UserHandle.USER_NULL));
1465 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1466
1467 synchronized (mGlobalLock) {
1468 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1469 aInfo);
1470 }
1471 } finally {
1472 Binder.restoreCallingIdentity(origId);
1473 }
1474 }
1475
1476 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 * This is the internal entry point for handling Activity.finish().
1478 *
1479 * @param token The Binder token referencing the Activity we want to finish.
1480 * @param resultCode Result code, if any, from this Activity.
1481 * @param resultData Result data (Intent), if any, from this Activity.
1482 * @param finishTask Whether to finish the task associated with this Activity.
1483 *
1484 * @return Returns true if the activity successfully finished, or false if it is still running.
1485 */
1486 @Override
1487 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1488 int finishTask) {
1489 // Refuse possible leaked file descriptors
1490 if (resultData != null && resultData.hasFileDescriptors()) {
1491 throw new IllegalArgumentException("File descriptors passed in Intent");
1492 }
1493
1494 synchronized (mGlobalLock) {
1495 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1496 if (r == null) {
1497 return true;
1498 }
1499 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001500 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001501 ActivityRecord rootR = tr.getRootActivity();
1502 if (rootR == null) {
1503 Slog.w(TAG, "Finishing task with all activities already finished");
1504 }
1505 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1506 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001507 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 return false;
1509 }
1510
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001511 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1512 // We should consolidate.
1513 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001514 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001515 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 if (next != null) {
1517 // ask watcher if this is allowed
1518 boolean resumeOK = true;
1519 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001520 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001522 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 Watchdog.getInstance().setActivityController(null);
1524 }
1525
1526 if (!resumeOK) {
1527 Slog.i(TAG, "Not finishing activity because controller resumed");
1528 return false;
1529 }
1530 }
1531 }
1532 final long origId = Binder.clearCallingIdentity();
1533 try {
1534 boolean res;
1535 final boolean finishWithRootActivity =
1536 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1537 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1538 || (finishWithRootActivity && r == rootR)) {
1539 // If requested, remove the task that is associated to this activity only if it
1540 // was the root activity in the task. The result code and data is ignored
1541 // because we don't support returning them across task boundaries. Also, to
1542 // keep backwards compatibility we remove the task from recents when finishing
1543 // task with root activity.
1544 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1545 finishWithRootActivity, "finish-activity");
1546 if (!res) {
1547 Slog.i(TAG, "Removing task failed to finish activity");
1548 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001549 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001550 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 } else {
1552 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1553 resultData, "app-request", true);
1554 if (!res) {
1555 Slog.i(TAG, "Failed to finish by app-request");
1556 }
1557 }
1558 return res;
1559 } finally {
1560 Binder.restoreCallingIdentity(origId);
1561 }
1562 }
1563 }
1564
1565 @Override
1566 public boolean finishActivityAffinity(IBinder token) {
1567 synchronized (mGlobalLock) {
1568 final long origId = Binder.clearCallingIdentity();
1569 try {
1570 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1571 if (r == null) {
1572 return false;
1573 }
1574
1575 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1576 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001577 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001578 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 return false;
1580 }
1581 return task.getStack().finishActivityAffinityLocked(r);
1582 } finally {
1583 Binder.restoreCallingIdentity(origId);
1584 }
1585 }
1586 }
1587
1588 @Override
1589 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1590 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001591 try {
1592 WindowProcessController proc = null;
1593 synchronized (mGlobalLock) {
1594 ActivityStack stack = ActivityRecord.getStackLocked(token);
1595 if (stack == null) {
1596 return;
1597 }
1598 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1599 false /* fromTimeout */, false /* processPausingActivities */, config);
1600 if (r != null) {
1601 proc = r.app;
1602 }
1603 if (stopProfiling && proc != null) {
1604 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 }
1606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001607 } finally {
1608 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 }
1611
1612 @Override
1613 public final void activityResumed(IBinder token) {
1614 final long origId = Binder.clearCallingIdentity();
1615 synchronized (mGlobalLock) {
1616 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001617 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 }
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public final void activityPaused(IBinder token) {
1624 final long origId = Binder.clearCallingIdentity();
1625 synchronized (mGlobalLock) {
1626 ActivityStack stack = ActivityRecord.getStackLocked(token);
1627 if (stack != null) {
1628 stack.activityPausedLocked(token, false);
1629 }
1630 }
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633
1634 @Override
1635 public final void activityStopped(IBinder token, Bundle icicle,
1636 PersistableBundle persistentState, CharSequence description) {
1637 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1638
1639 // Refuse possible leaked file descriptors
1640 if (icicle != null && icicle.hasFileDescriptors()) {
1641 throw new IllegalArgumentException("File descriptors passed in Bundle");
1642 }
1643
1644 final long origId = Binder.clearCallingIdentity();
1645
1646 synchronized (mGlobalLock) {
1647 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1648 if (r != null) {
1649 r.activityStoppedLocked(icicle, persistentState, description);
1650 }
1651 }
1652
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001653 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654
1655 Binder.restoreCallingIdentity(origId);
1656 }
1657
1658 @Override
1659 public final void activityDestroyed(IBinder token) {
1660 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1661 synchronized (mGlobalLock) {
1662 ActivityStack stack = ActivityRecord.getStackLocked(token);
1663 if (stack != null) {
1664 stack.activityDestroyedLocked(token, "activityDestroyed");
1665 }
1666 }
1667 }
1668
1669 @Override
1670 public final void activityRelaunched(IBinder token) {
1671 final long origId = Binder.clearCallingIdentity();
1672 synchronized (mGlobalLock) {
1673 mStackSupervisor.activityRelaunchedLocked(token);
1674 }
1675 Binder.restoreCallingIdentity(origId);
1676 }
1677
1678 public final void activitySlept(IBinder token) {
1679 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1680
1681 final long origId = Binder.clearCallingIdentity();
1682
1683 synchronized (mGlobalLock) {
1684 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1685 if (r != null) {
1686 mStackSupervisor.activitySleptLocked(r);
1687 }
1688 }
1689
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
1694 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1695 synchronized (mGlobalLock) {
1696 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1697 if (r == null) {
1698 return;
1699 }
1700 final long origId = Binder.clearCallingIdentity();
1701 try {
1702 r.setRequestedOrientation(requestedOrientation);
1703 } finally {
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706 }
1707 }
1708
1709 @Override
1710 public int getRequestedOrientation(IBinder token) {
1711 synchronized (mGlobalLock) {
1712 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1713 if (r == null) {
1714 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1715 }
1716 return r.getRequestedOrientation();
1717 }
1718 }
1719
1720 @Override
1721 public void setImmersive(IBinder token, boolean immersive) {
1722 synchronized (mGlobalLock) {
1723 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1724 if (r == null) {
1725 throw new IllegalArgumentException();
1726 }
1727 r.immersive = immersive;
1728
1729 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001730 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001732 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 }
1734 }
1735 }
1736
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001737 void applyUpdateLockStateLocked(ActivityRecord r) {
1738 // Modifications to the UpdateLock state are done on our handler, outside
1739 // the activity manager's locks. The new state is determined based on the
1740 // state *now* of the relevant activity record. The object is passed to
1741 // the handler solely for logging detail, not to be consulted/modified.
1742 final boolean nextState = r != null && r.immersive;
1743 mH.post(() -> {
1744 if (mUpdateLock.isHeld() != nextState) {
1745 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1746 "Applying new update lock state '" + nextState + "' for " + r);
1747 if (nextState) {
1748 mUpdateLock.acquire();
1749 } else {
1750 mUpdateLock.release();
1751 }
1752 }
1753 });
1754 }
1755
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 @Override
1757 public boolean isImmersive(IBinder token) {
1758 synchronized (mGlobalLock) {
1759 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1760 if (r == null) {
1761 throw new IllegalArgumentException();
1762 }
1763 return r.immersive;
1764 }
1765 }
1766
1767 @Override
1768 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001769 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001771 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 return (r != null) ? r.immersive : false;
1773 }
1774 }
1775
1776 @Override
1777 public void overridePendingTransition(IBinder token, String packageName,
1778 int enterAnim, int exitAnim) {
1779 synchronized (mGlobalLock) {
1780 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1781 if (self == null) {
1782 return;
1783 }
1784
1785 final long origId = Binder.clearCallingIdentity();
1786
1787 if (self.isState(
1788 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001789 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001790 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792
1793 Binder.restoreCallingIdentity(origId);
1794 }
1795 }
1796
1797 @Override
1798 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001801 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 if (r == null) {
1803 return ActivityManager.COMPAT_MODE_UNKNOWN;
1804 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001805 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
1807 }
1808
1809 @Override
1810 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001813 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001815 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 if (r == null) {
1817 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1818 return;
1819 }
1820 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001821 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001822 }
1823 }
1824
1825 @Override
1826 public int getLaunchedFromUid(IBinder activityToken) {
1827 ActivityRecord srec;
1828 synchronized (mGlobalLock) {
1829 srec = ActivityRecord.forTokenLocked(activityToken);
1830 }
1831 if (srec == null) {
1832 return -1;
1833 }
1834 return srec.launchedFromUid;
1835 }
1836
1837 @Override
1838 public String getLaunchedFromPackage(IBinder activityToken) {
1839 ActivityRecord srec;
1840 synchronized (mGlobalLock) {
1841 srec = ActivityRecord.forTokenLocked(activityToken);
1842 }
1843 if (srec == null) {
1844 return null;
1845 }
1846 return srec.launchedFromPackage;
1847 }
1848
1849 @Override
1850 public boolean convertFromTranslucent(IBinder token) {
1851 final long origId = Binder.clearCallingIdentity();
1852 try {
1853 synchronized (mGlobalLock) {
1854 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1855 if (r == null) {
1856 return false;
1857 }
1858 final boolean translucentChanged = r.changeWindowTranslucency(true);
1859 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001860 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001862 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 return translucentChanged;
1864 }
1865 } finally {
1866 Binder.restoreCallingIdentity(origId);
1867 }
1868 }
1869
1870 @Override
1871 public boolean convertToTranslucent(IBinder token, Bundle options) {
1872 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1873 final long origId = Binder.clearCallingIdentity();
1874 try {
1875 synchronized (mGlobalLock) {
1876 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1877 if (r == null) {
1878 return false;
1879 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001880 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 int index = task.mActivities.lastIndexOf(r);
1882 if (index > 0) {
1883 ActivityRecord under = task.mActivities.get(index - 1);
1884 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1885 }
1886 final boolean translucentChanged = r.changeWindowTranslucency(false);
1887 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001888 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001890 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 return translucentChanged;
1893 }
1894 } finally {
1895 Binder.restoreCallingIdentity(origId);
1896 }
1897 }
1898
1899 @Override
1900 public void notifyActivityDrawn(IBinder token) {
1901 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1902 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001903 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001905 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908 }
1909
1910 @Override
1911 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1912 synchronized (mGlobalLock) {
1913 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1914 if (r == null) {
1915 return;
1916 }
1917 r.reportFullyDrawnLocked(restoredFromBundle);
1918 }
1919 }
1920
1921 @Override
1922 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1923 synchronized (mGlobalLock) {
1924 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1925 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1926 return stack.mDisplayId;
1927 }
1928 return DEFAULT_DISPLAY;
1929 }
1930 }
1931
1932 @Override
1933 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 long ident = Binder.clearCallingIdentity();
1936 try {
1937 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001938 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001940 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 }
1942 return null;
1943 }
1944 } finally {
1945 Binder.restoreCallingIdentity(ident);
1946 }
1947 }
1948
1949 @Override
1950 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1953 final long callingId = Binder.clearCallingIdentity();
1954 try {
1955 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001956 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 if (stack == null) {
1958 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1959 return;
1960 }
1961 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001962 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 }
1966 } finally {
1967 Binder.restoreCallingIdentity(callingId);
1968 }
1969 }
1970
1971 @Override
1972 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001973 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1975 final long callingId = Binder.clearCallingIdentity();
1976 try {
1977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001978 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001979 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 if (task == null) {
1981 return;
1982 }
1983 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001984 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001985 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 }
1987 }
1988 } finally {
1989 Binder.restoreCallingIdentity(callingId);
1990 }
1991 }
1992
1993 @Override
1994 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001995 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 synchronized (mGlobalLock) {
1997 final long ident = Binder.clearCallingIdentity();
1998 try {
1999 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2000 "remove-task");
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
2003 }
2004 }
2005 }
2006
2007 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002008 public void removeAllVisibleRecentTasks() {
2009 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2010 synchronized (mGlobalLock) {
2011 final long ident = Binder.clearCallingIdentity();
2012 try {
2013 getRecentTasks().removeAllVisibleTasks();
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017 }
2018 }
2019
2020 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2022 synchronized (mGlobalLock) {
2023 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2024 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002025 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 }
2027 }
2028 return false;
2029 }
2030
2031 @Override
2032 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2033 Intent resultData) {
2034
2035 synchronized (mGlobalLock) {
2036 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2037 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002038 return r.getActivityStack().navigateUpToLocked(
2039 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 return false;
2042 }
2043 }
2044
2045 /**
2046 * Attempts to move a task backwards in z-order (the order of activities within the task is
2047 * unchanged).
2048 *
2049 * There are several possible results of this call:
2050 * - if the task is locked, then we will show the lock toast
2051 * - if there is a task behind the provided task, then that task is made visible and resumed as
2052 * this task is moved to the back
2053 * - otherwise, if there are no other tasks in the stack:
2054 * - if this task is in the pinned stack, then we remove the stack completely, which will
2055 * have the effect of moving the task to the top or bottom of the fullscreen stack
2056 * (depending on whether it is visible)
2057 * - otherwise, we simply return home and hide this task
2058 *
2059 * @param token A reference to the activity we wish to move
2060 * @param nonRoot If false then this only works if the activity is the root
2061 * of a task; if true it will work for any activity in a task.
2062 * @return Returns true if the move completed, false if not.
2063 */
2064 @Override
2065 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 synchronized (mGlobalLock) {
2068 final long origId = Binder.clearCallingIdentity();
2069 try {
2070 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002071 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 if (task != null) {
2073 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(origId);
2077 }
2078 }
2079 return false;
2080 }
2081
2082 @Override
2083 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 long ident = Binder.clearCallingIdentity();
2086 Rect rect = new Rect();
2087 try {
2088 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002089 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2091 if (task == null) {
2092 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2093 return rect;
2094 }
2095 if (task.getStack() != null) {
2096 // Return the bounds from window manager since it will be adjusted for various
2097 // things like the presense of a docked stack for tasks that aren't resizeable.
2098 task.getWindowContainerBounds(rect);
2099 } else {
2100 // Task isn't in window manager yet since it isn't associated with a stack.
2101 // Return the persist value from activity manager
2102 if (!task.matchParentBounds()) {
2103 rect.set(task.getBounds());
2104 } else if (task.mLastNonFullscreenBounds != null) {
2105 rect.set(task.mLastNonFullscreenBounds);
2106 }
2107 }
2108 }
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
2112 return rect;
2113 }
2114
2115 @Override
2116 public ActivityManager.TaskDescription getTaskDescription(int id) {
2117 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002118 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002120 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002121 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2122 if (tr != null) {
2123 return tr.lastTaskDescription;
2124 }
2125 }
2126 return null;
2127 }
2128
2129 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002130 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2131 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2132 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2133 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2134 return;
2135 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002136 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002137 synchronized (mGlobalLock) {
2138 final long ident = Binder.clearCallingIdentity();
2139 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002140 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002141 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002142 if (task == null) {
2143 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2144 return;
2145 }
2146
2147 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2148 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2149
2150 if (!task.isActivityTypeStandardOrUndefined()) {
2151 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2152 + " non-standard task " + taskId + " to windowing mode="
2153 + windowingMode);
2154 }
2155
2156 final ActivityStack stack = task.getStack();
2157 if (toTop) {
2158 stack.moveToFront("setTaskWindowingMode", task);
2159 }
2160 stack.setWindowingMode(windowingMode);
2161 } finally {
2162 Binder.restoreCallingIdentity(ident);
2163 }
2164 }
2165 }
2166
2167 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002169 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 ActivityRecord r = getCallingRecordLocked(token);
2171 return r != null ? r.info.packageName : null;
2172 }
2173 }
2174
2175 @Override
2176 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002177 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 ActivityRecord r = getCallingRecordLocked(token);
2179 return r != null ? r.intent.getComponent() : null;
2180 }
2181 }
2182
2183 private ActivityRecord getCallingRecordLocked(IBinder token) {
2184 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2185 if (r == null) {
2186 return null;
2187 }
2188 return r.resultTo;
2189 }
2190
2191 @Override
2192 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194
2195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002198 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 } finally {
2200 Binder.restoreCallingIdentity(origId);
2201 }
2202 }
2203 }
2204
2205 /**
2206 * TODO: Add mController hook
2207 */
2208 @Override
2209 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211
2212 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2213 synchronized (mGlobalLock) {
2214 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2215 false /* fromRecents */);
2216 }
2217 }
2218
2219 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2220 boolean fromRecents) {
2221
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 Binder.getCallingUid(), -1, -1, "Task to front")) {
2224 SafeActivityOptions.abort(options);
2225 return;
2226 }
2227 final long origId = Binder.clearCallingIdentity();
2228 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002229 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 if (task == null) {
2231 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002232 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 return;
2234 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002235 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002237 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 return;
2239 }
2240 ActivityOptions realOptions = options != null
2241 ? options.getOptions(mStackSupervisor)
2242 : null;
2243 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2244 false /* forceNonResizable */);
2245
2246 final ActivityRecord topActivity = task.getTopActivity();
2247 if (topActivity != null) {
2248
2249 // We are reshowing a task, use a starting window to hide the initial draw delay
2250 // so the transition can start earlier.
2251 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2252 true /* taskSwitch */, fromRecents);
2253 }
2254 } finally {
2255 Binder.restoreCallingIdentity(origId);
2256 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002257 }
2258
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002259 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2260 int callingPid, int callingUid, String name) {
2261 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2262 return true;
2263 }
2264
2265 if (getRecentTasks().isCallerRecents(sourceUid)) {
2266 return true;
2267 }
2268
2269 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2270 if (perm == PackageManager.PERMISSION_GRANTED) {
2271 return true;
2272 }
2273 if (checkAllowAppSwitchUid(sourceUid)) {
2274 return true;
2275 }
2276
2277 // If the actual IPC caller is different from the logical source, then
2278 // also see if they are allowed to control app switches.
2279 if (callingUid != -1 && callingUid != sourceUid) {
2280 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2281 if (perm == PackageManager.PERMISSION_GRANTED) {
2282 return true;
2283 }
2284 if (checkAllowAppSwitchUid(callingUid)) {
2285 return true;
2286 }
2287 }
2288
2289 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2290 return false;
2291 }
2292
2293 private boolean checkAllowAppSwitchUid(int uid) {
2294 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2295 if (types != null) {
2296 for (int i = types.size() - 1; i >= 0; i--) {
2297 if (types.valueAt(i).intValue() == uid) {
2298 return true;
2299 }
2300 }
2301 }
2302 return false;
2303 }
2304
2305 @Override
2306 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2307 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2308 "setActivityController()");
2309 synchronized (mGlobalLock) {
2310 mController = controller;
2311 mControllerIsAMonkey = imAMonkey;
2312 Watchdog.getInstance().setActivityController(controller);
2313 }
2314 }
2315
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002316 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002317 synchronized (mGlobalLock) {
2318 return mController != null && mControllerIsAMonkey;
2319 }
2320 }
2321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 @Override
2323 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2324 synchronized (mGlobalLock) {
2325 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2326 }
2327 }
2328
2329 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002330 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2331 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2332 }
2333
2334 @Override
2335 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2336 @WindowConfiguration.ActivityType int ignoreActivityType,
2337 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2338 final int callingUid = Binder.getCallingUid();
2339 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2340
2341 synchronized (mGlobalLock) {
2342 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2343
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002345 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002346 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002347 ignoreWindowingMode, callingUid, allowed);
2348 }
2349
2350 return list;
2351 }
2352
2353 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2355 synchronized (mGlobalLock) {
2356 final long origId = Binder.clearCallingIdentity();
2357 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2358 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002359 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 }
2361 Binder.restoreCallingIdentity(origId);
2362 }
2363 }
2364
2365 @Override
2366 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 ActivityStack stack = ActivityRecord.getStackLocked(token);
2369 if (stack != null) {
2370 return stack.willActivityBeVisibleLocked(token);
2371 }
2372 return false;
2373 }
2374 }
2375
2376 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002377 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002378 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 synchronized (mGlobalLock) {
2380 final long ident = Binder.clearCallingIdentity();
2381 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002382 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002383 if (task == null) {
2384 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2385 return;
2386 }
2387
2388 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2389 + " to stackId=" + stackId + " toTop=" + toTop);
2390
Wale Ogunwaled32da472018-11-16 07:19:28 -08002391 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002392 if (stack == null) {
2393 throw new IllegalStateException(
2394 "moveTaskToStack: No stack for stackId=" + stackId);
2395 }
2396 if (!stack.isActivityTypeStandardOrUndefined()) {
2397 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2398 + taskId + " to stack " + stackId);
2399 }
2400 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002401 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002402 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2403 }
2404 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2405 "moveTaskToStack");
2406 } finally {
2407 Binder.restoreCallingIdentity(ident);
2408 }
2409 }
2410 }
2411
2412 @Override
2413 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2414 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002416
2417 final long ident = Binder.clearCallingIdentity();
2418 try {
2419 synchronized (mGlobalLock) {
2420 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -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 }
2426 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2427 throw new IllegalArgumentException("Stack: " + stackId
2428 + " doesn't support animated resize.");
2429 }
2430 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2431 animationDuration, false /* fromFullscreen */);
2432 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002433 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002434 if (stack == null) {
2435 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2436 return;
2437 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002438 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2440 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2441 }
2442 }
2443 } finally {
2444 Binder.restoreCallingIdentity(ident);
2445 }
2446 }
2447
2448 /**
2449 * Moves the specified task to the primary-split-screen stack.
2450 *
2451 * @param taskId Id of task to move.
2452 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2453 * exist already. See
2454 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2455 * and
2456 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2457 * @param toTop If the task and stack should be moved to the top.
2458 * @param animate Whether we should play an animation for the moving the task.
2459 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2460 * stack. Pass {@code null} to use default bounds.
2461 * @param showRecents If the recents activity should be shown on the other side of the task
2462 * going into split-screen mode.
2463 */
2464 @Override
2465 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2466 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002467 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002468 "setTaskWindowingModeSplitScreenPrimary()");
2469 synchronized (mGlobalLock) {
2470 final long ident = Binder.clearCallingIdentity();
2471 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002472 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002473 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002474 if (task == null) {
2475 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2476 return false;
2477 }
2478 if (DEBUG_STACK) Slog.d(TAG_STACK,
2479 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2480 + " to createMode=" + createMode + " toTop=" + toTop);
2481 if (!task.isActivityTypeStandardOrUndefined()) {
2482 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2483 + " non-standard task " + taskId + " to split-screen windowing mode");
2484 }
2485
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002486 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002487 final int windowingMode = task.getWindowingMode();
2488 final ActivityStack stack = task.getStack();
2489 if (toTop) {
2490 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2491 }
2492 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002493 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2494 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002495 return windowingMode != task.getWindowingMode();
2496 } finally {
2497 Binder.restoreCallingIdentity(ident);
2498 }
2499 }
2500 }
2501
2502 /**
2503 * Removes stacks in the input windowing modes from the system if they are of activity type
2504 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2505 */
2506 @Override
2507 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002508 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002509 "removeStacksInWindowingModes()");
2510
2511 synchronized (mGlobalLock) {
2512 final long ident = Binder.clearCallingIdentity();
2513 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002514 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002515 } finally {
2516 Binder.restoreCallingIdentity(ident);
2517 }
2518 }
2519 }
2520
2521 @Override
2522 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002523 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002524 "removeStacksWithActivityTypes()");
2525
2526 synchronized (mGlobalLock) {
2527 final long ident = Binder.clearCallingIdentity();
2528 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002529 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002530 } finally {
2531 Binder.restoreCallingIdentity(ident);
2532 }
2533 }
2534 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002535
2536 @Override
2537 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2538 int userId) {
2539 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002540 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2541 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002542 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002543 final boolean detailed = checkGetTasksPermission(
2544 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2545 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002546 == PackageManager.PERMISSION_GRANTED;
2547
2548 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002549 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002550 callingUid);
2551 }
2552 }
2553
2554 @Override
2555 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002556 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 long ident = Binder.clearCallingIdentity();
2558 try {
2559 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002560 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002561 }
2562 } finally {
2563 Binder.restoreCallingIdentity(ident);
2564 }
2565 }
2566
2567 @Override
2568 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002569 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002570 long ident = Binder.clearCallingIdentity();
2571 try {
2572 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002573 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002574 }
2575 } finally {
2576 Binder.restoreCallingIdentity(ident);
2577 }
2578 }
2579
2580 @Override
2581 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002582 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002583 final long callingUid = Binder.getCallingUid();
2584 final long origId = Binder.clearCallingIdentity();
2585 try {
2586 synchronized (mGlobalLock) {
2587 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002588 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002589 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2590 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2591 }
2592 } finally {
2593 Binder.restoreCallingIdentity(origId);
2594 }
2595 }
2596
2597 @Override
2598 public void startLockTaskModeByToken(IBinder token) {
2599 synchronized (mGlobalLock) {
2600 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2601 if (r == null) {
2602 return;
2603 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002604 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002605 }
2606 }
2607
2608 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002609 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002610 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002611 // This makes inner call to look as if it was initiated by system.
2612 long ident = Binder.clearCallingIdentity();
2613 try {
2614 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002615 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002616 MATCH_TASK_IN_STACKS_ONLY);
2617 if (task == null) {
2618 return;
2619 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002620
2621 // When starting lock task mode the stack must be in front and focused
2622 task.getStack().moveToFront("startSystemLockTaskMode");
2623 startLockTaskModeLocked(task, true /* isSystemCaller */);
2624 }
2625 } finally {
2626 Binder.restoreCallingIdentity(ident);
2627 }
2628 }
2629
2630 @Override
2631 public void stopLockTaskModeByToken(IBinder token) {
2632 synchronized (mGlobalLock) {
2633 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2634 if (r == null) {
2635 return;
2636 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002637 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002638 }
2639 }
2640
2641 /**
2642 * This API should be called by SystemUI only when user perform certain action to dismiss
2643 * lock task mode. We should only dismiss pinned lock task mode in this case.
2644 */
2645 @Override
2646 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002647 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002648 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2649 }
2650
2651 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2652 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2653 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2654 return;
2655 }
2656
Wale Ogunwaled32da472018-11-16 07:19:28 -08002657 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002658 if (stack == null || task != stack.topTask()) {
2659 throw new IllegalArgumentException("Invalid task, not in foreground");
2660 }
2661
2662 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2663 // system or a specific app.
2664 // * System-initiated requests will only start the pinned mode (screen pinning)
2665 // * App-initiated requests
2666 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2667 // - will start the pinned mode, otherwise
2668 final int callingUid = Binder.getCallingUid();
2669 long ident = Binder.clearCallingIdentity();
2670 try {
2671 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002672 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002673
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002674 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002675 } finally {
2676 Binder.restoreCallingIdentity(ident);
2677 }
2678 }
2679
2680 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2681 final int callingUid = Binder.getCallingUid();
2682 long ident = Binder.clearCallingIdentity();
2683 try {
2684 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002685 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002686 }
2687 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2688 // task and jumping straight into a call in the case of emergency call back.
2689 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2690 if (tm != null) {
2691 tm.showInCallScreen(false);
2692 }
2693 } finally {
2694 Binder.restoreCallingIdentity(ident);
2695 }
2696 }
2697
2698 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002699 public void updateLockTaskPackages(int userId, String[] packages) {
2700 final int callingUid = Binder.getCallingUid();
2701 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2702 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2703 "updateLockTaskPackages()");
2704 }
2705 synchronized (this) {
2706 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2707 + Arrays.toString(packages));
2708 getLockTaskController().updateLockTaskPackages(userId, packages);
2709 }
2710 }
2711
2712 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002713 public boolean isInLockTaskMode() {
2714 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2715 }
2716
2717 @Override
2718 public int getLockTaskModeState() {
2719 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002720 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002721 }
2722 }
2723
2724 @Override
2725 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2726 synchronized (mGlobalLock) {
2727 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2728 if (r != null) {
2729 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002730 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002731 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002732 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002733 }
2734 }
2735 }
2736
2737 @Override
2738 public Bundle getActivityOptions(IBinder token) {
2739 final long origId = Binder.clearCallingIdentity();
2740 try {
2741 synchronized (mGlobalLock) {
2742 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2743 if (r != null) {
2744 final ActivityOptions activityOptions = r.takeOptionsLocked();
2745 return activityOptions == null ? null : activityOptions.toBundle();
2746 }
2747 return null;
2748 }
2749 } finally {
2750 Binder.restoreCallingIdentity(origId);
2751 }
2752 }
2753
2754 @Override
2755 public List<IBinder> getAppTasks(String callingPackage) {
2756 int callingUid = Binder.getCallingUid();
2757 long ident = Binder.clearCallingIdentity();
2758 try {
2759 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002760 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002761 }
2762 } finally {
2763 Binder.restoreCallingIdentity(ident);
2764 }
2765 }
2766
2767 @Override
2768 public void finishVoiceTask(IVoiceInteractionSession session) {
2769 synchronized (mGlobalLock) {
2770 final long origId = Binder.clearCallingIdentity();
2771 try {
2772 // TODO: VI Consider treating local voice interactions and voice tasks
2773 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002774 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002775 } finally {
2776 Binder.restoreCallingIdentity(origId);
2777 }
2778 }
2779
2780 }
2781
2782 @Override
2783 public boolean isTopOfTask(IBinder token) {
2784 synchronized (mGlobalLock) {
2785 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002786 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002787 }
2788 }
2789
2790 @Override
2791 public void notifyLaunchTaskBehindComplete(IBinder token) {
2792 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2793 }
2794
2795 @Override
2796 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002797 mH.post(() -> {
2798 synchronized (mGlobalLock) {
2799 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002800 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002801 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002802 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002803 } catch (RemoteException e) {
2804 }
2805 }
2806 }
2807
2808 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 }
2810
2811 /** Called from an app when assist data is ready. */
2812 @Override
2813 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2814 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002815 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002816 synchronized (pae) {
2817 pae.result = extras;
2818 pae.structure = structure;
2819 pae.content = content;
2820 if (referrer != null) {
2821 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2822 }
2823 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002824 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002825 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2826 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002827 structure.setHomeActivity(pae.isHome);
2828 }
2829 pae.haveResult = true;
2830 pae.notifyAll();
2831 if (pae.intent == null && pae.receiver == null) {
2832 // Caller is just waiting for the result.
2833 return;
2834 }
2835 }
2836 // We are now ready to launch the assist activity.
2837 IAssistDataReceiver sendReceiver = null;
2838 Bundle sendBundle = null;
2839 synchronized (mGlobalLock) {
2840 buildAssistBundleLocked(pae, extras);
2841 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002842 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 if (!exists) {
2844 // Timed out.
2845 return;
2846 }
2847
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002848 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002849 // Caller wants result sent back to them.
2850 sendBundle = new Bundle();
2851 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2852 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2853 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2854 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2855 }
2856 }
2857 if (sendReceiver != null) {
2858 try {
2859 sendReceiver.onHandleAssistData(sendBundle);
2860 } catch (RemoteException e) {
2861 }
2862 return;
2863 }
2864
2865 final long ident = Binder.clearCallingIdentity();
2866 try {
2867 if (TextUtils.equals(pae.intent.getAction(),
2868 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2869 pae.intent.putExtras(pae.extras);
2870 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2871 } else {
2872 pae.intent.replaceExtras(pae.extras);
2873 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2874 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2875 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002876 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877
2878 try {
2879 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2880 } catch (ActivityNotFoundException e) {
2881 Slog.w(TAG, "No activity to handle assist action.", e);
2882 }
2883 }
2884 } finally {
2885 Binder.restoreCallingIdentity(ident);
2886 }
2887 }
2888
2889 @Override
2890 public int addAppTask(IBinder activityToken, Intent intent,
2891 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2892 final int callingUid = Binder.getCallingUid();
2893 final long callingIdent = Binder.clearCallingIdentity();
2894
2895 try {
2896 synchronized (mGlobalLock) {
2897 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2898 if (r == null) {
2899 throw new IllegalArgumentException("Activity does not exist; token="
2900 + activityToken);
2901 }
2902 ComponentName comp = intent.getComponent();
2903 if (comp == null) {
2904 throw new IllegalArgumentException("Intent " + intent
2905 + " must specify explicit component");
2906 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002907 if (thumbnail.getWidth() != mThumbnailWidth
2908 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002909 throw new IllegalArgumentException("Bad thumbnail size: got "
2910 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002911 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002912 }
2913 if (intent.getSelector() != null) {
2914 intent.setSelector(null);
2915 }
2916 if (intent.getSourceBounds() != null) {
2917 intent.setSourceBounds(null);
2918 }
2919 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2920 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2921 // The caller has added this as an auto-remove task... that makes no
2922 // sense, so turn off auto-remove.
2923 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2924 }
2925 }
2926 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2927 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2928 if (ainfo.applicationInfo.uid != callingUid) {
2929 throw new SecurityException(
2930 "Can't add task for another application: target uid="
2931 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2932 }
2933
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002934 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002935 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002936 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002937 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002938 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002939 // The app has too many tasks already and we can't add any more
2940 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2941 return INVALID_TASK_ID;
2942 }
2943 task.lastTaskDescription.copyFrom(description);
2944
2945 // TODO: Send the thumbnail to WM to store it.
2946
2947 return task.taskId;
2948 }
2949 } finally {
2950 Binder.restoreCallingIdentity(callingIdent);
2951 }
2952 }
2953
2954 @Override
2955 public Point getAppTaskThumbnailSize() {
2956 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002957 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002958 }
2959 }
2960
2961 @Override
2962 public void setTaskResizeable(int taskId, int resizeableMode) {
2963 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002964 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002965 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2966 if (task == null) {
2967 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2968 return;
2969 }
2970 task.setResizeMode(resizeableMode);
2971 }
2972 }
2973
2974 @Override
2975 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002976 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002977 long ident = Binder.clearCallingIdentity();
2978 try {
2979 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002980 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002981 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 if (task == null) {
2983 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2984 return;
2985 }
2986 // Place the task in the right stack if it isn't there already based on
2987 // the requested bounds.
2988 // The stack transition logic is:
2989 // - a null bounds on a freeform task moves that task to fullscreen
2990 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2991 // that task to freeform
2992 // - otherwise the task is not moved
2993 ActivityStack stack = task.getStack();
2994 if (!task.getWindowConfiguration().canResizeTask()) {
2995 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2996 }
2997 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2998 stack = stack.getDisplay().getOrCreateStack(
2999 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3000 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3001 stack = stack.getDisplay().getOrCreateStack(
3002 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3003 }
3004
3005 // Reparent the task to the right stack if necessary
3006 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3007 if (stack != task.getStack()) {
3008 // Defer resume until the task is resized below
3009 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3010 DEFER_RESUME, "resizeTask");
3011 preserveWindow = false;
3012 }
3013
3014 // After reparenting (which only resizes the task to the stack bounds), resize the
3015 // task to the actual bounds provided
3016 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3017 }
3018 } finally {
3019 Binder.restoreCallingIdentity(ident);
3020 }
3021 }
3022
3023 @Override
3024 public boolean releaseActivityInstance(IBinder token) {
3025 synchronized (mGlobalLock) {
3026 final long origId = Binder.clearCallingIdentity();
3027 try {
3028 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3029 if (r == null) {
3030 return false;
3031 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003032 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 } finally {
3034 Binder.restoreCallingIdentity(origId);
3035 }
3036 }
3037 }
3038
3039 @Override
3040 public void releaseSomeActivities(IApplicationThread appInt) {
3041 synchronized (mGlobalLock) {
3042 final long origId = Binder.clearCallingIdentity();
3043 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003044 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003045 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003046 } finally {
3047 Binder.restoreCallingIdentity(origId);
3048 }
3049 }
3050 }
3051
3052 @Override
3053 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003054 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003055 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 != PackageManager.PERMISSION_GRANTED) {
3057 throw new SecurityException("Requires permission "
3058 + android.Manifest.permission.DEVICE_POWER);
3059 }
3060
3061 synchronized (mGlobalLock) {
3062 long ident = Binder.clearCallingIdentity();
3063 if (mKeyguardShown != keyguardShowing) {
3064 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003065 final Message msg = PooledLambda.obtainMessage(
3066 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3067 keyguardShowing);
3068 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003069 }
3070 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003071 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003072 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003073 } finally {
3074 Binder.restoreCallingIdentity(ident);
3075 }
3076 }
3077
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003078 mH.post(() -> {
3079 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3080 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3081 }
3082 });
3083 }
3084
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003085 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003086 mH.post(() -> {
3087 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3088 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3089 }
3090 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003091 }
3092
3093 @Override
3094 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003095 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3096 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003097
3098 final File passedIconFile = new File(filePath);
3099 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3100 passedIconFile.getName());
3101 if (!legitIconFile.getPath().equals(filePath)
3102 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3103 throw new IllegalArgumentException("Bad file path: " + filePath
3104 + " passed for userId " + userId);
3105 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003106 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 }
3108
3109 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003110 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003111 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3112 final ActivityOptions activityOptions = safeOptions != null
3113 ? safeOptions.getOptions(mStackSupervisor)
3114 : null;
3115 if (activityOptions == null
3116 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3117 || activityOptions.getCustomInPlaceResId() == 0) {
3118 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3119 "with valid animation");
3120 }
lumark588a3e82018-07-20 18:53:54 +08003121 // Get top display of front most application.
3122 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3123 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003124 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3125 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3126 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003127 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003128 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003129 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003130 }
3131
3132 @Override
3133 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003134 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003135 synchronized (mGlobalLock) {
3136 final long ident = Binder.clearCallingIdentity();
3137 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003138 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003139 if (stack == null) {
3140 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3141 return;
3142 }
3143 if (!stack.isActivityTypeStandardOrUndefined()) {
3144 throw new IllegalArgumentException(
3145 "Removing non-standard stack is not allowed.");
3146 }
3147 mStackSupervisor.removeStack(stack);
3148 } finally {
3149 Binder.restoreCallingIdentity(ident);
3150 }
3151 }
3152 }
3153
3154 @Override
3155 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003156 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157
3158 synchronized (mGlobalLock) {
3159 final long ident = Binder.clearCallingIdentity();
3160 try {
3161 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3162 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003163 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 } finally {
3165 Binder.restoreCallingIdentity(ident);
3166 }
3167 }
3168 }
3169
3170 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003171 public void exitFreeformMode(IBinder token) {
3172 synchronized (mGlobalLock) {
3173 long ident = Binder.clearCallingIdentity();
3174 try {
3175 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3176 if (r == null) {
3177 throw new IllegalArgumentException(
3178 "exitFreeformMode: No activity record matching token=" + token);
3179 }
3180
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003181 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 if (stack == null || !stack.inFreeformWindowingMode()) {
3183 throw new IllegalStateException(
3184 "exitFreeformMode: You can only go fullscreen from freeform.");
3185 }
3186
3187 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3188 } finally {
3189 Binder.restoreCallingIdentity(ident);
3190 }
3191 }
3192 }
3193
3194 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3195 @Override
3196 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003197 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003199 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200 }
3201
3202 /** Unregister a task stack listener so that it stops receiving callbacks. */
3203 @Override
3204 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003205 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003207 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 }
3209
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003210 @Override
3211 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3212 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3213 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3214 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3215 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3216 }
3217
3218 @Override
3219 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3220 IBinder activityToken, int flags) {
3221 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3222 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3223 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3224 }
3225
3226 @Override
3227 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3228 Bundle args) {
3229 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3230 true /* focused */, true /* newSessionId */, userHandle, args,
3231 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3232 }
3233
3234 @Override
3235 public Bundle getAssistContextExtras(int requestType) {
3236 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3237 null, null, true /* focused */, true /* newSessionId */,
3238 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3239 if (pae == null) {
3240 return null;
3241 }
3242 synchronized (pae) {
3243 while (!pae.haveResult) {
3244 try {
3245 pae.wait();
3246 } catch (InterruptedException e) {
3247 }
3248 }
3249 }
3250 synchronized (mGlobalLock) {
3251 buildAssistBundleLocked(pae, pae.result);
3252 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003253 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003254 }
3255 return pae.extras;
3256 }
3257
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003258 /**
3259 * Binder IPC calls go through the public entry point.
3260 * This can be called with or without the global lock held.
3261 */
3262 private static int checkCallingPermission(String permission) {
3263 return checkPermission(
3264 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3265 }
3266
3267 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003268 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003269 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3270 mAmInternal.enforceCallingPermission(permission, func);
3271 }
3272 }
3273
3274 @VisibleForTesting
3275 int checkGetTasksPermission(String permission, int pid, int uid) {
3276 return checkPermission(permission, pid, uid);
3277 }
3278
3279 static int checkPermission(String permission, int pid, int uid) {
3280 if (permission == null) {
3281 return PackageManager.PERMISSION_DENIED;
3282 }
3283 return checkComponentPermission(permission, pid, uid, -1, true);
3284 }
3285
Wale Ogunwale214f3482018-10-04 11:00:47 -07003286 public static int checkComponentPermission(String permission, int pid, int uid,
3287 int owningUid, boolean exported) {
3288 return ActivityManagerService.checkComponentPermission(
3289 permission, pid, uid, owningUid, exported);
3290 }
3291
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003292 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3293 if (getRecentTasks().isCallerRecents(callingUid)) {
3294 // Always allow the recents component to get tasks
3295 return true;
3296 }
3297
3298 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3299 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3300 if (!allowed) {
3301 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3302 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3303 // Temporary compatibility: some existing apps on the system image may
3304 // still be requesting the old permission and not switched to the new
3305 // one; if so, we'll still allow them full access. This means we need
3306 // to see if they are holding the old permission and are a system app.
3307 try {
3308 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3309 allowed = true;
3310 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3311 + " is using old GET_TASKS but privileged; allowing");
3312 }
3313 } catch (RemoteException e) {
3314 }
3315 }
3316 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3317 + " does not hold REAL_GET_TASKS; limiting output");
3318 }
3319 return allowed;
3320 }
3321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003322 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3323 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3324 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3325 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003326 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003327 "enqueueAssistContext()");
3328
3329 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003330 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003331 if (activity == null) {
3332 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3333 return null;
3334 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003335 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003336 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3337 return null;
3338 }
3339 if (focused) {
3340 if (activityToken != null) {
3341 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3342 if (activity != caller) {
3343 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3344 + " is not current top " + activity);
3345 return null;
3346 }
3347 }
3348 } else {
3349 activity = ActivityRecord.forTokenLocked(activityToken);
3350 if (activity == null) {
3351 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3352 + " couldn't be found");
3353 return null;
3354 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003355 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003356 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3357 return null;
3358 }
3359 }
3360
3361 PendingAssistExtras pae;
3362 Bundle extras = new Bundle();
3363 if (args != null) {
3364 extras.putAll(args);
3365 }
3366 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003367 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003368
3369 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3370 userHandle);
3371 pae.isHome = activity.isActivityTypeHome();
3372
3373 // Increment the sessionId if necessary
3374 if (newSessionId) {
3375 mViSessionId++;
3376 }
3377 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003378 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3379 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003380 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003381 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003382 } catch (RemoteException e) {
3383 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3384 return null;
3385 }
3386 return pae;
3387 }
3388 }
3389
3390 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3391 if (result != null) {
3392 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3393 }
3394 if (pae.hint != null) {
3395 pae.extras.putBoolean(pae.hint, true);
3396 }
3397 }
3398
3399 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3400 IAssistDataReceiver receiver;
3401 synchronized (mGlobalLock) {
3402 mPendingAssistExtras.remove(pae);
3403 receiver = pae.receiver;
3404 }
3405 if (receiver != null) {
3406 // Caller wants result sent back to them.
3407 Bundle sendBundle = new Bundle();
3408 // At least return the receiver extras
3409 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3410 try {
3411 pae.receiver.onHandleAssistData(sendBundle);
3412 } catch (RemoteException e) {
3413 }
3414 }
3415 }
3416
3417 public class PendingAssistExtras extends Binder implements Runnable {
3418 public final ActivityRecord activity;
3419 public boolean isHome;
3420 public final Bundle extras;
3421 public final Intent intent;
3422 public final String hint;
3423 public final IAssistDataReceiver receiver;
3424 public final int userHandle;
3425 public boolean haveResult = false;
3426 public Bundle result = null;
3427 public AssistStructure structure = null;
3428 public AssistContent content = null;
3429 public Bundle receiverExtras;
3430
3431 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3432 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3433 int _userHandle) {
3434 activity = _activity;
3435 extras = _extras;
3436 intent = _intent;
3437 hint = _hint;
3438 receiver = _receiver;
3439 receiverExtras = _receiverExtras;
3440 userHandle = _userHandle;
3441 }
3442
3443 @Override
3444 public void run() {
3445 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3446 synchronized (this) {
3447 haveResult = true;
3448 notifyAll();
3449 }
3450 pendingAssistExtrasTimedOut(this);
3451 }
3452 }
3453
3454 @Override
3455 public boolean isAssistDataAllowedOnCurrentActivity() {
3456 int userId;
3457 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003458 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003459 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3460 return false;
3461 }
3462
3463 final ActivityRecord activity = focusedStack.getTopActivity();
3464 if (activity == null) {
3465 return false;
3466 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003467 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003468 }
3469 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3470 }
3471
3472 @Override
3473 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3474 long ident = Binder.clearCallingIdentity();
3475 try {
3476 synchronized (mGlobalLock) {
3477 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003478 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003479 if (top != caller) {
3480 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3481 + " is not current top " + top);
3482 return false;
3483 }
3484 if (!top.nowVisible) {
3485 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3486 + " is not visible");
3487 return false;
3488 }
3489 }
3490 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3491 token);
3492 } finally {
3493 Binder.restoreCallingIdentity(ident);
3494 }
3495 }
3496
3497 @Override
3498 public boolean isRootVoiceInteraction(IBinder token) {
3499 synchronized (mGlobalLock) {
3500 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3501 if (r == null) {
3502 return false;
3503 }
3504 return r.rootVoiceInteraction;
3505 }
3506 }
3507
Wale Ogunwalef6733932018-06-27 05:14:34 -07003508 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3509 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3510 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3511 if (activityToCallback == null) return;
3512 activityToCallback.setVoiceSessionLocked(voiceSession);
3513
3514 // Inform the activity
3515 try {
3516 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3517 voiceInteractor);
3518 long token = Binder.clearCallingIdentity();
3519 try {
3520 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3521 } finally {
3522 Binder.restoreCallingIdentity(token);
3523 }
3524 // TODO: VI Should we cache the activity so that it's easier to find later
3525 // rather than scan through all the stacks and activities?
3526 } catch (RemoteException re) {
3527 activityToCallback.clearVoiceSessionLocked();
3528 // TODO: VI Should this terminate the voice session?
3529 }
3530 }
3531
3532 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3533 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3534 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3535 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3536 boolean wasRunningVoice = mRunningVoice != null;
3537 mRunningVoice = session;
3538 if (!wasRunningVoice) {
3539 mVoiceWakeLock.acquire();
3540 updateSleepIfNeededLocked();
3541 }
3542 }
3543 }
3544
3545 void finishRunningVoiceLocked() {
3546 if (mRunningVoice != null) {
3547 mRunningVoice = null;
3548 mVoiceWakeLock.release();
3549 updateSleepIfNeededLocked();
3550 }
3551 }
3552
3553 @Override
3554 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3555 synchronized (mGlobalLock) {
3556 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3557 if (keepAwake) {
3558 mVoiceWakeLock.acquire();
3559 } else {
3560 mVoiceWakeLock.release();
3561 }
3562 }
3563 }
3564 }
3565
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003566 @Override
3567 public ComponentName getActivityClassForToken(IBinder token) {
3568 synchronized (mGlobalLock) {
3569 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3570 if (r == null) {
3571 return null;
3572 }
3573 return r.intent.getComponent();
3574 }
3575 }
3576
3577 @Override
3578 public String getPackageForToken(IBinder token) {
3579 synchronized (mGlobalLock) {
3580 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3581 if (r == null) {
3582 return null;
3583 }
3584 return r.packageName;
3585 }
3586 }
3587
3588 @Override
3589 public void showLockTaskEscapeMessage(IBinder token) {
3590 synchronized (mGlobalLock) {
3591 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3592 if (r == null) {
3593 return;
3594 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003595 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003596 }
3597 }
3598
3599 @Override
3600 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003601 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003602 final long token = Binder.clearCallingIdentity();
3603 try {
3604 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003605 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003606 }
3607 } finally {
3608 Binder.restoreCallingIdentity(token);
3609 }
3610 }
3611
3612 /**
3613 * Try to place task to provided position. The final position might be different depending on
3614 * current user and stacks state. The task will be moved to target stack if it's currently in
3615 * different stack.
3616 */
3617 @Override
3618 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003619 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003620 synchronized (mGlobalLock) {
3621 long ident = Binder.clearCallingIdentity();
3622 try {
3623 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3624 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003625 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003626 if (task == null) {
3627 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3628 + taskId);
3629 }
3630
Wale Ogunwaled32da472018-11-16 07:19:28 -08003631 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003632
3633 if (stack == null) {
3634 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3635 + stackId);
3636 }
3637 if (!stack.isActivityTypeStandardOrUndefined()) {
3638 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3639 + " the position of task " + taskId + " in/to non-standard stack");
3640 }
3641
3642 // TODO: Have the callers of this API call a separate reparent method if that is
3643 // what they intended to do vs. having this method also do reparenting.
3644 if (task.getStack() == stack) {
3645 // Change position in current stack.
3646 stack.positionChildAt(task, position);
3647 } else {
3648 // Reparent to new stack.
3649 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3650 !DEFER_RESUME, "positionTaskInStack");
3651 }
3652 } finally {
3653 Binder.restoreCallingIdentity(ident);
3654 }
3655 }
3656 }
3657
3658 @Override
3659 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3660 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3661 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3662 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3663 synchronized (mGlobalLock) {
3664 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3665 if (record == null) {
3666 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3667 + "found for: " + token);
3668 }
3669 record.setSizeConfigurations(horizontalSizeConfiguration,
3670 verticalSizeConfigurations, smallestSizeConfigurations);
3671 }
3672 }
3673
3674 /**
3675 * Dismisses split-screen multi-window mode.
3676 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3677 */
3678 @Override
3679 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003680 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003681 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3682 final long ident = Binder.clearCallingIdentity();
3683 try {
3684 synchronized (mGlobalLock) {
3685 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003686 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003687 if (stack == null) {
3688 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3689 return;
3690 }
3691
3692 if (toTop) {
3693 // Caller wants the current split-screen primary stack to be the top stack after
3694 // it goes fullscreen, so move it to the front.
3695 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003696 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003697 // In this case the current split-screen primary stack shouldn't be the top
3698 // stack after it goes fullscreen, but it current has focus, so we move the
3699 // focus to the top-most split-screen secondary stack next to it.
3700 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3701 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3702 if (otherStack != null) {
3703 otherStack.moveToFront("dismissSplitScreenMode_other");
3704 }
3705 }
3706
Evan Rosky10475742018-09-05 19:02:48 -07003707 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003708 }
3709 } finally {
3710 Binder.restoreCallingIdentity(ident);
3711 }
3712 }
3713
3714 /**
3715 * Dismisses Pip
3716 * @param animate True if the dismissal should be animated.
3717 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3718 * default animation duration should be used.
3719 */
3720 @Override
3721 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003722 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003723 final long ident = Binder.clearCallingIdentity();
3724 try {
3725 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003726 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003727 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003728 if (stack == null) {
3729 Slog.w(TAG, "dismissPip: pinned stack not found.");
3730 return;
3731 }
3732 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3733 throw new IllegalArgumentException("Stack: " + stack
3734 + " doesn't support animated resize.");
3735 }
3736 if (animate) {
3737 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3738 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3739 } else {
3740 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3741 }
3742 }
3743 } finally {
3744 Binder.restoreCallingIdentity(ident);
3745 }
3746 }
3747
3748 @Override
3749 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003750 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 synchronized (mGlobalLock) {
3752 mSuppressResizeConfigChanges = suppress;
3753 }
3754 }
3755
3756 /**
3757 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3758 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3759 * activity and clearing the task at the same time.
3760 */
3761 @Override
3762 // TODO: API should just be about changing windowing modes...
3763 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003764 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003765 "moveTasksToFullscreenStack()");
3766 synchronized (mGlobalLock) {
3767 final long origId = Binder.clearCallingIdentity();
3768 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003769 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003770 if (stack != null){
3771 if (!stack.isActivityTypeStandardOrUndefined()) {
3772 throw new IllegalArgumentException(
3773 "You can't move tasks from non-standard stacks.");
3774 }
3775 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3776 }
3777 } finally {
3778 Binder.restoreCallingIdentity(origId);
3779 }
3780 }
3781 }
3782
3783 /**
3784 * Moves the top activity in the input stackId to the pinned stack.
3785 *
3786 * @param stackId Id of stack to move the top activity to pinned stack.
3787 * @param bounds Bounds to use for pinned stack.
3788 *
3789 * @return True if the top activity of the input stack was successfully moved to the pinned
3790 * stack.
3791 */
3792 @Override
3793 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003794 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003795 "moveTopActivityToPinnedStack()");
3796 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003797 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003798 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3799 + "Device doesn't support picture-in-picture mode");
3800 }
3801
3802 long ident = Binder.clearCallingIdentity();
3803 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003804 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003805 } finally {
3806 Binder.restoreCallingIdentity(ident);
3807 }
3808 }
3809 }
3810
3811 @Override
3812 public boolean isInMultiWindowMode(IBinder token) {
3813 final long origId = Binder.clearCallingIdentity();
3814 try {
3815 synchronized (mGlobalLock) {
3816 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3817 if (r == null) {
3818 return false;
3819 }
3820 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3821 return r.inMultiWindowMode();
3822 }
3823 } finally {
3824 Binder.restoreCallingIdentity(origId);
3825 }
3826 }
3827
3828 @Override
3829 public boolean isInPictureInPictureMode(IBinder token) {
3830 final long origId = Binder.clearCallingIdentity();
3831 try {
3832 synchronized (mGlobalLock) {
3833 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3834 }
3835 } finally {
3836 Binder.restoreCallingIdentity(origId);
3837 }
3838 }
3839
3840 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003841 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3842 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 return false;
3844 }
3845
3846 // If we are animating to fullscreen then we have already dispatched the PIP mode
3847 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003848 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3849 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 }
3851
3852 @Override
3853 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3854 final long origId = Binder.clearCallingIdentity();
3855 try {
3856 synchronized (mGlobalLock) {
3857 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3858 "enterPictureInPictureMode", token, params);
3859
3860 // If the activity is already in picture in picture mode, then just return early
3861 if (isInPictureInPictureMode(r)) {
3862 return true;
3863 }
3864
3865 // Activity supports picture-in-picture, now check that we can enter PiP at this
3866 // point, if it is
3867 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3868 false /* beforeStopping */)) {
3869 return false;
3870 }
3871
3872 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003873 synchronized (mGlobalLock) {
3874 // Only update the saved args from the args that are set
3875 r.pictureInPictureArgs.copyOnlySet(params);
3876 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3877 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3878 // Adjust the source bounds by the insets for the transition down
3879 final Rect sourceBounds = new Rect(
3880 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003881 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003882 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003883 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003884 stack.setPictureInPictureAspectRatio(aspectRatio);
3885 stack.setPictureInPictureActions(actions);
3886 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3887 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3888 logPictureInPictureArgs(params);
3889 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003890 };
3891
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003892 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 // If the keyguard is showing or occluded, then try and dismiss it before
3894 // entering picture-in-picture (this will prompt the user to authenticate if the
3895 // device is currently locked).
3896 dismissKeyguard(token, new KeyguardDismissCallback() {
3897 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003898 public void onDismissSucceeded() {
3899 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003900 }
3901 }, null /* message */);
3902 } else {
3903 // Enter picture in picture immediately otherwise
3904 enterPipRunnable.run();
3905 }
3906 return true;
3907 }
3908 } finally {
3909 Binder.restoreCallingIdentity(origId);
3910 }
3911 }
3912
3913 @Override
3914 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3915 final long origId = Binder.clearCallingIdentity();
3916 try {
3917 synchronized (mGlobalLock) {
3918 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3919 "setPictureInPictureParams", token, params);
3920
3921 // Only update the saved args from the args that are set
3922 r.pictureInPictureArgs.copyOnlySet(params);
3923 if (r.inPinnedWindowingMode()) {
3924 // If the activity is already in picture-in-picture, update the pinned stack now
3925 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3926 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003927 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003928 if (!stack.isAnimatingBoundsToFullscreen()) {
3929 stack.setPictureInPictureAspectRatio(
3930 r.pictureInPictureArgs.getAspectRatio());
3931 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3932 }
3933 }
3934 logPictureInPictureArgs(params);
3935 }
3936 } finally {
3937 Binder.restoreCallingIdentity(origId);
3938 }
3939 }
3940
3941 @Override
3942 public int getMaxNumPictureInPictureActions(IBinder token) {
3943 // Currently, this is a static constant, but later, we may change this to be dependent on
3944 // the context of the activity
3945 return 3;
3946 }
3947
3948 private void logPictureInPictureArgs(PictureInPictureParams params) {
3949 if (params.hasSetActions()) {
3950 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3951 params.getActions().size());
3952 }
3953 if (params.hasSetAspectRatio()) {
3954 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3955 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3956 MetricsLogger.action(lm);
3957 }
3958 }
3959
3960 /**
3961 * Checks the state of the system and the activity associated with the given {@param token} to
3962 * verify that picture-in-picture is supported for that activity.
3963 *
3964 * @return the activity record for the given {@param token} if all the checks pass.
3965 */
3966 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3967 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003968 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003969 throw new IllegalStateException(caller
3970 + ": Device doesn't support picture-in-picture mode.");
3971 }
3972
3973 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3974 if (r == null) {
3975 throw new IllegalStateException(caller
3976 + ": Can't find activity for token=" + token);
3977 }
3978
3979 if (!r.supportsPictureInPicture()) {
3980 throw new IllegalStateException(caller
3981 + ": Current activity does not support picture-in-picture.");
3982 }
3983
3984 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003985 && !mWindowManager.isValidPictureInPictureAspectRatio(
3986 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003987 final float minAspectRatio = mContext.getResources().getFloat(
3988 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3989 final float maxAspectRatio = mContext.getResources().getFloat(
3990 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3991 throw new IllegalArgumentException(String.format(caller
3992 + ": Aspect ratio is too extreme (must be between %f and %f).",
3993 minAspectRatio, maxAspectRatio));
3994 }
3995
3996 // Truncate the number of actions if necessary
3997 params.truncateActions(getMaxNumPictureInPictureActions(token));
3998
3999 return r;
4000 }
4001
4002 @Override
4003 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004004 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 synchronized (mGlobalLock) {
4006 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4007 if (r == null) {
4008 throw new IllegalArgumentException("Activity does not exist; token="
4009 + activityToken);
4010 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004011 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 }
4013 }
4014
4015 @Override
4016 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4017 Rect tempDockedTaskInsetBounds,
4018 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004019 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004020 long ident = Binder.clearCallingIdentity();
4021 try {
4022 synchronized (mGlobalLock) {
4023 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4024 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4025 PRESERVE_WINDOWS);
4026 }
4027 } finally {
4028 Binder.restoreCallingIdentity(ident);
4029 }
4030 }
4031
4032 @Override
4033 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004034 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004035 final long ident = Binder.clearCallingIdentity();
4036 try {
4037 synchronized (mGlobalLock) {
4038 mStackSupervisor.setSplitScreenResizing(resizing);
4039 }
4040 } finally {
4041 Binder.restoreCallingIdentity(ident);
4042 }
4043 }
4044
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004045 /**
4046 * Check that we have the features required for VR-related API calls, and throw an exception if
4047 * not.
4048 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004049 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004050 if (!mContext.getPackageManager().hasSystemFeature(
4051 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4052 throw new UnsupportedOperationException("VR mode not supported on this device!");
4053 }
4054 }
4055
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004056 @Override
4057 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004058 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004059
4060 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4061
4062 ActivityRecord r;
4063 synchronized (mGlobalLock) {
4064 r = ActivityRecord.isInStackLocked(token);
4065 }
4066
4067 if (r == null) {
4068 throw new IllegalArgumentException();
4069 }
4070
4071 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004072 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 VrManagerInternal.NO_ERROR) {
4074 return err;
4075 }
4076
4077 // Clear the binder calling uid since this path may call moveToTask().
4078 final long callingId = Binder.clearCallingIdentity();
4079 try {
4080 synchronized (mGlobalLock) {
4081 r.requestedVrComponent = (enabled) ? packageName : null;
4082
4083 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004084 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004085 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 }
4087 return 0;
4088 }
4089 } finally {
4090 Binder.restoreCallingIdentity(callingId);
4091 }
4092 }
4093
4094 @Override
4095 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4096 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4097 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004098 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004099 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4100 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4101 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004102 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004103 || activity.voiceSession != null) {
4104 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4105 return;
4106 }
4107 if (activity.pendingVoiceInteractionStart) {
4108 Slog.w(TAG, "Pending start of voice interaction already.");
4109 return;
4110 }
4111 activity.pendingVoiceInteractionStart = true;
4112 }
4113 LocalServices.getService(VoiceInteractionManagerInternal.class)
4114 .startLocalVoiceInteraction(callingActivity, options);
4115 }
4116
4117 @Override
4118 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4119 LocalServices.getService(VoiceInteractionManagerInternal.class)
4120 .stopLocalVoiceInteraction(callingActivity);
4121 }
4122
4123 @Override
4124 public boolean supportsLocalVoiceInteraction() {
4125 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4126 .supportsLocalVoiceInteraction();
4127 }
4128
4129 /** Notifies all listeners when the pinned stack animation starts. */
4130 @Override
4131 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004132 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004133 }
4134
4135 /** Notifies all listeners when the pinned stack animation ends. */
4136 @Override
4137 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004138 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004139 }
4140
4141 @Override
4142 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004143 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 final long ident = Binder.clearCallingIdentity();
4145 try {
4146 synchronized (mGlobalLock) {
4147 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4148 }
4149 } finally {
4150 Binder.restoreCallingIdentity(ident);
4151 }
4152 }
4153
4154 @Override
4155 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004156 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157
4158 synchronized (mGlobalLock) {
4159 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004160 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004161 // Call might come when display is not yet added or has already been removed.
4162 if (DEBUG_CONFIGURATION) {
4163 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4164 + displayId);
4165 }
4166 return false;
4167 }
4168
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004169 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004170 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004171 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004172 }
4173
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004174 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004175 final Message msg = PooledLambda.obtainMessage(
4176 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4177 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 }
4179
4180 final long origId = Binder.clearCallingIdentity();
4181 try {
4182 if (values != null) {
4183 Settings.System.clearConfiguration(values);
4184 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004185 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004186 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4187 return mTmpUpdateConfigurationResult.changes != 0;
4188 } finally {
4189 Binder.restoreCallingIdentity(origId);
4190 }
4191 }
4192 }
4193
4194 @Override
4195 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004196 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004197
4198 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004199 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004201 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202 }
4203
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004204 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004205 final Message msg = PooledLambda.obtainMessage(
4206 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4207 DEFAULT_DISPLAY);
4208 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004209 }
4210
4211 final long origId = Binder.clearCallingIdentity();
4212 try {
4213 if (values != null) {
4214 Settings.System.clearConfiguration(values);
4215 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004216 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004217 UserHandle.USER_NULL, false /* deferResume */,
4218 mTmpUpdateConfigurationResult);
4219 return mTmpUpdateConfigurationResult.changes != 0;
4220 } finally {
4221 Binder.restoreCallingIdentity(origId);
4222 }
4223 }
4224 }
4225
4226 @Override
4227 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4228 CharSequence message) {
4229 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004230 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004231 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4232 }
4233 final long callingId = Binder.clearCallingIdentity();
4234 try {
4235 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004236 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004237 }
4238 } finally {
4239 Binder.restoreCallingIdentity(callingId);
4240 }
4241 }
4242
4243 @Override
4244 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004245 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004246 "cancelTaskWindowTransition()");
4247 final long ident = Binder.clearCallingIdentity();
4248 try {
4249 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004250 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004251 MATCH_TASK_IN_STACKS_ONLY);
4252 if (task == null) {
4253 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4254 return;
4255 }
4256 task.cancelWindowTransition();
4257 }
4258 } finally {
4259 Binder.restoreCallingIdentity(ident);
4260 }
4261 }
4262
4263 @Override
4264 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004265 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004266 final long ident = Binder.clearCallingIdentity();
4267 try {
4268 final TaskRecord task;
4269 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004270 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004271 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4272 if (task == null) {
4273 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4274 return null;
4275 }
4276 }
4277 // Don't call this while holding the lock as this operation might hit the disk.
4278 return task.getSnapshot(reducedResolution);
4279 } finally {
4280 Binder.restoreCallingIdentity(ident);
4281 }
4282 }
4283
4284 @Override
4285 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4286 synchronized (mGlobalLock) {
4287 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4288 if (r == null) {
4289 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4290 + token);
4291 return;
4292 }
4293 final long origId = Binder.clearCallingIdentity();
4294 try {
4295 r.setDisablePreviewScreenshots(disable);
4296 } finally {
4297 Binder.restoreCallingIdentity(origId);
4298 }
4299 }
4300 }
4301
4302 /** Return the user id of the last resumed activity. */
4303 @Override
4304 public @UserIdInt
4305 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004306 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004307 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4308 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004309 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004312 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004313 }
4314 }
4315
4316 @Override
4317 public void updateLockTaskFeatures(int userId, int flags) {
4318 final int callingUid = Binder.getCallingUid();
4319 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004320 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004321 "updateLockTaskFeatures()");
4322 }
4323 synchronized (mGlobalLock) {
4324 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4325 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004326 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004327 }
4328 }
4329
4330 @Override
4331 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4332 synchronized (mGlobalLock) {
4333 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4334 if (r == null) {
4335 return;
4336 }
4337 final long origId = Binder.clearCallingIdentity();
4338 try {
4339 r.setShowWhenLocked(showWhenLocked);
4340 } finally {
4341 Binder.restoreCallingIdentity(origId);
4342 }
4343 }
4344 }
4345
4346 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004347 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4348 synchronized (mGlobalLock) {
4349 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4350 if (r == null) {
4351 return;
4352 }
4353 final long origId = Binder.clearCallingIdentity();
4354 try {
4355 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4356 } finally {
4357 Binder.restoreCallingIdentity(origId);
4358 }
4359 }
4360 }
4361
4362 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004363 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4364 synchronized (mGlobalLock) {
4365 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4366 if (r == null) {
4367 return;
4368 }
4369 final long origId = Binder.clearCallingIdentity();
4370 try {
4371 r.setTurnScreenOn(turnScreenOn);
4372 } finally {
4373 Binder.restoreCallingIdentity(origId);
4374 }
4375 }
4376 }
4377
4378 @Override
4379 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004380 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004381 "registerRemoteAnimations");
4382 definition.setCallingPid(Binder.getCallingPid());
4383 synchronized (mGlobalLock) {
4384 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4385 if (r == null) {
4386 return;
4387 }
4388 final long origId = Binder.clearCallingIdentity();
4389 try {
4390 r.registerRemoteAnimations(definition);
4391 } finally {
4392 Binder.restoreCallingIdentity(origId);
4393 }
4394 }
4395 }
4396
4397 @Override
4398 public void registerRemoteAnimationForNextActivityStart(String packageName,
4399 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004400 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004401 "registerRemoteAnimationForNextActivityStart");
4402 adapter.setCallingPid(Binder.getCallingPid());
4403 synchronized (mGlobalLock) {
4404 final long origId = Binder.clearCallingIdentity();
4405 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004406 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004407 packageName, adapter);
4408 } finally {
4409 Binder.restoreCallingIdentity(origId);
4410 }
4411 }
4412 }
4413
Evan Rosky966759f2019-01-15 10:33:58 -08004414 @Override
4415 public void registerRemoteAnimationsForDisplay(int displayId,
4416 RemoteAnimationDefinition definition) {
4417 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4418 "registerRemoteAnimations");
4419 definition.setCallingPid(Binder.getCallingPid());
4420 synchronized (mGlobalLock) {
4421 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4422 if (display == null) {
4423 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4424 return;
4425 }
4426 final long origId = Binder.clearCallingIdentity();
4427 try {
4428 display.mDisplayContent.registerRemoteAnimations(definition);
4429 } finally {
4430 Binder.restoreCallingIdentity(origId);
4431 }
4432 }
4433 }
4434
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004435 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4436 @Override
4437 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4438 synchronized (mGlobalLock) {
4439 final long origId = Binder.clearCallingIdentity();
4440 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004441 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004442 } finally {
4443 Binder.restoreCallingIdentity(origId);
4444 }
4445 }
4446 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004447
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004448 @Override
4449 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004450 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004451 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004452 final int pid = Binder.getCallingPid();
4453 final WindowProcessController wpc = mPidMap.get(pid);
4454 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004455 }
4456 }
4457
4458 @Override
4459 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004460 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004461 != PERMISSION_GRANTED) {
4462 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4463 + Binder.getCallingPid()
4464 + ", uid=" + Binder.getCallingUid()
4465 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4466 Slog.w(TAG, msg);
4467 throw new SecurityException(msg);
4468 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004469 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004470 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004471 final int pid = Binder.getCallingPid();
4472 final WindowProcessController proc = mPidMap.get(pid);
4473 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004474 }
4475 }
4476
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004477 @Override
4478 public void stopAppSwitches() {
4479 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4480 synchronized (mGlobalLock) {
4481 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4482 mDidAppSwitch = false;
4483 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4484 }
4485 }
4486
4487 @Override
4488 public void resumeAppSwitches() {
4489 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4490 synchronized (mGlobalLock) {
4491 // Note that we don't execute any pending app switches... we will
4492 // let those wait until either the timeout, or the next start
4493 // activity request.
4494 mAppSwitchesAllowedTime = 0;
4495 }
4496 }
4497
4498 void onStartActivitySetDidAppSwitch() {
4499 if (mDidAppSwitch) {
4500 // This is the second allowed switch since we stopped switches, so now just generally
4501 // allow switches. Use case:
4502 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4503 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4504 // anyone to switch again).
4505 mAppSwitchesAllowedTime = 0;
4506 } else {
4507 mDidAppSwitch = true;
4508 }
4509 }
4510
4511 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004512 boolean shouldDisableNonVrUiLocked() {
4513 return mVrController.shouldDisableNonVrUiLocked();
4514 }
4515
Wale Ogunwale53783742018-09-16 10:21:51 -07004516 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004517 // VR apps are expected to run in a main display. If an app is turning on VR for
4518 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4519 // fullscreen stack before enabling VR Mode.
4520 // TODO: The goal of this code is to keep the VR app on the main display. When the
4521 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4522 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4523 // option would be a better choice here.
4524 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4525 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4526 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004527 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004528 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004529 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004530 }
4531 mH.post(() -> {
4532 if (!mVrController.onVrModeChanged(r)) {
4533 return;
4534 }
4535 synchronized (mGlobalLock) {
4536 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4537 mWindowManager.disableNonVrUi(disableNonVrUi);
4538 if (disableNonVrUi) {
4539 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4540 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004541 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004542 }
4543 }
4544 });
4545 }
4546
Wale Ogunwale53783742018-09-16 10:21:51 -07004547 @Override
4548 public int getPackageScreenCompatMode(String packageName) {
4549 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4550 synchronized (mGlobalLock) {
4551 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4552 }
4553 }
4554
4555 @Override
4556 public void setPackageScreenCompatMode(String packageName, int mode) {
4557 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4558 "setPackageScreenCompatMode");
4559 synchronized (mGlobalLock) {
4560 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4561 }
4562 }
4563
4564 @Override
4565 public boolean getPackageAskScreenCompat(String packageName) {
4566 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4567 synchronized (mGlobalLock) {
4568 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4569 }
4570 }
4571
4572 @Override
4573 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4574 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4575 "setPackageAskScreenCompat");
4576 synchronized (mGlobalLock) {
4577 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4578 }
4579 }
4580
Wale Ogunwale64258362018-10-16 15:13:37 -07004581 public static String relaunchReasonToString(int relaunchReason) {
4582 switch (relaunchReason) {
4583 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4584 return "window_resize";
4585 case RELAUNCH_REASON_FREE_RESIZE:
4586 return "free_resize";
4587 default:
4588 return null;
4589 }
4590 }
4591
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004592 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004593 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004594 }
4595
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004596 /** Pokes the task persister. */
4597 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4598 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4599 }
4600
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004601 boolean isKeyguardLocked() {
4602 return mKeyguardController.isKeyguardLocked();
4603 }
4604
Garfield Tan01548632018-11-27 10:15:48 -08004605 /**
4606 * Clears launch params for the given package.
4607 * @param packageNames the names of the packages of which the launch params are to be cleared
4608 */
4609 @Override
4610 public void clearLaunchParamsForPackages(List<String> packageNames) {
4611 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4612 "clearLaunchParamsForPackages");
4613 synchronized (mGlobalLock) {
4614 for (int i = 0; i < packageNames.size(); ++i) {
4615 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4616 }
4617 }
4618 }
4619
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004620 /**
4621 * Makes the display with the given id a single task instance display. I.e the display can only
4622 * contain one task.
4623 */
4624 @Override
4625 public void setDisplayToSingleTaskInstance(int displayId) {
4626 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4627 "setDisplayToSingleTaskInstance");
4628 final long origId = Binder.clearCallingIdentity();
4629 try {
4630 final ActivityDisplay display =
4631 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4632 if (display != null) {
4633 display.setDisplayToSingleTaskInstance();
4634 }
4635 } finally {
4636 Binder.restoreCallingIdentity(origId);
4637 }
4638 }
4639
Wale Ogunwale31913b52018-10-13 08:29:31 -07004640 void dumpLastANRLocked(PrintWriter pw) {
4641 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4642 if (mLastANRState == null) {
4643 pw.println(" <no ANR has occurred since boot>");
4644 } else {
4645 pw.println(mLastANRState);
4646 }
4647 }
4648
4649 void dumpLastANRTracesLocked(PrintWriter pw) {
4650 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4651
4652 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4653 if (ArrayUtils.isEmpty(files)) {
4654 pw.println(" <no ANR has occurred since boot>");
4655 return;
4656 }
4657 // Find the latest file.
4658 File latest = null;
4659 for (File f : files) {
4660 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4661 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004662 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004663 }
4664 pw.print("File: ");
4665 pw.print(latest.getName());
4666 pw.println();
4667 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4668 String line;
4669 while ((line = in.readLine()) != null) {
4670 pw.println(line);
4671 }
4672 } catch (IOException e) {
4673 pw.print("Unable to read: ");
4674 pw.print(e);
4675 pw.println();
4676 }
4677 }
4678
4679 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4680 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4681 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4682 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4683 }
4684
4685 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4686 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4687 pw.println(header);
4688
Wale Ogunwaled32da472018-11-16 07:19:28 -08004689 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004690 dumpPackage);
4691 boolean needSep = printedAnything;
4692
4693 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004694 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004695 " ResumedActivity: ");
4696 if (printed) {
4697 printedAnything = true;
4698 needSep = false;
4699 }
4700
4701 if (dumpPackage == null) {
4702 if (needSep) {
4703 pw.println();
4704 }
4705 printedAnything = true;
4706 mStackSupervisor.dump(pw, " ");
4707 }
4708
4709 if (!printedAnything) {
4710 pw.println(" (nothing)");
4711 }
4712 }
4713
4714 void dumpActivityContainersLocked(PrintWriter pw) {
4715 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004716 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004717 pw.println(" ");
4718 }
4719
4720 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4721 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4722 getActivityStartController().dump(pw, "", dumpPackage);
4723 }
4724
4725 /**
4726 * There are three things that cmd can be:
4727 * - a flattened component name that matches an existing activity
4728 * - the cmd arg isn't the flattened component name of an existing activity:
4729 * dump all activity whose component contains the cmd as a substring
4730 * - A hex number of the ActivityRecord object instance.
4731 *
4732 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4733 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4734 */
4735 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4736 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4737 ArrayList<ActivityRecord> activities;
4738
4739 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004740 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004741 dumpFocusedStackOnly);
4742 }
4743
4744 if (activities.size() <= 0) {
4745 return false;
4746 }
4747
4748 String[] newArgs = new String[args.length - opti];
4749 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4750
4751 TaskRecord lastTask = null;
4752 boolean needSep = false;
4753 for (int i = activities.size() - 1; i >= 0; i--) {
4754 ActivityRecord r = activities.get(i);
4755 if (needSep) {
4756 pw.println();
4757 }
4758 needSep = true;
4759 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004760 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004761 if (lastTask != task) {
4762 lastTask = task;
4763 pw.print("TASK "); pw.print(lastTask.affinity);
4764 pw.print(" id="); pw.print(lastTask.taskId);
4765 pw.print(" userId="); pw.println(lastTask.userId);
4766 if (dumpAll) {
4767 lastTask.dump(pw, " ");
4768 }
4769 }
4770 }
4771 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4772 }
4773 return true;
4774 }
4775
4776 /**
4777 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4778 * there is a thread associated with the activity.
4779 */
4780 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4781 final ActivityRecord r, String[] args, boolean dumpAll) {
4782 String innerPrefix = prefix + " ";
4783 synchronized (mGlobalLock) {
4784 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4785 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4786 pw.print(" pid=");
4787 if (r.hasProcess()) pw.println(r.app.getPid());
4788 else pw.println("(not running)");
4789 if (dumpAll) {
4790 r.dump(pw, innerPrefix);
4791 }
4792 }
4793 if (r.attachedToProcess()) {
4794 // flush anything that is already in the PrintWriter since the thread is going
4795 // to write to the file descriptor directly
4796 pw.flush();
4797 try {
4798 TransferPipe tp = new TransferPipe();
4799 try {
4800 r.app.getThread().dumpActivity(tp.getWriteFd(),
4801 r.appToken, innerPrefix, args);
4802 tp.go(fd);
4803 } finally {
4804 tp.kill();
4805 }
4806 } catch (IOException e) {
4807 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4808 } catch (RemoteException e) {
4809 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4810 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004811 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004812 }
4813
sanryhuang498e77e2018-12-06 14:57:01 +08004814 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4815 boolean testPssMode) {
4816 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4817 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4818 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004819 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004820 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4821 st.toString());
4822 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004823 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4824 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4825 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004826 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4827 testPssMode);
4828 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004829 }
4830
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004831 int getCurrentUserId() {
4832 return mAmInternal.getCurrentUserId();
4833 }
4834
4835 private void enforceNotIsolatedCaller(String caller) {
4836 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4837 throw new SecurityException("Isolated process not allowed to call " + caller);
4838 }
4839 }
4840
Wale Ogunwalef6733932018-06-27 05:14:34 -07004841 public Configuration getConfiguration() {
4842 Configuration ci;
4843 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004844 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004845 ci.userSetLocale = false;
4846 }
4847 return ci;
4848 }
4849
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004850 /**
4851 * Current global configuration information. Contains general settings for the entire system,
4852 * also corresponds to the merged configuration of the default display.
4853 */
4854 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004855 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004856 }
4857
4858 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4859 boolean initLocale) {
4860 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4861 }
4862
4863 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4864 boolean initLocale, boolean deferResume) {
4865 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4866 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4867 UserHandle.USER_NULL, deferResume);
4868 }
4869
Wale Ogunwale59507092018-10-29 09:00:30 -07004870 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004871 final long origId = Binder.clearCallingIdentity();
4872 try {
4873 synchronized (mGlobalLock) {
4874 updateConfigurationLocked(values, null, false, true, userId,
4875 false /* deferResume */);
4876 }
4877 } finally {
4878 Binder.restoreCallingIdentity(origId);
4879 }
4880 }
4881
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004882 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4883 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4884 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4885 deferResume, null /* result */);
4886 }
4887
4888 /**
4889 * Do either or both things: (1) change the current configuration, and (2)
4890 * make sure the given activity is running with the (now) current
4891 * configuration. Returns true if the activity has been left running, or
4892 * false if <var>starting</var> is being destroyed to match the new
4893 * configuration.
4894 *
4895 * @param userId is only used when persistent parameter is set to true to persist configuration
4896 * for that particular user
4897 */
4898 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4899 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4900 ActivityTaskManagerService.UpdateConfigurationResult result) {
4901 int changes = 0;
4902 boolean kept = true;
4903
4904 if (mWindowManager != null) {
4905 mWindowManager.deferSurfaceLayout();
4906 }
4907 try {
4908 if (values != null) {
4909 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4910 deferResume);
4911 }
4912
4913 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4914 } finally {
4915 if (mWindowManager != null) {
4916 mWindowManager.continueSurfaceLayout();
4917 }
4918 }
4919
4920 if (result != null) {
4921 result.changes = changes;
4922 result.activityRelaunched = !kept;
4923 }
4924 return kept;
4925 }
4926
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004927 /** Update default (global) configuration and notify listeners about changes. */
4928 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4929 boolean persistent, int userId, boolean deferResume) {
4930 mTempConfig.setTo(getGlobalConfiguration());
4931 final int changes = mTempConfig.updateFrom(values);
4932 if (changes == 0) {
4933 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4934 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4935 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4936 // (even if there are no actual changes) to unfreeze the window.
4937 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4938 return 0;
4939 }
4940
4941 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4942 "Updating global configuration to: " + values);
4943
4944 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4945 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4946 values.colorMode,
4947 values.densityDpi,
4948 values.fontScale,
4949 values.hardKeyboardHidden,
4950 values.keyboard,
4951 values.keyboardHidden,
4952 values.mcc,
4953 values.mnc,
4954 values.navigation,
4955 values.navigationHidden,
4956 values.orientation,
4957 values.screenHeightDp,
4958 values.screenLayout,
4959 values.screenWidthDp,
4960 values.smallestScreenWidthDp,
4961 values.touchscreen,
4962 values.uiMode);
4963
4964
4965 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4966 final LocaleList locales = values.getLocales();
4967 int bestLocaleIndex = 0;
4968 if (locales.size() > 1) {
4969 if (mSupportedSystemLocales == null) {
4970 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4971 }
4972 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4973 }
4974 SystemProperties.set("persist.sys.locale",
4975 locales.get(bestLocaleIndex).toLanguageTag());
4976 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004977
4978 final Message m = PooledLambda.obtainMessage(
4979 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4980 locales.get(bestLocaleIndex));
4981 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004982 }
4983
Yunfan Chen75157d72018-07-27 14:47:21 +09004984 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004985
4986 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004987 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004988
4989 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4990 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004991 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004992
4993 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004994 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004995
4996 AttributeCache ac = AttributeCache.instance();
4997 if (ac != null) {
4998 ac.updateConfiguration(mTempConfig);
4999 }
5000
5001 // Make sure all resources in our process are updated right now, so that anyone who is going
5002 // to retrieve resource values after we return will be sure to get the new ones. This is
5003 // especially important during boot, where the first config change needs to guarantee all
5004 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005005 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005006
5007 // We need another copy of global config because we're scheduling some calls instead of
5008 // running them in place. We need to be sure that object we send will be handled unchanged.
5009 final Configuration configCopy = new Configuration(mTempConfig);
5010 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005011 final Message msg = PooledLambda.obtainMessage(
5012 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5013 this, userId, configCopy);
5014 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005015 }
5016
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005017 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005018 final int pid = mPidMap.keyAt(i);
5019 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005020 if (DEBUG_CONFIGURATION) {
5021 Slog.v(TAG_CONFIGURATION, "Update process config of "
5022 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005023 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005024 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005025 }
5026
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005027 final Message msg = PooledLambda.obtainMessage(
5028 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5029 mAmInternal, changes, initLocale);
5030 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005031
5032 // Override configuration of the default display duplicates global config, so we need to
5033 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005034 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005035 DEFAULT_DISPLAY);
5036
5037 return changes;
5038 }
5039
5040 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5041 boolean deferResume, int displayId) {
5042 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5043 displayId, null /* result */);
5044 }
5045
5046 /**
5047 * Updates override configuration specific for the selected display. If no config is provided,
5048 * new one will be computed in WM based on current display info.
5049 */
5050 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5051 ActivityRecord starting, boolean deferResume, int displayId,
5052 ActivityTaskManagerService.UpdateConfigurationResult result) {
5053 int changes = 0;
5054 boolean kept = true;
5055
5056 if (mWindowManager != null) {
5057 mWindowManager.deferSurfaceLayout();
5058 }
5059 try {
5060 if (values != null) {
5061 if (displayId == DEFAULT_DISPLAY) {
5062 // Override configuration of the default display duplicates global config, so
5063 // we're calling global config update instead for default display. It will also
5064 // apply the correct override config.
5065 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5066 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5067 } else {
5068 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5069 }
5070 }
5071
5072 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5073 } finally {
5074 if (mWindowManager != null) {
5075 mWindowManager.continueSurfaceLayout();
5076 }
5077 }
5078
5079 if (result != null) {
5080 result.changes = changes;
5081 result.activityRelaunched = !kept;
5082 }
5083 return kept;
5084 }
5085
5086 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5087 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005088 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005089 final int changes = mTempConfig.updateFrom(values);
5090 if (changes != 0) {
5091 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5092 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005093 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005094
5095 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5096 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005097 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005098
Wale Ogunwale5c918702018-10-18 11:06:33 -07005099 // Post message to start process to avoid possible deadlock of calling into AMS with
5100 // the ATMS lock held.
5101 final Message msg = PooledLambda.obtainMessage(
5102 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5103 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5104 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005105 }
5106 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005107 return changes;
5108 }
5109
Wale Ogunwalef6733932018-06-27 05:14:34 -07005110 private void updateEventDispatchingLocked(boolean booted) {
5111 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5112 }
5113
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005114 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5115 final ContentResolver resolver = mContext.getContentResolver();
5116 Settings.System.putConfigurationForUser(resolver, config, userId);
5117 }
5118
5119 private void sendLocaleToMountDaemonMsg(Locale l) {
5120 try {
5121 IBinder service = ServiceManager.getService("mount");
5122 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5123 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5124 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5125 } catch (RemoteException e) {
5126 Log.e(TAG, "Error storing locale for decryption UI", e);
5127 }
5128 }
5129
Alison Cichowlas3e340502018-08-07 17:15:01 -04005130 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5131 mStartActivitySources.remove(permissionToken);
5132 mExpiredStartAsCallerTokens.add(permissionToken);
5133 }
5134
5135 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5136 mExpiredStartAsCallerTokens.remove(permissionToken);
5137 }
5138
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005139 boolean isActivityStartsLoggingEnabled() {
5140 return mAmInternal.isActivityStartsLoggingEnabled();
5141 }
5142
Michal Karpinski8596ded2018-11-14 14:43:48 +00005143 boolean isBackgroundActivityStartsEnabled() {
5144 return mAmInternal.isBackgroundActivityStartsEnabled();
5145 }
5146
Wale Ogunwalef6733932018-06-27 05:14:34 -07005147 void enableScreenAfterBoot(boolean booted) {
5148 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5149 SystemClock.uptimeMillis());
5150 mWindowManager.enableScreenAfterBoot();
5151
5152 synchronized (mGlobalLock) {
5153 updateEventDispatchingLocked(booted);
5154 }
5155 }
5156
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005157 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5158 if (r == null || !r.hasProcess()) {
5159 return KEY_DISPATCHING_TIMEOUT_MS;
5160 }
5161 return getInputDispatchingTimeoutLocked(r.app);
5162 }
5163
5164 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005165 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005166 }
5167
Wale Ogunwalef6733932018-06-27 05:14:34 -07005168 /**
5169 * Decide based on the configuration whether we should show the ANR,
5170 * crash, etc dialogs. The idea is that if there is no affordance to
5171 * press the on-screen buttons, or the user experience would be more
5172 * greatly impacted than the crash itself, we shouldn't show the dialog.
5173 *
5174 * A thought: SystemUI might also want to get told about this, the Power
5175 * dialog / global actions also might want different behaviors.
5176 */
5177 private void updateShouldShowDialogsLocked(Configuration config) {
5178 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5179 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5180 && config.navigation == Configuration.NAVIGATION_NONAV);
5181 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5182 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5183 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5184 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5185 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5186 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5187 HIDE_ERROR_DIALOGS, 0) != 0;
5188 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5189 }
5190
5191 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5192 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5193 FONT_SCALE, 1.0f, userId);
5194
5195 synchronized (this) {
5196 if (getGlobalConfiguration().fontScale == scaleFactor) {
5197 return;
5198 }
5199
5200 final Configuration configuration
5201 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5202 configuration.fontScale = scaleFactor;
5203 updatePersistentConfiguration(configuration, userId);
5204 }
5205 }
5206
5207 // Actually is sleeping or shutting down or whatever else in the future
5208 // is an inactive state.
5209 boolean isSleepingOrShuttingDownLocked() {
5210 return isSleepingLocked() || mShuttingDown;
5211 }
5212
5213 boolean isSleepingLocked() {
5214 return mSleeping;
5215 }
5216
Riddle Hsu16567132018-08-16 21:37:47 +08005217 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005218 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005219 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005220 if (task.isActivityTypeStandard()) {
5221 if (mCurAppTimeTracker != r.appTimeTracker) {
5222 // We are switching app tracking. Complete the current one.
5223 if (mCurAppTimeTracker != null) {
5224 mCurAppTimeTracker.stop();
5225 mH.obtainMessage(
5226 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005227 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005228 mCurAppTimeTracker = null;
5229 }
5230 if (r.appTimeTracker != null) {
5231 mCurAppTimeTracker = r.appTimeTracker;
5232 startTimeTrackingFocusedActivityLocked();
5233 }
5234 } else {
5235 startTimeTrackingFocusedActivityLocked();
5236 }
5237 } else {
5238 r.appTimeTracker = null;
5239 }
5240 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5241 // TODO: Probably not, because we don't want to resume voice on switching
5242 // back to this activity
5243 if (task.voiceInteractor != null) {
5244 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5245 } else {
5246 finishRunningVoiceLocked();
5247
5248 if (mLastResumedActivity != null) {
5249 final IVoiceInteractionSession session;
5250
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005251 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005252 if (lastResumedActivityTask != null
5253 && lastResumedActivityTask.voiceSession != null) {
5254 session = lastResumedActivityTask.voiceSession;
5255 } else {
5256 session = mLastResumedActivity.voiceSession;
5257 }
5258
5259 if (session != null) {
5260 // We had been in a voice interaction session, but now focused has
5261 // move to something different. Just finish the session, we can't
5262 // return to it and retain the proper state and synchronization with
5263 // the voice interaction service.
5264 finishVoiceTask(session);
5265 }
5266 }
5267 }
5268
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005269 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5270 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005271 }
5272 updateResumedAppTrace(r);
5273 mLastResumedActivity = r;
5274
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005275 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005276
5277 applyUpdateLockStateLocked(r);
5278 applyUpdateVrModeLocked(r);
5279
5280 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005281 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005282 r == null ? "NULL" : r.shortComponentName,
5283 reason);
5284 }
5285
5286 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5287 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005288 final ActivityTaskManagerInternal.SleepToken token =
5289 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005290 updateSleepIfNeededLocked();
5291 return token;
5292 }
5293 }
5294
5295 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005296 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 final boolean wasSleeping = mSleeping;
5298 boolean updateOomAdj = false;
5299
5300 if (!shouldSleep) {
5301 // If wasSleeping is true, we need to wake up activity manager state from when
5302 // we started sleeping. In either case, we need to apply the sleep tokens, which
5303 // will wake up stacks or put them to sleep as appropriate.
5304 if (wasSleeping) {
5305 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005306 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5307 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005308 startTimeTrackingFocusedActivityLocked();
5309 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5310 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5311 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005312 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005313 if (wasSleeping) {
5314 updateOomAdj = true;
5315 }
5316 } else if (!mSleeping && shouldSleep) {
5317 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005318 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5319 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005320 if (mCurAppTimeTracker != null) {
5321 mCurAppTimeTracker.stop();
5322 }
5323 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5324 mStackSupervisor.goingToSleepLocked();
5325 updateResumedAppTrace(null /* resumed */);
5326 updateOomAdj = true;
5327 }
5328 if (updateOomAdj) {
5329 mH.post(mAmInternal::updateOomAdj);
5330 }
5331 }
5332
5333 void updateOomAdj() {
5334 mH.post(mAmInternal::updateOomAdj);
5335 }
5336
Wale Ogunwale53783742018-09-16 10:21:51 -07005337 void updateCpuStats() {
5338 mH.post(mAmInternal::updateCpuStats);
5339 }
5340
Hui Yu03d12402018-12-06 18:00:37 -08005341 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5342 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005343 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5344 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005345 mH.sendMessage(m);
5346 }
5347
Hui Yu03d12402018-12-06 18:00:37 -08005348 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005349 ComponentName taskRoot = null;
5350 final TaskRecord task = activity.getTaskRecord();
5351 if (task != null) {
5352 final ActivityRecord rootActivity = task.getRootActivity();
5353 if (rootActivity != null) {
5354 taskRoot = rootActivity.mActivityComponent;
5355 }
5356 }
5357
Hui Yu03d12402018-12-06 18:00:37 -08005358 final Message m = PooledLambda.obtainMessage(
5359 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005360 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005361 mH.sendMessage(m);
5362 }
5363
Wale Ogunwale53783742018-09-16 10:21:51 -07005364 void setBooting(boolean booting) {
5365 mAmInternal.setBooting(booting);
5366 }
5367
5368 boolean isBooting() {
5369 return mAmInternal.isBooting();
5370 }
5371
5372 void setBooted(boolean booted) {
5373 mAmInternal.setBooted(booted);
5374 }
5375
5376 boolean isBooted() {
5377 return mAmInternal.isBooted();
5378 }
5379
5380 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5381 mH.post(() -> {
5382 if (finishBooting) {
5383 mAmInternal.finishBooting();
5384 }
5385 if (enableScreen) {
5386 mInternal.enableScreenAfterBoot(isBooted());
5387 }
5388 });
5389 }
5390
5391 void setHeavyWeightProcess(ActivityRecord root) {
5392 mHeavyWeightProcess = root.app;
5393 final Message m = PooledLambda.obtainMessage(
5394 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005395 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005396 mH.sendMessage(m);
5397 }
5398
5399 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5400 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5401 return;
5402 }
5403
5404 mHeavyWeightProcess = null;
5405 final Message m = PooledLambda.obtainMessage(
5406 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5407 proc.mUserId);
5408 mH.sendMessage(m);
5409 }
5410
5411 private void cancelHeavyWeightProcessNotification(int userId) {
5412 final INotificationManager inm = NotificationManager.getService();
5413 if (inm == null) {
5414 return;
5415 }
5416 try {
5417 inm.cancelNotificationWithTag("android", null,
5418 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5419 } catch (RuntimeException e) {
5420 Slog.w(TAG, "Error canceling notification for service", e);
5421 } catch (RemoteException e) {
5422 }
5423
5424 }
5425
5426 private void postHeavyWeightProcessNotification(
5427 WindowProcessController proc, Intent intent, int userId) {
5428 if (proc == null) {
5429 return;
5430 }
5431
5432 final INotificationManager inm = NotificationManager.getService();
5433 if (inm == null) {
5434 return;
5435 }
5436
5437 try {
5438 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5439 String text = mContext.getString(R.string.heavy_weight_notification,
5440 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5441 Notification notification =
5442 new Notification.Builder(context,
5443 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5444 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5445 .setWhen(0)
5446 .setOngoing(true)
5447 .setTicker(text)
5448 .setColor(mContext.getColor(
5449 com.android.internal.R.color.system_notification_accent_color))
5450 .setContentTitle(text)
5451 .setContentText(
5452 mContext.getText(R.string.heavy_weight_notification_detail))
5453 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5454 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5455 new UserHandle(userId)))
5456 .build();
5457 try {
5458 inm.enqueueNotificationWithTag("android", "android", null,
5459 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5460 } catch (RuntimeException e) {
5461 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5462 } catch (RemoteException e) {
5463 }
5464 } catch (PackageManager.NameNotFoundException e) {
5465 Slog.w(TAG, "Unable to create context for heavy notification", e);
5466 }
5467
5468 }
5469
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005470 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5471 IBinder token, String resultWho, int requestCode, Intent[] intents,
5472 String[] resolvedTypes, int flags, Bundle bOptions) {
5473
5474 ActivityRecord activity = null;
5475 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5476 activity = ActivityRecord.isInStackLocked(token);
5477 if (activity == null) {
5478 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5479 return null;
5480 }
5481 if (activity.finishing) {
5482 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5483 return null;
5484 }
5485 }
5486
5487 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5488 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5489 bOptions);
5490 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5491 if (noCreate) {
5492 return rec;
5493 }
5494 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5495 if (activity.pendingResults == null) {
5496 activity.pendingResults = new HashSet<>();
5497 }
5498 activity.pendingResults.add(rec.ref);
5499 }
5500 return rec;
5501 }
5502
Andrii Kulian52d255c2018-07-13 11:32:19 -07005503 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005504 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005505 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005506 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5507 mCurAppTimeTracker.start(resumedActivity.packageName);
5508 }
5509 }
5510
5511 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5512 if (mTracedResumedActivity != null) {
5513 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5514 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5515 }
5516 if (resumed != null) {
5517 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5518 constructResumedTraceName(resumed.packageName), 0);
5519 }
5520 mTracedResumedActivity = resumed;
5521 }
5522
5523 private String constructResumedTraceName(String packageName) {
5524 return "focused app: " + packageName;
5525 }
5526
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005527 /** Applies latest configuration and/or visibility updates if needed. */
5528 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5529 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005530 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005531 // mainStack is null during startup.
5532 if (mainStack != null) {
5533 if (changes != 0 && starting == null) {
5534 // If the configuration changed, and the caller is not already
5535 // in the process of starting an activity, then find the top
5536 // activity to check if its configuration needs to change.
5537 starting = mainStack.topRunningActivityLocked();
5538 }
5539
5540 if (starting != null) {
5541 kept = starting.ensureActivityConfiguration(changes,
5542 false /* preserveWindow */);
5543 // And we need to make sure at this point that all other activities
5544 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005545 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005546 !PRESERVE_WINDOWS);
5547 }
5548 }
5549
5550 return kept;
5551 }
5552
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005553 void scheduleAppGcsLocked() {
5554 mH.post(() -> mAmInternal.scheduleAppGcs());
5555 }
5556
Wale Ogunwale53783742018-09-16 10:21:51 -07005557 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5558 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5559 }
5560
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005561 /**
5562 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5563 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5564 * on demand.
5565 */
5566 IPackageManager getPackageManager() {
5567 return AppGlobals.getPackageManager();
5568 }
5569
5570 PackageManagerInternal getPackageManagerInternalLocked() {
5571 if (mPmInternal == null) {
5572 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5573 }
5574 return mPmInternal;
5575 }
5576
Wale Ogunwale008163e2018-07-23 23:11:08 -07005577 AppWarnings getAppWarningsLocked() {
5578 return mAppWarnings;
5579 }
5580
Wale Ogunwale214f3482018-10-04 11:00:47 -07005581 Intent getHomeIntent() {
5582 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5583 intent.setComponent(mTopComponent);
5584 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5585 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5586 intent.addCategory(Intent.CATEGORY_HOME);
5587 }
5588 return intent;
5589 }
5590
Chilun2ef71f72018-11-16 17:57:15 +08005591 /**
5592 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5593 * activities.
5594 *
5595 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5596 * component defined in config_secondaryHomeComponent.
5597 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5598 */
5599 Intent getSecondaryHomeIntent(String preferredPackage) {
5600 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5601 if (preferredPackage == null) {
5602 // Using the component stored in config if no package name.
5603 final String secondaryHomeComponent = mContext.getResources().getString(
5604 com.android.internal.R.string.config_secondaryHomeComponent);
5605 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5606 } else {
5607 intent.setPackage(preferredPackage);
5608 }
5609 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5610 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5611 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5612 }
5613 return intent;
5614 }
5615
Wale Ogunwale214f3482018-10-04 11:00:47 -07005616 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5617 if (info == null) return null;
5618 ApplicationInfo newInfo = new ApplicationInfo(info);
5619 newInfo.initForUser(userId);
5620 return newInfo;
5621 }
5622
Wale Ogunwale9c103022018-10-18 07:44:54 -07005623 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005624 if (uid == SYSTEM_UID) {
5625 // The system gets to run in any process. If there are multiple processes with the same
5626 // uid, just pick the first (this should never happen).
5627 final SparseArray<WindowProcessController> procs =
5628 mProcessNames.getMap().get(processName);
5629 if (procs == null) return null;
5630 final int procCount = procs.size();
5631 for (int i = 0; i < procCount; i++) {
5632 final int procUid = procs.keyAt(i);
5633 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5634 // Don't use an app process or different user process for system component.
5635 continue;
5636 }
5637 return procs.valueAt(i);
5638 }
5639 }
5640
5641 return mProcessNames.get(processName, uid);
5642 }
5643
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005644 WindowProcessController getProcessController(IApplicationThread thread) {
5645 if (thread == null) {
5646 return null;
5647 }
5648
5649 final IBinder threadBinder = thread.asBinder();
5650 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5651 for (int i = pmap.size()-1; i >= 0; i--) {
5652 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5653 for (int j = procs.size() - 1; j >= 0; j--) {
5654 final WindowProcessController proc = procs.valueAt(j);
5655 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5656 return proc;
5657 }
5658 }
5659 }
5660
5661 return null;
5662 }
5663
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005664 WindowProcessController getProcessController(int pid, int uid) {
5665 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5666 for (int i = pmap.size()-1; i >= 0; i--) {
5667 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5668 for (int j = procs.size() - 1; j >= 0; j--) {
5669 final WindowProcessController proc = procs.valueAt(j);
5670 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5671 return proc;
5672 }
5673 }
5674 }
5675 return null;
5676 }
5677
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005678 int getUidStateLocked(int uid) {
5679 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5680 }
5681
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005682 boolean isUidForeground(int uid) {
5683 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5684 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5685 }
5686
Michal Karpinski4026cae2019-02-12 11:51:47 +00005687 boolean isDeviceOwner(String packageName) {
5688 if (packageName == null) {
5689 return false;
5690 }
5691 return packageName.equals(mDeviceOwnerPackageName);
5692 }
5693
5694 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5695 mDeviceOwnerPackageName = deviceOwnerPkg;
5696 }
5697
Wale Ogunwale9de19442018-10-18 19:05:03 -07005698 /**
5699 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5700 * the whitelist
5701 */
5702 String getPendingTempWhitelistTagForUidLocked(int uid) {
5703 return mPendingTempWhitelist.get(uid);
5704 }
5705
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005706 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5707 if (true || Build.IS_USER) {
5708 return;
5709 }
5710
5711 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5712 StrictMode.allowThreadDiskWrites();
5713 try {
5714 File tracesDir = new File("/data/anr");
5715 File tracesFile = null;
5716 try {
5717 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5718
5719 StringBuilder sb = new StringBuilder();
5720 Time tobj = new Time();
5721 tobj.set(System.currentTimeMillis());
5722 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5723 sb.append(": ");
5724 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5725 sb.append(" since ");
5726 sb.append(msg);
5727 FileOutputStream fos = new FileOutputStream(tracesFile);
5728 fos.write(sb.toString().getBytes());
5729 if (app == null) {
5730 fos.write("\n*** No application process!".getBytes());
5731 }
5732 fos.close();
5733 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5734 } catch (IOException e) {
5735 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5736 return;
5737 }
5738
5739 if (app != null && app.getPid() > 0) {
5740 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5741 firstPids.add(app.getPid());
5742 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5743 }
5744
5745 File lastTracesFile = null;
5746 File curTracesFile = null;
5747 for (int i=9; i>=0; i--) {
5748 String name = String.format(Locale.US, "slow%02d.txt", i);
5749 curTracesFile = new File(tracesDir, name);
5750 if (curTracesFile.exists()) {
5751 if (lastTracesFile != null) {
5752 curTracesFile.renameTo(lastTracesFile);
5753 } else {
5754 curTracesFile.delete();
5755 }
5756 }
5757 lastTracesFile = curTracesFile;
5758 }
5759 tracesFile.renameTo(curTracesFile);
5760 } finally {
5761 StrictMode.setThreadPolicy(oldPolicy);
5762 }
5763 }
5764
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005765 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005766 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005767
5768
Wale Ogunwale98875612018-10-12 07:53:02 -07005769 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5770 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005771
Riddle Hsud93a6c42018-11-29 21:50:06 +08005772 H(Looper looper) {
5773 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005774 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005775
5776 @Override
5777 public void handleMessage(Message msg) {
5778 switch (msg.what) {
5779 case REPORT_TIME_TRACKER_MSG: {
5780 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5781 tracker.deliverResult(mContext);
5782 } break;
5783 }
5784 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005785 }
5786
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005787 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005788 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005789
5790 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005791 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005792 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005793
5794 @Override
5795 public void handleMessage(Message msg) {
5796 switch (msg.what) {
5797 case DISMISS_DIALOG_UI_MSG: {
5798 final Dialog d = (Dialog) msg.obj;
5799 d.dismiss();
5800 break;
5801 }
5802 }
5803 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005804 }
5805
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005806 final class LocalService extends ActivityTaskManagerInternal {
5807 @Override
5808 public SleepToken acquireSleepToken(String tag, int displayId) {
5809 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005810 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005811 }
5812
5813 @Override
5814 public ComponentName getHomeActivityForUser(int userId) {
5815 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005816 final ActivityRecord homeActivity =
5817 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005818 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005819 }
5820 }
5821
5822 @Override
5823 public void onLocalVoiceInteractionStarted(IBinder activity,
5824 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5825 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005826 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005827 }
5828 }
5829
5830 @Override
5831 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5832 synchronized (mGlobalLock) {
5833 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5834 reasons, timestamp);
5835 }
5836 }
5837
5838 @Override
5839 public void notifyAppTransitionFinished() {
5840 synchronized (mGlobalLock) {
5841 mStackSupervisor.notifyAppTransitionDone();
5842 }
5843 }
5844
5845 @Override
5846 public void notifyAppTransitionCancelled() {
5847 synchronized (mGlobalLock) {
5848 mStackSupervisor.notifyAppTransitionDone();
5849 }
5850 }
5851
5852 @Override
5853 public List<IBinder> getTopVisibleActivities() {
5854 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005855 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005856 }
5857 }
5858
5859 @Override
5860 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5861 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005862 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005863 }
5864 }
5865
5866 @Override
5867 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5868 Bundle bOptions) {
5869 Preconditions.checkNotNull(intents, "intents");
5870 final String[] resolvedTypes = new String[intents.length];
5871
5872 // UID of the package on user userId.
5873 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5874 // packageUid may not be initialized.
5875 int packageUid = 0;
5876 final long ident = Binder.clearCallingIdentity();
5877
5878 try {
5879 for (int i = 0; i < intents.length; i++) {
5880 resolvedTypes[i] =
5881 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5882 }
5883
5884 packageUid = AppGlobals.getPackageManager().getPackageUid(
5885 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5886 } catch (RemoteException e) {
5887 // Shouldn't happen.
5888 } finally {
5889 Binder.restoreCallingIdentity(ident);
5890 }
5891
5892 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005893 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005894 packageUid, packageName,
5895 intents, resolvedTypes, null /* resultTo */,
5896 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005897 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5898 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005899 }
5900 }
5901
5902 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005903 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5904 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5905 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5906 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005907 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005908 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005909 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5910 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5911 userId, validateIncomingUser, originatingPendingIntent,
5912 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005913 }
5914 }
5915
5916 @Override
5917 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5918 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5919 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5920 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005921 PendingIntentRecord originatingPendingIntent,
5922 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005923 synchronized (mGlobalLock) {
5924 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5925 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5926 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005927 validateIncomingUser, originatingPendingIntent,
5928 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005929 }
5930 }
5931
5932 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005933 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5934 Intent intent, Bundle options, int userId) {
5935 return ActivityTaskManagerService.this.startActivityAsUser(
5936 caller, callerPacakge, intent,
5937 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5938 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5939 false /*validateIncomingUser*/);
5940 }
5941
5942 @Override
lumark588a3e82018-07-20 18:53:54 +08005943 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005944 synchronized (mGlobalLock) {
5945
5946 // We might change the visibilities here, so prepare an empty app transition which
5947 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005948 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005949 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005950 if (activityDisplay == null) {
5951 return;
5952 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005953 final DisplayContent dc = activityDisplay.mDisplayContent;
5954 final boolean wasTransitionSet =
5955 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005956 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005957 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005958 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005959 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005960
5961 // If there was a transition set already we don't want to interfere with it as we
5962 // might be starting it too early.
5963 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005964 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005965 }
5966 }
5967 if (callback != null) {
5968 callback.run();
5969 }
5970 }
5971
5972 @Override
5973 public void notifyKeyguardTrustedChanged() {
5974 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005975 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005976 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005977 }
5978 }
5979 }
5980
5981 /**
5982 * Called after virtual display Id is updated by
5983 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5984 * {@param vrVr2dDisplayId}.
5985 */
5986 @Override
5987 public void setVr2dDisplayId(int vr2dDisplayId) {
5988 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5989 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005990 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005991 }
5992 }
5993
5994 @Override
5995 public void setFocusedActivity(IBinder token) {
5996 synchronized (mGlobalLock) {
5997 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5998 if (r == null) {
5999 throw new IllegalArgumentException(
6000 "setFocusedActivity: No activity record matching token=" + token);
6001 }
Louis Chang19443452018-10-09 12:10:21 +08006002 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006003 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006004 }
6005 }
6006 }
6007
6008 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006009 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006010 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006011 }
6012
6013 @Override
6014 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006015 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006016 }
6017
6018 @Override
6019 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006020 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006021 }
6022
6023 @Override
6024 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6025 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6026 }
6027
6028 @Override
6029 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006030 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006031 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006032
6033 @Override
6034 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6035 synchronized (mGlobalLock) {
6036 mActiveVoiceInteractionServiceComponent = component;
6037 }
6038 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006039
6040 @Override
6041 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6042 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6043 return;
6044 }
6045 synchronized (mGlobalLock) {
6046 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6047 if (types == null) {
6048 if (uid < 0) {
6049 return;
6050 }
6051 types = new ArrayMap<>();
6052 mAllowAppSwitchUids.put(userId, types);
6053 }
6054 if (uid < 0) {
6055 types.remove(type);
6056 } else {
6057 types.put(type, uid);
6058 }
6059 }
6060 }
6061
6062 @Override
6063 public void onUserStopped(int userId) {
6064 synchronized (mGlobalLock) {
6065 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6066 mAllowAppSwitchUids.remove(userId);
6067 }
6068 }
6069
6070 @Override
6071 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6072 synchronized (mGlobalLock) {
6073 return ActivityTaskManagerService.this.isGetTasksAllowed(
6074 caller, callingPid, callingUid);
6075 }
6076 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006077
6078 @Override
6079 public void onProcessAdded(WindowProcessController proc) {
6080 synchronized (mGlobalLock) {
6081 mProcessNames.put(proc.mName, proc.mUid, proc);
6082 }
6083 }
6084
6085 @Override
6086 public void onProcessRemoved(String name, int uid) {
6087 synchronized (mGlobalLock) {
6088 mProcessNames.remove(name, uid);
6089 }
6090 }
6091
6092 @Override
6093 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6094 synchronized (mGlobalLock) {
6095 if (proc == mHomeProcess) {
6096 mHomeProcess = null;
6097 }
6098 if (proc == mPreviousProcess) {
6099 mPreviousProcess = null;
6100 }
6101 }
6102 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006103
6104 @Override
6105 public int getTopProcessState() {
6106 synchronized (mGlobalLock) {
6107 return mTopProcessState;
6108 }
6109 }
6110
6111 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006112 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6113 synchronized (mGlobalLock) {
6114 return proc == mHeavyWeightProcess;
6115 }
6116 }
6117
6118 @Override
6119 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6120 synchronized (mGlobalLock) {
6121 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6122 }
6123 }
6124
6125 @Override
6126 public void finishHeavyWeightApp() {
6127 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006128 if (mHeavyWeightProcess != null) {
6129 mHeavyWeightProcess.finishActivities();
6130 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006131 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6132 mHeavyWeightProcess);
6133 }
6134 }
6135
6136 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006137 public boolean isSleeping() {
6138 synchronized (mGlobalLock) {
6139 return isSleepingLocked();
6140 }
6141 }
6142
6143 @Override
6144 public boolean isShuttingDown() {
6145 synchronized (mGlobalLock) {
6146 return mShuttingDown;
6147 }
6148 }
6149
6150 @Override
6151 public boolean shuttingDown(boolean booted, int timeout) {
6152 synchronized (mGlobalLock) {
6153 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006154 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006155 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006156 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006157 return mStackSupervisor.shutdownLocked(timeout);
6158 }
6159 }
6160
6161 @Override
6162 public void enableScreenAfterBoot(boolean booted) {
6163 synchronized (mGlobalLock) {
6164 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6165 SystemClock.uptimeMillis());
6166 mWindowManager.enableScreenAfterBoot();
6167 updateEventDispatchingLocked(booted);
6168 }
6169 }
6170
6171 @Override
6172 public boolean showStrictModeViolationDialog() {
6173 synchronized (mGlobalLock) {
6174 return mShowDialogs && !mSleeping && !mShuttingDown;
6175 }
6176 }
6177
6178 @Override
6179 public void showSystemReadyErrorDialogsIfNeeded() {
6180 synchronized (mGlobalLock) {
6181 try {
6182 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6183 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6184 + " data partition or your device will be unstable.");
6185 mUiHandler.post(() -> {
6186 if (mShowDialogs) {
6187 AlertDialog d = new BaseErrorDialog(mUiContext);
6188 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6189 d.setCancelable(false);
6190 d.setTitle(mUiContext.getText(R.string.android_system_label));
6191 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6192 d.setButton(DialogInterface.BUTTON_POSITIVE,
6193 mUiContext.getText(R.string.ok),
6194 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6195 d.show();
6196 }
6197 });
6198 }
6199 } catch (RemoteException e) {
6200 }
6201
6202 if (!Build.isBuildConsistent()) {
6203 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6204 mUiHandler.post(() -> {
6205 if (mShowDialogs) {
6206 AlertDialog d = new BaseErrorDialog(mUiContext);
6207 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6208 d.setCancelable(false);
6209 d.setTitle(mUiContext.getText(R.string.android_system_label));
6210 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6211 d.setButton(DialogInterface.BUTTON_POSITIVE,
6212 mUiContext.getText(R.string.ok),
6213 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6214 d.show();
6215 }
6216 });
6217 }
6218 }
6219 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006220
6221 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006222 public void onProcessMapped(int pid, WindowProcessController proc) {
6223 synchronized (mGlobalLock) {
6224 mPidMap.put(pid, proc);
6225 }
6226 }
6227
6228 @Override
6229 public void onProcessUnMapped(int pid) {
6230 synchronized (mGlobalLock) {
6231 mPidMap.remove(pid);
6232 }
6233 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006234
6235 @Override
6236 public void onPackageDataCleared(String name) {
6237 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006238 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006239 mAppWarnings.onPackageDataCleared(name);
6240 }
6241 }
6242
6243 @Override
6244 public void onPackageUninstalled(String name) {
6245 synchronized (mGlobalLock) {
6246 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006247 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006248 }
6249 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006250
6251 @Override
6252 public void onPackageAdded(String name, boolean replacing) {
6253 synchronized (mGlobalLock) {
6254 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6255 }
6256 }
6257
6258 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006259 public void onPackageReplaced(ApplicationInfo aInfo) {
6260 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006261 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006262 }
6263 }
6264
6265 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006266 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6267 synchronized (mGlobalLock) {
6268 return compatibilityInfoForPackageLocked(ai);
6269 }
6270 }
6271
Yunfan Chen75157d72018-07-27 14:47:21 +09006272 /**
6273 * Set the corresponding display information for the process global configuration. To be
6274 * called when we need to show IME on a different display.
6275 *
6276 * @param pid The process id associated with the IME window.
6277 * @param displayId The ID of the display showing the IME.
6278 */
6279 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006280 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006281 if (pid == MY_PID || pid < 0) {
6282 if (DEBUG_CONFIGURATION) {
6283 Slog.w(TAG,
6284 "Trying to update display configuration for system/invalid process.");
6285 }
6286 return;
6287 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006288 synchronized (mGlobalLock) {
6289 final ActivityDisplay activityDisplay =
6290 mRootActivityContainer.getActivityDisplay(displayId);
6291 if (activityDisplay == null) {
6292 // Call might come when display is not yet added or has been removed.
6293 if (DEBUG_CONFIGURATION) {
6294 Slog.w(TAG, "Trying to update display configuration for non-existing "
6295 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006296 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006297 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006298 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006299 final WindowProcessController process = mPidMap.get(pid);
6300 if (process == null) {
6301 if (DEBUG_CONFIGURATION) {
6302 Slog.w(TAG, "Trying to update display configuration for invalid "
6303 + "process, pid=" + pid);
6304 }
6305 return;
6306 }
6307 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6308 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006309 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006310
6311 @Override
6312 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6313 int requestCode, int resultCode, Intent data) {
6314 synchronized (mGlobalLock) {
6315 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006316 if (r != null && r.getActivityStack() != null) {
6317 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6318 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006319 }
6320 }
6321 }
6322
6323 @Override
6324 public void clearPendingResultForActivity(IBinder activityToken,
6325 WeakReference<PendingIntentRecord> pir) {
6326 synchronized (mGlobalLock) {
6327 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6328 if (r != null && r.pendingResults != null) {
6329 r.pendingResults.remove(pir);
6330 }
6331 }
6332 }
6333
6334 @Override
6335 public IIntentSender getIntentSender(int type, String packageName,
6336 int callingUid, int userId, IBinder token, String resultWho,
6337 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6338 Bundle bOptions) {
6339 synchronized (mGlobalLock) {
6340 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6341 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6342 }
6343 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006344
6345 @Override
6346 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6347 synchronized (mGlobalLock) {
6348 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6349 if (r == null) {
6350 return null;
6351 }
6352 if (r.mServiceConnectionsHolder == null) {
6353 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6354 ActivityTaskManagerService.this, r);
6355 }
6356
6357 return r.mServiceConnectionsHolder;
6358 }
6359 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006360
6361 @Override
6362 public Intent getHomeIntent() {
6363 synchronized (mGlobalLock) {
6364 return ActivityTaskManagerService.this.getHomeIntent();
6365 }
6366 }
6367
6368 @Override
6369 public boolean startHomeActivity(int userId, String reason) {
6370 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006371 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006372 }
6373 }
6374
6375 @Override
6376 public boolean startHomeOnAllDisplays(int userId, String reason) {
6377 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006378 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006379 }
6380 }
6381
6382 @Override
6383 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6384 synchronized (mGlobalLock) {
6385 if (mFactoryTest == FACTORY_TEST_OFF) {
6386 return false;
6387 }
6388 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6389 && wpc.mName.equals(mTopComponent.getPackageName())) {
6390 return true;
6391 }
6392 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6393 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6394 }
6395 }
6396
6397 @Override
6398 public void updateTopComponentForFactoryTest() {
6399 synchronized (mGlobalLock) {
6400 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6401 return;
6402 }
6403 final ResolveInfo ri = mContext.getPackageManager()
6404 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6405 final CharSequence errorMsg;
6406 if (ri != null) {
6407 final ActivityInfo ai = ri.activityInfo;
6408 final ApplicationInfo app = ai.applicationInfo;
6409 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6410 mTopAction = Intent.ACTION_FACTORY_TEST;
6411 mTopData = null;
6412 mTopComponent = new ComponentName(app.packageName, ai.name);
6413 errorMsg = null;
6414 } else {
6415 errorMsg = mContext.getResources().getText(
6416 com.android.internal.R.string.factorytest_not_system);
6417 }
6418 } else {
6419 errorMsg = mContext.getResources().getText(
6420 com.android.internal.R.string.factorytest_no_action);
6421 }
6422 if (errorMsg == null) {
6423 return;
6424 }
6425
6426 mTopAction = null;
6427 mTopData = null;
6428 mTopComponent = null;
6429 mUiHandler.post(() -> {
6430 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6431 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006432 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006433 });
6434 }
6435 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006436
6437 @Override
6438 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6439 Runnable finishInstrumentationCallback) {
6440 synchronized (mGlobalLock) {
6441 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006442 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006443
6444 wpc.clearRecentTasks();
6445 wpc.clearActivities();
6446
6447 if (wpc.isInstrumenting()) {
6448 finishInstrumentationCallback.run();
6449 }
6450
Jorim Jaggid0752812018-10-16 16:07:20 +02006451 if (!restarting && hasVisibleActivities) {
6452 mWindowManager.deferSurfaceLayout();
6453 try {
6454 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6455 // If there was nothing to resume, and we are not already restarting
6456 // this process, but there is a visible activity that is hosted by the
6457 // process...then make sure all visible activities are running, taking
6458 // care of restarting this process.
6459 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6460 !PRESERVE_WINDOWS);
6461 }
6462 } finally {
6463 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006464 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006465 }
6466 }
6467 }
6468
6469 @Override
6470 public void closeSystemDialogs(String reason) {
6471 enforceNotIsolatedCaller("closeSystemDialogs");
6472
6473 final int pid = Binder.getCallingPid();
6474 final int uid = Binder.getCallingUid();
6475 final long origId = Binder.clearCallingIdentity();
6476 try {
6477 synchronized (mGlobalLock) {
6478 // Only allow this from foreground processes, so that background
6479 // applications can't abuse it to prevent system UI from being shown.
6480 if (uid >= FIRST_APPLICATION_UID) {
6481 final WindowProcessController proc = mPidMap.get(pid);
6482 if (!proc.isPerceptible()) {
6483 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6484 + " from background process " + proc);
6485 return;
6486 }
6487 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006488 mWindowManager.closeSystemDialogs(reason);
6489
Wale Ogunwaled32da472018-11-16 07:19:28 -08006490 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006491 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006492 // Call into AM outside the synchronized block.
6493 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006494 } finally {
6495 Binder.restoreCallingIdentity(origId);
6496 }
6497 }
6498
6499 @Override
6500 public void cleanupDisabledPackageComponents(
6501 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6502 synchronized (mGlobalLock) {
6503 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006504 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006505 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006506 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006507 mStackSupervisor.scheduleIdleLocked();
6508 }
6509
6510 // Clean-up disabled tasks
6511 getRecentTasks().cleanupDisabledPackageTasksLocked(
6512 packageName, disabledClasses, userId);
6513 }
6514 }
6515
6516 @Override
6517 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6518 int userId) {
6519 synchronized (mGlobalLock) {
6520
6521 boolean didSomething =
6522 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006523 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006524 null, doit, evenPersistent, userId);
6525 return didSomething;
6526 }
6527 }
6528
6529 @Override
6530 public void resumeTopActivities(boolean scheduleIdle) {
6531 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006532 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006533 if (scheduleIdle) {
6534 mStackSupervisor.scheduleIdleLocked();
6535 }
6536 }
6537 }
6538
6539 @Override
6540 public void preBindApplication(WindowProcessController wpc) {
6541 synchronized (mGlobalLock) {
6542 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6543 }
6544 }
6545
6546 @Override
6547 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6548 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006549 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006550 }
6551 }
6552
6553 @Override
6554 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6555 try {
6556 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6557 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6558 }
6559 } catch (RemoteException ex) {
6560 throw new SecurityException("Fail to check is caller a privileged app", ex);
6561 }
6562
6563 synchronized (mGlobalLock) {
6564 final long ident = Binder.clearCallingIdentity();
6565 try {
6566 if (mAmInternal.shouldConfirmCredentials(userId)) {
6567 if (mKeyguardController.isKeyguardLocked()) {
6568 // Showing launcher to avoid user entering credential twice.
6569 startHomeActivity(currentUserId, "notifyLockedProfile");
6570 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006571 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006572 }
6573 } finally {
6574 Binder.restoreCallingIdentity(ident);
6575 }
6576 }
6577 }
6578
6579 @Override
6580 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6581 mAmInternal.enforceCallingPermission(
6582 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6583
6584 synchronized (mGlobalLock) {
6585 final long ident = Binder.clearCallingIdentity();
6586 try {
6587 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6588 FLAG_ACTIVITY_TASK_ON_HOME);
6589 ActivityOptions activityOptions = options != null
6590 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006591 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006592 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006593 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006594 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006595 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006596 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6597 UserHandle.CURRENT);
6598 } finally {
6599 Binder.restoreCallingIdentity(ident);
6600 }
6601 }
6602 }
6603
6604 @Override
6605 public void writeActivitiesToProto(ProtoOutputStream proto) {
6606 synchronized (mGlobalLock) {
6607 // The output proto of "activity --proto activities"
6608 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006609 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006610 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6611 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006612 }
6613 }
6614
6615 @Override
6616 public void saveANRState(String reason) {
6617 synchronized (mGlobalLock) {
6618 final StringWriter sw = new StringWriter();
6619 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6620 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6621 if (reason != null) {
6622 pw.println(" Reason: " + reason);
6623 }
6624 pw.println();
6625 getActivityStartController().dump(pw, " ", null);
6626 pw.println();
6627 pw.println("-------------------------------------------------------------------------------");
6628 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6629 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6630 "" /* header */);
6631 pw.println();
6632 pw.close();
6633
6634 mLastANRState = sw.toString();
6635 }
6636 }
6637
6638 @Override
6639 public void clearSavedANRState() {
6640 synchronized (mGlobalLock) {
6641 mLastANRState = null;
6642 }
6643 }
6644
6645 @Override
6646 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6647 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6648 synchronized (mGlobalLock) {
6649 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6650 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6651 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6652 dumpLastANRLocked(pw);
6653 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6654 dumpLastANRTracesLocked(pw);
6655 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6656 dumpActivityStarterLocked(pw, dumpPackage);
6657 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6658 dumpActivityContainersLocked(pw);
6659 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6660 if (getRecentTasks() != null) {
6661 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6662 }
6663 }
6664 }
6665 }
6666
6667 @Override
6668 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6669 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6670 int wakefulness) {
6671 synchronized (mGlobalLock) {
6672 if (mHomeProcess != null && (dumpPackage == null
6673 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6674 if (needSep) {
6675 pw.println();
6676 needSep = false;
6677 }
6678 pw.println(" mHomeProcess: " + mHomeProcess);
6679 }
6680 if (mPreviousProcess != null && (dumpPackage == null
6681 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6682 if (needSep) {
6683 pw.println();
6684 needSep = false;
6685 }
6686 pw.println(" mPreviousProcess: " + mPreviousProcess);
6687 }
6688 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6689 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6690 StringBuilder sb = new StringBuilder(128);
6691 sb.append(" mPreviousProcessVisibleTime: ");
6692 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6693 pw.println(sb);
6694 }
6695 if (mHeavyWeightProcess != null && (dumpPackage == null
6696 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6697 if (needSep) {
6698 pw.println();
6699 needSep = false;
6700 }
6701 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6702 }
6703 if (dumpPackage == null) {
6704 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006705 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006706 }
6707 if (dumpAll) {
6708 if (dumpPackage == null) {
6709 pw.println(" mConfigWillChange: "
6710 + getTopDisplayFocusedStack().mConfigWillChange);
6711 }
6712 if (mCompatModePackages.getPackages().size() > 0) {
6713 boolean printed = false;
6714 for (Map.Entry<String, Integer> entry
6715 : mCompatModePackages.getPackages().entrySet()) {
6716 String pkg = entry.getKey();
6717 int mode = entry.getValue();
6718 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6719 continue;
6720 }
6721 if (!printed) {
6722 pw.println(" mScreenCompatPackages:");
6723 printed = true;
6724 }
6725 pw.println(" " + pkg + ": " + mode);
6726 }
6727 }
6728 }
6729
6730 if (dumpPackage == null) {
6731 pw.println(" mWakefulness="
6732 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006733 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006734 if (mRunningVoice != null) {
6735 pw.println(" mRunningVoice=" + mRunningVoice);
6736 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6737 }
6738 pw.println(" mSleeping=" + mSleeping);
6739 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6740 pw.println(" mVrController=" + mVrController);
6741 }
6742 if (mCurAppTimeTracker != null) {
6743 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6744 }
6745 if (mAllowAppSwitchUids.size() > 0) {
6746 boolean printed = false;
6747 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6748 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6749 for (int j = 0; j < types.size(); j++) {
6750 if (dumpPackage == null ||
6751 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6752 if (needSep) {
6753 pw.println();
6754 needSep = false;
6755 }
6756 if (!printed) {
6757 pw.println(" mAllowAppSwitchUids:");
6758 printed = true;
6759 }
6760 pw.print(" User ");
6761 pw.print(mAllowAppSwitchUids.keyAt(i));
6762 pw.print(": Type ");
6763 pw.print(types.keyAt(j));
6764 pw.print(" = ");
6765 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6766 pw.println();
6767 }
6768 }
6769 }
6770 }
6771 if (dumpPackage == null) {
6772 if (mController != null) {
6773 pw.println(" mController=" + mController
6774 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6775 }
6776 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6777 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6778 }
6779
6780 return needSep;
6781 }
6782 }
6783
6784 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006785 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6786 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006787 synchronized (mGlobalLock) {
6788 if (dumpPackage == null) {
6789 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6790 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006791 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6792 if (mRunningVoice != null) {
6793 final long vrToken = proto.start(
6794 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6795 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6796 mRunningVoice.toString());
6797 mVoiceWakeLock.writeToProto(
6798 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6799 proto.end(vrToken);
6800 }
6801 mVrController.writeToProto(proto,
6802 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006803 if (mController != null) {
6804 final long token = proto.start(CONTROLLER);
6805 proto.write(CONTROLLER, mController.toString());
6806 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6807 proto.end(token);
6808 }
6809 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6810 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6811 }
6812
6813 if (mHomeProcess != null && (dumpPackage == null
6814 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006815 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 }
6817
6818 if (mPreviousProcess != null && (dumpPackage == null
6819 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006820 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006821 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6822 }
6823
6824 if (mHeavyWeightProcess != null && (dumpPackage == null
6825 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006826 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006827 }
6828
6829 for (Map.Entry<String, Integer> entry
6830 : mCompatModePackages.getPackages().entrySet()) {
6831 String pkg = entry.getKey();
6832 int mode = entry.getValue();
6833 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6834 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6835 proto.write(PACKAGE, pkg);
6836 proto.write(MODE, mode);
6837 proto.end(compatToken);
6838 }
6839 }
6840
6841 if (mCurAppTimeTracker != null) {
6842 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6843 }
6844
6845 }
6846 }
6847
6848 @Override
6849 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6850 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6851 boolean dumpFocusedStackOnly) {
6852 synchronized (mGlobalLock) {
6853 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6854 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6855 }
6856 }
6857
6858 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006859 public void dumpForOom(PrintWriter pw) {
6860 synchronized (mGlobalLock) {
6861 pw.println(" mHomeProcess: " + mHomeProcess);
6862 pw.println(" mPreviousProcess: " + mPreviousProcess);
6863 if (mHeavyWeightProcess != null) {
6864 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6865 }
6866 }
6867 }
6868
6869 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 public boolean canGcNow() {
6871 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006872 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006873 }
6874 }
6875
6876 @Override
6877 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006878 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006879 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006880 return top != null ? top.app : null;
6881 }
6882 }
6883
6884 @Override
6885 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006886 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006887 if (mRootActivityContainer != null) {
6888 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006889 }
6890 }
6891 }
6892
6893 @Override
6894 public void scheduleDestroyAllActivities(String reason) {
6895 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006896 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006897 }
6898 }
6899
6900 @Override
6901 public void removeUser(int userId) {
6902 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006903 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006904 }
6905 }
6906
6907 @Override
6908 public boolean switchUser(int userId, UserState userState) {
6909 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006910 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006911 }
6912 }
6913
6914 @Override
6915 public void onHandleAppCrash(WindowProcessController wpc) {
6916 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006917 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006918 }
6919 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006920
6921 @Override
6922 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6923 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006924 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006925 }
6926 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006927
6928 @Override
6929 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006930 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006931 mActiveUids.put(uid, procState);
6932 }
6933 }
6934
6935 @Override
6936 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006937 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006938 mActiveUids.remove(uid);
6939 }
6940 }
6941
6942 @Override
6943 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006944 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006945 mActiveUids.clear();
6946 }
6947 }
6948
6949 @Override
6950 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006951 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006952 if (mActiveUids.get(uid) != null) {
6953 mActiveUids.put(uid, procState);
6954 }
6955 }
6956 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006957
6958 @Override
6959 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006960 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006961 mPendingTempWhitelist.put(uid, tag);
6962 }
6963 }
6964
6965 @Override
6966 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006967 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07006968 mPendingTempWhitelist.remove(uid);
6969 }
6970 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006971
6972 @Override
6973 public boolean handleAppCrashInActivityController(String processName, int pid,
6974 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6975 Runnable killCrashingAppCallback) {
6976 synchronized (mGlobalLock) {
6977 if (mController == null) {
6978 return false;
6979 }
6980
6981 try {
6982 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6983 stackTrace)) {
6984 killCrashingAppCallback.run();
6985 return true;
6986 }
6987 } catch (RemoteException e) {
6988 mController = null;
6989 Watchdog.getInstance().setActivityController(null);
6990 }
6991 return false;
6992 }
6993 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006994
6995 @Override
6996 public void removeRecentTasksByPackageName(String packageName, int userId) {
6997 synchronized (mGlobalLock) {
6998 mRecentTasks.removeTasksByPackageName(packageName, userId);
6999 }
7000 }
7001
7002 @Override
7003 public void cleanupRecentTasksForUser(int userId) {
7004 synchronized (mGlobalLock) {
7005 mRecentTasks.cleanupLocked(userId);
7006 }
7007 }
7008
7009 @Override
7010 public void loadRecentTasksForUser(int userId) {
7011 synchronized (mGlobalLock) {
7012 mRecentTasks.loadUserRecentsLocked(userId);
7013 }
7014 }
7015
7016 @Override
7017 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7018 synchronized (mGlobalLock) {
7019 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7020 }
7021 }
7022
7023 @Override
7024 public void flushRecentTasks() {
7025 mRecentTasks.flush();
7026 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007027
7028 @Override
7029 public WindowProcessController getHomeProcess() {
7030 synchronized (mGlobalLock) {
7031 return mHomeProcess;
7032 }
7033 }
7034
7035 @Override
7036 public WindowProcessController getPreviousProcess() {
7037 synchronized (mGlobalLock) {
7038 return mPreviousProcess;
7039 }
7040 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007041
7042 @Override
7043 public void clearLockedTasks(String reason) {
7044 synchronized (mGlobalLock) {
7045 getLockTaskController().clearLockedTasks(reason);
7046 }
7047 }
7048
7049 @Override
7050 public void updateUserConfiguration() {
7051 synchronized (mGlobalLock) {
7052 final Configuration configuration = new Configuration(getGlobalConfiguration());
7053 final int currentUserId = mAmInternal.getCurrentUserId();
7054 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7055 configuration, currentUserId, Settings.System.canWrite(mContext));
7056 updateConfigurationLocked(configuration, null /* starting */,
7057 false /* initLocale */, false /* persistent */, currentUserId,
7058 false /* deferResume */);
7059 }
7060 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007061
7062 @Override
7063 public boolean canShowErrorDialogs() {
7064 synchronized (mGlobalLock) {
7065 return mShowDialogs && !mSleeping && !mShuttingDown
7066 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7067 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7068 mAmInternal.getCurrentUserId())
7069 && !(UserManager.isDeviceInDemoMode(mContext)
7070 && mAmInternal.getCurrentUser().isDemo());
7071 }
7072 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007073
7074 @Override
7075 public void setProfileApp(String profileApp) {
7076 synchronized (mGlobalLock) {
7077 mProfileApp = profileApp;
7078 }
7079 }
7080
7081 @Override
7082 public void setProfileProc(WindowProcessController wpc) {
7083 synchronized (mGlobalLock) {
7084 mProfileProc = wpc;
7085 }
7086 }
7087
7088 @Override
7089 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7090 synchronized (mGlobalLock) {
7091 mProfilerInfo = profilerInfo;
7092 }
7093 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007094
7095 @Override
7096 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7097 synchronized (mGlobalLock) {
7098 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7099 }
7100 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007101
7102 @Override
7103 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7104 synchronized (mGlobalLock) {
7105 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7106 }
7107 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007108
7109 @Override
7110 public boolean isUidForeground(int uid) {
7111 synchronized (mGlobalLock) {
7112 return ActivityTaskManagerService.this.isUidForeground(uid);
7113 }
7114 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007115
7116 @Override
7117 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7118 synchronized (mGlobalLock) {
7119 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7120 }
7121 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007122 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007123}