blob: 82fce67d8dd705ddd9e2c90d34b9fcb1e05d4ab8 [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
Andrii Kulian86e70fc2019-02-12 11:04:10 +00001623 public final void activityTopResumedStateLost() {
1624 final long origId = Binder.clearCallingIdentity();
1625 synchronized (mGlobalLock) {
1626 mStackSupervisor.handleTopResumedStateReleased(false /* timeout */);
1627 }
1628 Binder.restoreCallingIdentity(origId);
1629 }
1630
1631 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001632 public final void activityPaused(IBinder token) {
1633 final long origId = Binder.clearCallingIdentity();
1634 synchronized (mGlobalLock) {
1635 ActivityStack stack = ActivityRecord.getStackLocked(token);
1636 if (stack != null) {
1637 stack.activityPausedLocked(token, false);
1638 }
1639 }
1640 Binder.restoreCallingIdentity(origId);
1641 }
1642
1643 @Override
1644 public final void activityStopped(IBinder token, Bundle icicle,
1645 PersistableBundle persistentState, CharSequence description) {
1646 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1647
1648 // Refuse possible leaked file descriptors
1649 if (icicle != null && icicle.hasFileDescriptors()) {
1650 throw new IllegalArgumentException("File descriptors passed in Bundle");
1651 }
1652
1653 final long origId = Binder.clearCallingIdentity();
1654
1655 synchronized (mGlobalLock) {
1656 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1657 if (r != null) {
1658 r.activityStoppedLocked(icicle, persistentState, description);
1659 }
1660 }
1661
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001662 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001663
1664 Binder.restoreCallingIdentity(origId);
1665 }
1666
1667 @Override
1668 public final void activityDestroyed(IBinder token) {
1669 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1670 synchronized (mGlobalLock) {
1671 ActivityStack stack = ActivityRecord.getStackLocked(token);
1672 if (stack != null) {
1673 stack.activityDestroyedLocked(token, "activityDestroyed");
1674 }
1675 }
1676 }
1677
1678 @Override
1679 public final void activityRelaunched(IBinder token) {
1680 final long origId = Binder.clearCallingIdentity();
1681 synchronized (mGlobalLock) {
1682 mStackSupervisor.activityRelaunchedLocked(token);
1683 }
1684 Binder.restoreCallingIdentity(origId);
1685 }
1686
1687 public final void activitySlept(IBinder token) {
1688 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1689
1690 final long origId = Binder.clearCallingIdentity();
1691
1692 synchronized (mGlobalLock) {
1693 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1694 if (r != null) {
1695 mStackSupervisor.activitySleptLocked(r);
1696 }
1697 }
1698
1699 Binder.restoreCallingIdentity(origId);
1700 }
1701
1702 @Override
1703 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1704 synchronized (mGlobalLock) {
1705 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1706 if (r == null) {
1707 return;
1708 }
1709 final long origId = Binder.clearCallingIdentity();
1710 try {
1711 r.setRequestedOrientation(requestedOrientation);
1712 } finally {
1713 Binder.restoreCallingIdentity(origId);
1714 }
1715 }
1716 }
1717
1718 @Override
1719 public int getRequestedOrientation(IBinder token) {
1720 synchronized (mGlobalLock) {
1721 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1722 if (r == null) {
1723 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1724 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001725 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001726 }
1727 }
1728
1729 @Override
1730 public void setImmersive(IBinder token, boolean immersive) {
1731 synchronized (mGlobalLock) {
1732 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1733 if (r == null) {
1734 throw new IllegalArgumentException();
1735 }
1736 r.immersive = immersive;
1737
1738 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001739 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001740 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001741 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001742 }
1743 }
1744 }
1745
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001746 void applyUpdateLockStateLocked(ActivityRecord r) {
1747 // Modifications to the UpdateLock state are done on our handler, outside
1748 // the activity manager's locks. The new state is determined based on the
1749 // state *now* of the relevant activity record. The object is passed to
1750 // the handler solely for logging detail, not to be consulted/modified.
1751 final boolean nextState = r != null && r.immersive;
1752 mH.post(() -> {
1753 if (mUpdateLock.isHeld() != nextState) {
1754 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1755 "Applying new update lock state '" + nextState + "' for " + r);
1756 if (nextState) {
1757 mUpdateLock.acquire();
1758 } else {
1759 mUpdateLock.release();
1760 }
1761 }
1762 });
1763 }
1764
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001765 @Override
1766 public boolean isImmersive(IBinder token) {
1767 synchronized (mGlobalLock) {
1768 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1769 if (r == null) {
1770 throw new IllegalArgumentException();
1771 }
1772 return r.immersive;
1773 }
1774 }
1775
1776 @Override
1777 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001778 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001779 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001780 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001781 return (r != null) ? r.immersive : false;
1782 }
1783 }
1784
1785 @Override
1786 public void overridePendingTransition(IBinder token, String packageName,
1787 int enterAnim, int exitAnim) {
1788 synchronized (mGlobalLock) {
1789 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1790 if (self == null) {
1791 return;
1792 }
1793
1794 final long origId = Binder.clearCallingIdentity();
1795
1796 if (self.isState(
1797 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001798 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001799 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 }
1801
1802 Binder.restoreCallingIdentity(origId);
1803 }
1804 }
1805
1806 @Override
1807 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001808 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001809 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001810 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 if (r == null) {
1812 return ActivityManager.COMPAT_MODE_UNKNOWN;
1813 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001814 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001815 }
1816 }
1817
1818 @Override
1819 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001820 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001821 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001822 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001823 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001824 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001825 if (r == null) {
1826 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1827 return;
1828 }
1829 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001830 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001831 }
1832 }
1833
1834 @Override
1835 public int getLaunchedFromUid(IBinder activityToken) {
1836 ActivityRecord srec;
1837 synchronized (mGlobalLock) {
1838 srec = ActivityRecord.forTokenLocked(activityToken);
1839 }
1840 if (srec == null) {
1841 return -1;
1842 }
1843 return srec.launchedFromUid;
1844 }
1845
1846 @Override
1847 public String getLaunchedFromPackage(IBinder activityToken) {
1848 ActivityRecord srec;
1849 synchronized (mGlobalLock) {
1850 srec = ActivityRecord.forTokenLocked(activityToken);
1851 }
1852 if (srec == null) {
1853 return null;
1854 }
1855 return srec.launchedFromPackage;
1856 }
1857
1858 @Override
1859 public boolean convertFromTranslucent(IBinder token) {
1860 final long origId = Binder.clearCallingIdentity();
1861 try {
1862 synchronized (mGlobalLock) {
1863 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1864 if (r == null) {
1865 return false;
1866 }
1867 final boolean translucentChanged = r.changeWindowTranslucency(true);
1868 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001869 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001870 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001871 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001872 return translucentChanged;
1873 }
1874 } finally {
1875 Binder.restoreCallingIdentity(origId);
1876 }
1877 }
1878
1879 @Override
1880 public boolean convertToTranslucent(IBinder token, Bundle options) {
1881 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1882 final long origId = Binder.clearCallingIdentity();
1883 try {
1884 synchronized (mGlobalLock) {
1885 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1886 if (r == null) {
1887 return false;
1888 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001889 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001890 int index = task.mActivities.lastIndexOf(r);
1891 if (index > 0) {
1892 ActivityRecord under = task.mActivities.get(index - 1);
1893 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1894 }
1895 final boolean translucentChanged = r.changeWindowTranslucency(false);
1896 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001897 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001898 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001899 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001900 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001901 return translucentChanged;
1902 }
1903 } finally {
1904 Binder.restoreCallingIdentity(origId);
1905 }
1906 }
1907
1908 @Override
1909 public void notifyActivityDrawn(IBinder token) {
1910 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1911 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001912 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001913 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001914 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001915 }
1916 }
1917 }
1918
1919 @Override
1920 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1921 synchronized (mGlobalLock) {
1922 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1923 if (r == null) {
1924 return;
1925 }
1926 r.reportFullyDrawnLocked(restoredFromBundle);
1927 }
1928 }
1929
1930 @Override
1931 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1932 synchronized (mGlobalLock) {
1933 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1934 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1935 return stack.mDisplayId;
1936 }
1937 return DEFAULT_DISPLAY;
1938 }
1939 }
1940
1941 @Override
1942 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001943 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 long ident = Binder.clearCallingIdentity();
1945 try {
1946 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001947 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001948 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001949 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001950 }
1951 return null;
1952 }
1953 } finally {
1954 Binder.restoreCallingIdentity(ident);
1955 }
1956 }
1957
1958 @Override
1959 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001960 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1962 final long callingId = Binder.clearCallingIdentity();
1963 try {
1964 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001965 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001966 if (stack == null) {
1967 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1968 return;
1969 }
1970 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001971 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001972 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001973 }
1974 }
1975 } finally {
1976 Binder.restoreCallingIdentity(callingId);
1977 }
1978 }
1979
1980 @Override
1981 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001982 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1984 final long callingId = Binder.clearCallingIdentity();
1985 try {
1986 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001987 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001988 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001989 if (task == null) {
1990 return;
1991 }
1992 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001993 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001994 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001995 }
1996 }
1997 } finally {
1998 Binder.restoreCallingIdentity(callingId);
1999 }
2000 }
2001
2002 @Override
2003 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002004 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 synchronized (mGlobalLock) {
2006 final long ident = Binder.clearCallingIdentity();
2007 try {
2008 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2009 "remove-task");
2010 } finally {
2011 Binder.restoreCallingIdentity(ident);
2012 }
2013 }
2014 }
2015
2016 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002017 public void removeAllVisibleRecentTasks() {
2018 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2019 synchronized (mGlobalLock) {
2020 final long ident = Binder.clearCallingIdentity();
2021 try {
2022 getRecentTasks().removeAllVisibleTasks();
2023 } finally {
2024 Binder.restoreCallingIdentity(ident);
2025 }
2026 }
2027 }
2028
2029 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002030 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2031 synchronized (mGlobalLock) {
2032 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2033 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002034 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002035 }
2036 }
2037 return false;
2038 }
2039
2040 @Override
2041 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2042 Intent resultData) {
2043
2044 synchronized (mGlobalLock) {
2045 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2046 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002047 return r.getActivityStack().navigateUpToLocked(
2048 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002049 }
2050 return false;
2051 }
2052 }
2053
2054 /**
2055 * Attempts to move a task backwards in z-order (the order of activities within the task is
2056 * unchanged).
2057 *
2058 * There are several possible results of this call:
2059 * - if the task is locked, then we will show the lock toast
2060 * - if there is a task behind the provided task, then that task is made visible and resumed as
2061 * this task is moved to the back
2062 * - otherwise, if there are no other tasks in the stack:
2063 * - if this task is in the pinned stack, then we remove the stack completely, which will
2064 * have the effect of moving the task to the top or bottom of the fullscreen stack
2065 * (depending on whether it is visible)
2066 * - otherwise, we simply return home and hide this task
2067 *
2068 * @param token A reference to the activity we wish to move
2069 * @param nonRoot If false then this only works if the activity is the root
2070 * of a task; if true it will work for any activity in a task.
2071 * @return Returns true if the move completed, false if not.
2072 */
2073 @Override
2074 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002075 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002076 synchronized (mGlobalLock) {
2077 final long origId = Binder.clearCallingIdentity();
2078 try {
2079 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002080 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002081 if (task != null) {
2082 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2083 }
2084 } finally {
2085 Binder.restoreCallingIdentity(origId);
2086 }
2087 }
2088 return false;
2089 }
2090
2091 @Override
2092 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002093 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002094 long ident = Binder.clearCallingIdentity();
2095 Rect rect = new Rect();
2096 try {
2097 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002098 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002099 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2100 if (task == null) {
2101 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2102 return rect;
2103 }
2104 if (task.getStack() != null) {
2105 // Return the bounds from window manager since it will be adjusted for various
2106 // things like the presense of a docked stack for tasks that aren't resizeable.
2107 task.getWindowContainerBounds(rect);
2108 } else {
2109 // Task isn't in window manager yet since it isn't associated with a stack.
2110 // Return the persist value from activity manager
2111 if (!task.matchParentBounds()) {
2112 rect.set(task.getBounds());
2113 } else if (task.mLastNonFullscreenBounds != null) {
2114 rect.set(task.mLastNonFullscreenBounds);
2115 }
2116 }
2117 }
2118 } finally {
2119 Binder.restoreCallingIdentity(ident);
2120 }
2121 return rect;
2122 }
2123
2124 @Override
2125 public ActivityManager.TaskDescription getTaskDescription(int id) {
2126 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002127 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002128 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002129 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002130 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2131 if (tr != null) {
2132 return tr.lastTaskDescription;
2133 }
2134 }
2135 return null;
2136 }
2137
2138 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002139 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2140 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2141 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2142 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2143 return;
2144 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002145 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002146 synchronized (mGlobalLock) {
2147 final long ident = Binder.clearCallingIdentity();
2148 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002149 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002150 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002151 if (task == null) {
2152 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2153 return;
2154 }
2155
2156 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2157 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2158
2159 if (!task.isActivityTypeStandardOrUndefined()) {
2160 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2161 + " non-standard task " + taskId + " to windowing mode="
2162 + windowingMode);
2163 }
2164
2165 final ActivityStack stack = task.getStack();
2166 if (toTop) {
2167 stack.moveToFront("setTaskWindowingMode", task);
2168 }
2169 stack.setWindowingMode(windowingMode);
2170 } finally {
2171 Binder.restoreCallingIdentity(ident);
2172 }
2173 }
2174 }
2175
2176 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002177 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002178 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002179 ActivityRecord r = getCallingRecordLocked(token);
2180 return r != null ? r.info.packageName : null;
2181 }
2182 }
2183
2184 @Override
2185 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002186 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002187 ActivityRecord r = getCallingRecordLocked(token);
2188 return r != null ? r.intent.getComponent() : null;
2189 }
2190 }
2191
2192 private ActivityRecord getCallingRecordLocked(IBinder token) {
2193 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2194 if (r == null) {
2195 return null;
2196 }
2197 return r.resultTo;
2198 }
2199
2200 @Override
2201 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002202 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002203
2204 synchronized (mGlobalLock) {
2205 final long origId = Binder.clearCallingIdentity();
2206 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002207 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002208 } finally {
2209 Binder.restoreCallingIdentity(origId);
2210 }
2211 }
2212 }
2213
2214 /**
2215 * TODO: Add mController hook
2216 */
2217 @Override
2218 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002219 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002220
2221 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2222 synchronized (mGlobalLock) {
2223 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2224 false /* fromRecents */);
2225 }
2226 }
2227
2228 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2229 boolean fromRecents) {
2230
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002231 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002232 Binder.getCallingUid(), -1, -1, "Task to front")) {
2233 SafeActivityOptions.abort(options);
2234 return;
2235 }
2236 final long origId = Binder.clearCallingIdentity();
2237 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002238 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002239 if (task == null) {
2240 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002241 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002242 return;
2243 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002244 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002245 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002246 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002247 return;
2248 }
2249 ActivityOptions realOptions = options != null
2250 ? options.getOptions(mStackSupervisor)
2251 : null;
2252 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2253 false /* forceNonResizable */);
2254
2255 final ActivityRecord topActivity = task.getTopActivity();
2256 if (topActivity != null) {
2257
2258 // We are reshowing a task, use a starting window to hide the initial draw delay
2259 // so the transition can start earlier.
2260 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2261 true /* taskSwitch */, fromRecents);
2262 }
2263 } finally {
2264 Binder.restoreCallingIdentity(origId);
2265 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002266 }
2267
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002268 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2269 int callingPid, int callingUid, String name) {
2270 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2271 return true;
2272 }
2273
2274 if (getRecentTasks().isCallerRecents(sourceUid)) {
2275 return true;
2276 }
2277
2278 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2279 if (perm == PackageManager.PERMISSION_GRANTED) {
2280 return true;
2281 }
2282 if (checkAllowAppSwitchUid(sourceUid)) {
2283 return true;
2284 }
2285
2286 // If the actual IPC caller is different from the logical source, then
2287 // also see if they are allowed to control app switches.
2288 if (callingUid != -1 && callingUid != sourceUid) {
2289 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2290 if (perm == PackageManager.PERMISSION_GRANTED) {
2291 return true;
2292 }
2293 if (checkAllowAppSwitchUid(callingUid)) {
2294 return true;
2295 }
2296 }
2297
2298 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2299 return false;
2300 }
2301
2302 private boolean checkAllowAppSwitchUid(int uid) {
2303 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2304 if (types != null) {
2305 for (int i = types.size() - 1; i >= 0; i--) {
2306 if (types.valueAt(i).intValue() == uid) {
2307 return true;
2308 }
2309 }
2310 }
2311 return false;
2312 }
2313
2314 @Override
2315 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2316 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2317 "setActivityController()");
2318 synchronized (mGlobalLock) {
2319 mController = controller;
2320 mControllerIsAMonkey = imAMonkey;
2321 Watchdog.getInstance().setActivityController(controller);
2322 }
2323 }
2324
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002325 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002326 synchronized (mGlobalLock) {
2327 return mController != null && mControllerIsAMonkey;
2328 }
2329 }
2330
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002331 @Override
2332 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2333 synchronized (mGlobalLock) {
2334 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2335 }
2336 }
2337
2338 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002339 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2340 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2341 }
2342
2343 @Override
2344 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2345 @WindowConfiguration.ActivityType int ignoreActivityType,
2346 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2347 final int callingUid = Binder.getCallingUid();
2348 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2349
2350 synchronized (mGlobalLock) {
2351 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2352
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002353 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002354 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002355 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002356 ignoreWindowingMode, callingUid, allowed);
2357 }
2358
2359 return list;
2360 }
2361
2362 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002363 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2364 synchronized (mGlobalLock) {
2365 final long origId = Binder.clearCallingIdentity();
2366 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2367 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002368 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369 }
2370 Binder.restoreCallingIdentity(origId);
2371 }
2372 }
2373
2374 @Override
2375 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002376 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002377 ActivityStack stack = ActivityRecord.getStackLocked(token);
2378 if (stack != null) {
2379 return stack.willActivityBeVisibleLocked(token);
2380 }
2381 return false;
2382 }
2383 }
2384
2385 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002386 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002387 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002388 synchronized (mGlobalLock) {
2389 final long ident = Binder.clearCallingIdentity();
2390 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002391 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002392 if (task == null) {
2393 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2394 return;
2395 }
2396
2397 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2398 + " to stackId=" + stackId + " toTop=" + toTop);
2399
Wale Ogunwaled32da472018-11-16 07:19:28 -08002400 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002401 if (stack == null) {
2402 throw new IllegalStateException(
2403 "moveTaskToStack: No stack for stackId=" + stackId);
2404 }
2405 if (!stack.isActivityTypeStandardOrUndefined()) {
2406 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2407 + taskId + " to stack " + stackId);
2408 }
2409 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002410 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002411 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2412 }
2413 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2414 "moveTaskToStack");
2415 } finally {
2416 Binder.restoreCallingIdentity(ident);
2417 }
2418 }
2419 }
2420
2421 @Override
2422 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2423 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002424 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002425
2426 final long ident = Binder.clearCallingIdentity();
2427 try {
2428 synchronized (mGlobalLock) {
2429 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002430 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002431 if (stack == null) {
2432 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2433 return;
2434 }
2435 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2436 throw new IllegalArgumentException("Stack: " + stackId
2437 + " doesn't support animated resize.");
2438 }
2439 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2440 animationDuration, false /* fromFullscreen */);
2441 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002442 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002443 if (stack == null) {
2444 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2445 return;
2446 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002447 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002448 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2449 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2450 }
2451 }
2452 } finally {
2453 Binder.restoreCallingIdentity(ident);
2454 }
2455 }
2456
wilsonshih5c4cf522019-01-25 09:03:47 +08002457 @Override
2458 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2459 int animationDuration) {
2460 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2461
2462 final long ident = Binder.clearCallingIdentity();
2463 try {
2464 synchronized (mGlobalLock) {
2465 if (xOffset == 0 && yOffset == 0) {
2466 return;
2467 }
2468 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2469 if (stack == null) {
2470 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2471 return;
2472 }
2473 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2474 throw new IllegalArgumentException("Stack: " + stackId
2475 + " doesn't support animated resize.");
2476 }
2477 final Rect destBounds = new Rect();
2478 stack.getAnimationOrCurrentBounds(destBounds);
2479 if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
2480 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2481 return;
2482 }
2483 destBounds.offset(xOffset, yOffset);
2484 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2485 animationDuration, false /* fromFullscreen */);
2486 }
2487 } finally {
2488 Binder.restoreCallingIdentity(ident);
2489 }
2490 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002491 /**
2492 * Moves the specified task to the primary-split-screen stack.
2493 *
2494 * @param taskId Id of task to move.
2495 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2496 * exist already. See
2497 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2498 * and
2499 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2500 * @param toTop If the task and stack should be moved to the top.
2501 * @param animate Whether we should play an animation for the moving the task.
2502 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2503 * stack. Pass {@code null} to use default bounds.
2504 * @param showRecents If the recents activity should be shown on the other side of the task
2505 * going into split-screen mode.
2506 */
2507 @Override
2508 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2509 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002510 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002511 "setTaskWindowingModeSplitScreenPrimary()");
2512 synchronized (mGlobalLock) {
2513 final long ident = Binder.clearCallingIdentity();
2514 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002515 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002516 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 if (task == null) {
2518 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2519 return false;
2520 }
2521 if (DEBUG_STACK) Slog.d(TAG_STACK,
2522 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2523 + " to createMode=" + createMode + " toTop=" + toTop);
2524 if (!task.isActivityTypeStandardOrUndefined()) {
2525 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2526 + " non-standard task " + taskId + " to split-screen windowing mode");
2527 }
2528
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002529 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002530 final int windowingMode = task.getWindowingMode();
2531 final ActivityStack stack = task.getStack();
2532 if (toTop) {
2533 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2534 }
2535 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002536 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2537 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002538 return windowingMode != task.getWindowingMode();
2539 } finally {
2540 Binder.restoreCallingIdentity(ident);
2541 }
2542 }
2543 }
2544
2545 /**
2546 * Removes stacks in the input windowing modes from the system if they are of activity type
2547 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2548 */
2549 @Override
2550 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002551 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002552 "removeStacksInWindowingModes()");
2553
2554 synchronized (mGlobalLock) {
2555 final long ident = Binder.clearCallingIdentity();
2556 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002557 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 } finally {
2559 Binder.restoreCallingIdentity(ident);
2560 }
2561 }
2562 }
2563
2564 @Override
2565 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002566 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002567 "removeStacksWithActivityTypes()");
2568
2569 synchronized (mGlobalLock) {
2570 final long ident = Binder.clearCallingIdentity();
2571 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002572 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002573 } finally {
2574 Binder.restoreCallingIdentity(ident);
2575 }
2576 }
2577 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002578
2579 @Override
2580 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2581 int userId) {
2582 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002583 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2584 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002585 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002586 final boolean detailed = checkGetTasksPermission(
2587 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2588 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002589 == PackageManager.PERMISSION_GRANTED;
2590
2591 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002592 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002593 callingUid);
2594 }
2595 }
2596
2597 @Override
2598 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002599 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002600 long ident = Binder.clearCallingIdentity();
2601 try {
2602 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002603 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002604 }
2605 } finally {
2606 Binder.restoreCallingIdentity(ident);
2607 }
2608 }
2609
2610 @Override
2611 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002612 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002613 long ident = Binder.clearCallingIdentity();
2614 try {
2615 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002616 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002617 }
2618 } finally {
2619 Binder.restoreCallingIdentity(ident);
2620 }
2621 }
2622
2623 @Override
2624 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002625 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002626 final long callingUid = Binder.getCallingUid();
2627 final long origId = Binder.clearCallingIdentity();
2628 try {
2629 synchronized (mGlobalLock) {
2630 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002631 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002632 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2633 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2634 }
2635 } finally {
2636 Binder.restoreCallingIdentity(origId);
2637 }
2638 }
2639
2640 @Override
2641 public void startLockTaskModeByToken(IBinder token) {
2642 synchronized (mGlobalLock) {
2643 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2644 if (r == null) {
2645 return;
2646 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002647 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002648 }
2649 }
2650
2651 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002652 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002653 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654 // This makes inner call to look as if it was initiated by system.
2655 long ident = Binder.clearCallingIdentity();
2656 try {
2657 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002658 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002659 MATCH_TASK_IN_STACKS_ONLY);
2660 if (task == null) {
2661 return;
2662 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002663
2664 // When starting lock task mode the stack must be in front and focused
2665 task.getStack().moveToFront("startSystemLockTaskMode");
2666 startLockTaskModeLocked(task, true /* isSystemCaller */);
2667 }
2668 } finally {
2669 Binder.restoreCallingIdentity(ident);
2670 }
2671 }
2672
2673 @Override
2674 public void stopLockTaskModeByToken(IBinder token) {
2675 synchronized (mGlobalLock) {
2676 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2677 if (r == null) {
2678 return;
2679 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002680 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002681 }
2682 }
2683
2684 /**
2685 * This API should be called by SystemUI only when user perform certain action to dismiss
2686 * lock task mode. We should only dismiss pinned lock task mode in this case.
2687 */
2688 @Override
2689 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002690 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002691 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2692 }
2693
2694 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2695 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2696 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2697 return;
2698 }
2699
Wale Ogunwaled32da472018-11-16 07:19:28 -08002700 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002701 if (stack == null || task != stack.topTask()) {
2702 throw new IllegalArgumentException("Invalid task, not in foreground");
2703 }
2704
2705 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2706 // system or a specific app.
2707 // * System-initiated requests will only start the pinned mode (screen pinning)
2708 // * App-initiated requests
2709 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2710 // - will start the pinned mode, otherwise
2711 final int callingUid = Binder.getCallingUid();
2712 long ident = Binder.clearCallingIdentity();
2713 try {
2714 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002715 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002716
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002717 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002718 } finally {
2719 Binder.restoreCallingIdentity(ident);
2720 }
2721 }
2722
2723 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2724 final int callingUid = Binder.getCallingUid();
2725 long ident = Binder.clearCallingIdentity();
2726 try {
2727 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002728 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002729 }
2730 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2731 // task and jumping straight into a call in the case of emergency call back.
2732 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2733 if (tm != null) {
2734 tm.showInCallScreen(false);
2735 }
2736 } finally {
2737 Binder.restoreCallingIdentity(ident);
2738 }
2739 }
2740
2741 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002742 public void updateLockTaskPackages(int userId, String[] packages) {
2743 final int callingUid = Binder.getCallingUid();
2744 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2745 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2746 "updateLockTaskPackages()");
2747 }
2748 synchronized (this) {
2749 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2750 + Arrays.toString(packages));
2751 getLockTaskController().updateLockTaskPackages(userId, packages);
2752 }
2753 }
2754
2755 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002756 public boolean isInLockTaskMode() {
2757 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2758 }
2759
2760 @Override
2761 public int getLockTaskModeState() {
2762 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002763 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002764 }
2765 }
2766
2767 @Override
2768 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2769 synchronized (mGlobalLock) {
2770 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2771 if (r != null) {
2772 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002773 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002775 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002776 }
2777 }
2778 }
2779
2780 @Override
2781 public Bundle getActivityOptions(IBinder token) {
2782 final long origId = Binder.clearCallingIdentity();
2783 try {
2784 synchronized (mGlobalLock) {
2785 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2786 if (r != null) {
2787 final ActivityOptions activityOptions = r.takeOptionsLocked();
2788 return activityOptions == null ? null : activityOptions.toBundle();
2789 }
2790 return null;
2791 }
2792 } finally {
2793 Binder.restoreCallingIdentity(origId);
2794 }
2795 }
2796
2797 @Override
2798 public List<IBinder> getAppTasks(String callingPackage) {
2799 int callingUid = Binder.getCallingUid();
2800 long ident = Binder.clearCallingIdentity();
2801 try {
2802 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002803 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002804 }
2805 } finally {
2806 Binder.restoreCallingIdentity(ident);
2807 }
2808 }
2809
2810 @Override
2811 public void finishVoiceTask(IVoiceInteractionSession session) {
2812 synchronized (mGlobalLock) {
2813 final long origId = Binder.clearCallingIdentity();
2814 try {
2815 // TODO: VI Consider treating local voice interactions and voice tasks
2816 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002817 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002818 } finally {
2819 Binder.restoreCallingIdentity(origId);
2820 }
2821 }
2822
2823 }
2824
2825 @Override
2826 public boolean isTopOfTask(IBinder token) {
2827 synchronized (mGlobalLock) {
2828 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002829 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 }
2831 }
2832
2833 @Override
2834 public void notifyLaunchTaskBehindComplete(IBinder token) {
2835 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2836 }
2837
2838 @Override
2839 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002840 mH.post(() -> {
2841 synchronized (mGlobalLock) {
2842 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002843 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002844 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002845 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002846 } catch (RemoteException e) {
2847 }
2848 }
2849 }
2850
2851 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002852 }
2853
2854 /** Called from an app when assist data is ready. */
2855 @Override
2856 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2857 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002858 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002859 synchronized (pae) {
2860 pae.result = extras;
2861 pae.structure = structure;
2862 pae.content = content;
2863 if (referrer != null) {
2864 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2865 }
2866 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002867 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002868 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2869 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002870 structure.setHomeActivity(pae.isHome);
2871 }
2872 pae.haveResult = true;
2873 pae.notifyAll();
2874 if (pae.intent == null && pae.receiver == null) {
2875 // Caller is just waiting for the result.
2876 return;
2877 }
2878 }
2879 // We are now ready to launch the assist activity.
2880 IAssistDataReceiver sendReceiver = null;
2881 Bundle sendBundle = null;
2882 synchronized (mGlobalLock) {
2883 buildAssistBundleLocked(pae, extras);
2884 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002885 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002886 if (!exists) {
2887 // Timed out.
2888 return;
2889 }
2890
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002891 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002892 // Caller wants result sent back to them.
2893 sendBundle = new Bundle();
2894 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2895 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2896 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2897 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2898 }
2899 }
2900 if (sendReceiver != null) {
2901 try {
2902 sendReceiver.onHandleAssistData(sendBundle);
2903 } catch (RemoteException e) {
2904 }
2905 return;
2906 }
2907
2908 final long ident = Binder.clearCallingIdentity();
2909 try {
2910 if (TextUtils.equals(pae.intent.getAction(),
2911 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2912 pae.intent.putExtras(pae.extras);
2913 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2914 } else {
2915 pae.intent.replaceExtras(pae.extras);
2916 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2917 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2918 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002919 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002920
2921 try {
2922 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2923 } catch (ActivityNotFoundException e) {
2924 Slog.w(TAG, "No activity to handle assist action.", e);
2925 }
2926 }
2927 } finally {
2928 Binder.restoreCallingIdentity(ident);
2929 }
2930 }
2931
2932 @Override
2933 public int addAppTask(IBinder activityToken, Intent intent,
2934 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2935 final int callingUid = Binder.getCallingUid();
2936 final long callingIdent = Binder.clearCallingIdentity();
2937
2938 try {
2939 synchronized (mGlobalLock) {
2940 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2941 if (r == null) {
2942 throw new IllegalArgumentException("Activity does not exist; token="
2943 + activityToken);
2944 }
2945 ComponentName comp = intent.getComponent();
2946 if (comp == null) {
2947 throw new IllegalArgumentException("Intent " + intent
2948 + " must specify explicit component");
2949 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002950 if (thumbnail.getWidth() != mThumbnailWidth
2951 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 throw new IllegalArgumentException("Bad thumbnail size: got "
2953 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002954 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002955 }
2956 if (intent.getSelector() != null) {
2957 intent.setSelector(null);
2958 }
2959 if (intent.getSourceBounds() != null) {
2960 intent.setSourceBounds(null);
2961 }
2962 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2963 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2964 // The caller has added this as an auto-remove task... that makes no
2965 // sense, so turn off auto-remove.
2966 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2967 }
2968 }
2969 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2970 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2971 if (ainfo.applicationInfo.uid != callingUid) {
2972 throw new SecurityException(
2973 "Can't add task for another application: target uid="
2974 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2975 }
2976
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002977 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002978 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002979 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002980 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002981 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002982 // The app has too many tasks already and we can't add any more
2983 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2984 return INVALID_TASK_ID;
2985 }
2986 task.lastTaskDescription.copyFrom(description);
2987
2988 // TODO: Send the thumbnail to WM to store it.
2989
2990 return task.taskId;
2991 }
2992 } finally {
2993 Binder.restoreCallingIdentity(callingIdent);
2994 }
2995 }
2996
2997 @Override
2998 public Point getAppTaskThumbnailSize() {
2999 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003000 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003001 }
3002 }
3003
3004 @Override
3005 public void setTaskResizeable(int taskId, int resizeableMode) {
3006 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003007 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003008 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3009 if (task == null) {
3010 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3011 return;
3012 }
3013 task.setResizeMode(resizeableMode);
3014 }
3015 }
3016
3017 @Override
3018 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003019 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 long ident = Binder.clearCallingIdentity();
3021 try {
3022 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003023 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003024 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003025 if (task == null) {
3026 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3027 return;
3028 }
3029 // Place the task in the right stack if it isn't there already based on
3030 // the requested bounds.
3031 // The stack transition logic is:
3032 // - a null bounds on a freeform task moves that task to fullscreen
3033 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3034 // that task to freeform
3035 // - otherwise the task is not moved
3036 ActivityStack stack = task.getStack();
3037 if (!task.getWindowConfiguration().canResizeTask()) {
3038 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3039 }
3040 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3041 stack = stack.getDisplay().getOrCreateStack(
3042 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3043 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3044 stack = stack.getDisplay().getOrCreateStack(
3045 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3046 }
3047
3048 // Reparent the task to the right stack if necessary
3049 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3050 if (stack != task.getStack()) {
3051 // Defer resume until the task is resized below
3052 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3053 DEFER_RESUME, "resizeTask");
3054 preserveWindow = false;
3055 }
3056
3057 // After reparenting (which only resizes the task to the stack bounds), resize the
3058 // task to the actual bounds provided
3059 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3060 }
3061 } finally {
3062 Binder.restoreCallingIdentity(ident);
3063 }
3064 }
3065
3066 @Override
3067 public boolean releaseActivityInstance(IBinder token) {
3068 synchronized (mGlobalLock) {
3069 final long origId = Binder.clearCallingIdentity();
3070 try {
3071 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3072 if (r == null) {
3073 return false;
3074 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003075 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003076 } finally {
3077 Binder.restoreCallingIdentity(origId);
3078 }
3079 }
3080 }
3081
3082 @Override
3083 public void releaseSomeActivities(IApplicationThread appInt) {
3084 synchronized (mGlobalLock) {
3085 final long origId = Binder.clearCallingIdentity();
3086 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003087 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003088 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003089 } finally {
3090 Binder.restoreCallingIdentity(origId);
3091 }
3092 }
3093 }
3094
3095 @Override
3096 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003097 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003098 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003099 != PackageManager.PERMISSION_GRANTED) {
3100 throw new SecurityException("Requires permission "
3101 + android.Manifest.permission.DEVICE_POWER);
3102 }
3103
3104 synchronized (mGlobalLock) {
3105 long ident = Binder.clearCallingIdentity();
3106 if (mKeyguardShown != keyguardShowing) {
3107 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003108 final Message msg = PooledLambda.obtainMessage(
3109 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3110 keyguardShowing);
3111 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003112 }
3113 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003114 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003115 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003116 } finally {
3117 Binder.restoreCallingIdentity(ident);
3118 }
3119 }
3120
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003121 mH.post(() -> {
3122 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3123 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3124 }
3125 });
3126 }
3127
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003128 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003129 mH.post(() -> {
3130 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3131 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3132 }
3133 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003134 }
3135
3136 @Override
3137 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003138 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3139 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003140
3141 final File passedIconFile = new File(filePath);
3142 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3143 passedIconFile.getName());
3144 if (!legitIconFile.getPath().equals(filePath)
3145 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3146 throw new IllegalArgumentException("Bad file path: " + filePath
3147 + " passed for userId " + userId);
3148 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003149 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003150 }
3151
3152 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003153 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003154 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3155 final ActivityOptions activityOptions = safeOptions != null
3156 ? safeOptions.getOptions(mStackSupervisor)
3157 : null;
3158 if (activityOptions == null
3159 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3160 || activityOptions.getCustomInPlaceResId() == 0) {
3161 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3162 "with valid animation");
3163 }
lumark588a3e82018-07-20 18:53:54 +08003164 // Get top display of front most application.
3165 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3166 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003167 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3168 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3169 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003170 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003171 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003172 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 }
3174
3175 @Override
3176 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003177 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003178 synchronized (mGlobalLock) {
3179 final long ident = Binder.clearCallingIdentity();
3180 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003181 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 if (stack == null) {
3183 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3184 return;
3185 }
3186 if (!stack.isActivityTypeStandardOrUndefined()) {
3187 throw new IllegalArgumentException(
3188 "Removing non-standard stack is not allowed.");
3189 }
3190 mStackSupervisor.removeStack(stack);
3191 } finally {
3192 Binder.restoreCallingIdentity(ident);
3193 }
3194 }
3195 }
3196
3197 @Override
3198 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003199 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003200
3201 synchronized (mGlobalLock) {
3202 final long ident = Binder.clearCallingIdentity();
3203 try {
3204 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3205 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003206 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003207 } finally {
3208 Binder.restoreCallingIdentity(ident);
3209 }
3210 }
3211 }
3212
3213 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 public void exitFreeformMode(IBinder token) {
3215 synchronized (mGlobalLock) {
3216 long ident = Binder.clearCallingIdentity();
3217 try {
3218 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3219 if (r == null) {
3220 throw new IllegalArgumentException(
3221 "exitFreeformMode: No activity record matching token=" + token);
3222 }
3223
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003224 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003225 if (stack == null || !stack.inFreeformWindowingMode()) {
3226 throw new IllegalStateException(
3227 "exitFreeformMode: You can only go fullscreen from freeform.");
3228 }
3229
3230 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3231 } finally {
3232 Binder.restoreCallingIdentity(ident);
3233 }
3234 }
3235 }
3236
3237 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3238 @Override
3239 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003240 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003242 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 }
3244
3245 /** Unregister a task stack listener so that it stops receiving callbacks. */
3246 @Override
3247 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003248 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003249 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003250 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 }
3252
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253 @Override
3254 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3255 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3256 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3257 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3258 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3259 }
3260
3261 @Override
3262 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3263 IBinder activityToken, int flags) {
3264 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3265 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3266 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3267 }
3268
3269 @Override
3270 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3271 Bundle args) {
3272 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3273 true /* focused */, true /* newSessionId */, userHandle, args,
3274 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3275 }
3276
3277 @Override
3278 public Bundle getAssistContextExtras(int requestType) {
3279 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3280 null, null, true /* focused */, true /* newSessionId */,
3281 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3282 if (pae == null) {
3283 return null;
3284 }
3285 synchronized (pae) {
3286 while (!pae.haveResult) {
3287 try {
3288 pae.wait();
3289 } catch (InterruptedException e) {
3290 }
3291 }
3292 }
3293 synchronized (mGlobalLock) {
3294 buildAssistBundleLocked(pae, pae.result);
3295 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003296 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003297 }
3298 return pae.extras;
3299 }
3300
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003301 /**
3302 * Binder IPC calls go through the public entry point.
3303 * This can be called with or without the global lock held.
3304 */
3305 private static int checkCallingPermission(String permission) {
3306 return checkPermission(
3307 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3308 }
3309
3310 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003311 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003312 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3313 mAmInternal.enforceCallingPermission(permission, func);
3314 }
3315 }
3316
3317 @VisibleForTesting
3318 int checkGetTasksPermission(String permission, int pid, int uid) {
3319 return checkPermission(permission, pid, uid);
3320 }
3321
3322 static int checkPermission(String permission, int pid, int uid) {
3323 if (permission == null) {
3324 return PackageManager.PERMISSION_DENIED;
3325 }
3326 return checkComponentPermission(permission, pid, uid, -1, true);
3327 }
3328
Wale Ogunwale214f3482018-10-04 11:00:47 -07003329 public static int checkComponentPermission(String permission, int pid, int uid,
3330 int owningUid, boolean exported) {
3331 return ActivityManagerService.checkComponentPermission(
3332 permission, pid, uid, owningUid, exported);
3333 }
3334
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003335 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3336 if (getRecentTasks().isCallerRecents(callingUid)) {
3337 // Always allow the recents component to get tasks
3338 return true;
3339 }
3340
3341 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3342 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3343 if (!allowed) {
3344 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3345 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3346 // Temporary compatibility: some existing apps on the system image may
3347 // still be requesting the old permission and not switched to the new
3348 // one; if so, we'll still allow them full access. This means we need
3349 // to see if they are holding the old permission and are a system app.
3350 try {
3351 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3352 allowed = true;
3353 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3354 + " is using old GET_TASKS but privileged; allowing");
3355 }
3356 } catch (RemoteException e) {
3357 }
3358 }
3359 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3360 + " does not hold REAL_GET_TASKS; limiting output");
3361 }
3362 return allowed;
3363 }
3364
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003365 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3366 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3367 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3368 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003369 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003370 "enqueueAssistContext()");
3371
3372 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003373 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003374 if (activity == null) {
3375 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3376 return null;
3377 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003378 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003379 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3380 return null;
3381 }
3382 if (focused) {
3383 if (activityToken != null) {
3384 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3385 if (activity != caller) {
3386 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3387 + " is not current top " + activity);
3388 return null;
3389 }
3390 }
3391 } else {
3392 activity = ActivityRecord.forTokenLocked(activityToken);
3393 if (activity == null) {
3394 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3395 + " couldn't be found");
3396 return null;
3397 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003398 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003399 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3400 return null;
3401 }
3402 }
3403
3404 PendingAssistExtras pae;
3405 Bundle extras = new Bundle();
3406 if (args != null) {
3407 extras.putAll(args);
3408 }
3409 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003410 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003411
3412 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3413 userHandle);
3414 pae.isHome = activity.isActivityTypeHome();
3415
3416 // Increment the sessionId if necessary
3417 if (newSessionId) {
3418 mViSessionId++;
3419 }
3420 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003421 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3422 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003423 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003424 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 } catch (RemoteException e) {
3426 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3427 return null;
3428 }
3429 return pae;
3430 }
3431 }
3432
3433 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3434 if (result != null) {
3435 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3436 }
3437 if (pae.hint != null) {
3438 pae.extras.putBoolean(pae.hint, true);
3439 }
3440 }
3441
3442 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3443 IAssistDataReceiver receiver;
3444 synchronized (mGlobalLock) {
3445 mPendingAssistExtras.remove(pae);
3446 receiver = pae.receiver;
3447 }
3448 if (receiver != null) {
3449 // Caller wants result sent back to them.
3450 Bundle sendBundle = new Bundle();
3451 // At least return the receiver extras
3452 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3453 try {
3454 pae.receiver.onHandleAssistData(sendBundle);
3455 } catch (RemoteException e) {
3456 }
3457 }
3458 }
3459
3460 public class PendingAssistExtras extends Binder implements Runnable {
3461 public final ActivityRecord activity;
3462 public boolean isHome;
3463 public final Bundle extras;
3464 public final Intent intent;
3465 public final String hint;
3466 public final IAssistDataReceiver receiver;
3467 public final int userHandle;
3468 public boolean haveResult = false;
3469 public Bundle result = null;
3470 public AssistStructure structure = null;
3471 public AssistContent content = null;
3472 public Bundle receiverExtras;
3473
3474 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3475 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3476 int _userHandle) {
3477 activity = _activity;
3478 extras = _extras;
3479 intent = _intent;
3480 hint = _hint;
3481 receiver = _receiver;
3482 receiverExtras = _receiverExtras;
3483 userHandle = _userHandle;
3484 }
3485
3486 @Override
3487 public void run() {
3488 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3489 synchronized (this) {
3490 haveResult = true;
3491 notifyAll();
3492 }
3493 pendingAssistExtrasTimedOut(this);
3494 }
3495 }
3496
3497 @Override
3498 public boolean isAssistDataAllowedOnCurrentActivity() {
3499 int userId;
3500 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003501 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003502 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3503 return false;
3504 }
3505
3506 final ActivityRecord activity = focusedStack.getTopActivity();
3507 if (activity == null) {
3508 return false;
3509 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003510 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003511 }
3512 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3513 }
3514
3515 @Override
3516 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3517 long ident = Binder.clearCallingIdentity();
3518 try {
3519 synchronized (mGlobalLock) {
3520 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003521 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003522 if (top != caller) {
3523 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3524 + " is not current top " + top);
3525 return false;
3526 }
3527 if (!top.nowVisible) {
3528 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3529 + " is not visible");
3530 return false;
3531 }
3532 }
3533 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3534 token);
3535 } finally {
3536 Binder.restoreCallingIdentity(ident);
3537 }
3538 }
3539
3540 @Override
3541 public boolean isRootVoiceInteraction(IBinder token) {
3542 synchronized (mGlobalLock) {
3543 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3544 if (r == null) {
3545 return false;
3546 }
3547 return r.rootVoiceInteraction;
3548 }
3549 }
3550
Wale Ogunwalef6733932018-06-27 05:14:34 -07003551 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3552 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3553 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3554 if (activityToCallback == null) return;
3555 activityToCallback.setVoiceSessionLocked(voiceSession);
3556
3557 // Inform the activity
3558 try {
3559 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3560 voiceInteractor);
3561 long token = Binder.clearCallingIdentity();
3562 try {
3563 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3564 } finally {
3565 Binder.restoreCallingIdentity(token);
3566 }
3567 // TODO: VI Should we cache the activity so that it's easier to find later
3568 // rather than scan through all the stacks and activities?
3569 } catch (RemoteException re) {
3570 activityToCallback.clearVoiceSessionLocked();
3571 // TODO: VI Should this terminate the voice session?
3572 }
3573 }
3574
3575 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3576 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3577 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3578 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3579 boolean wasRunningVoice = mRunningVoice != null;
3580 mRunningVoice = session;
3581 if (!wasRunningVoice) {
3582 mVoiceWakeLock.acquire();
3583 updateSleepIfNeededLocked();
3584 }
3585 }
3586 }
3587
3588 void finishRunningVoiceLocked() {
3589 if (mRunningVoice != null) {
3590 mRunningVoice = null;
3591 mVoiceWakeLock.release();
3592 updateSleepIfNeededLocked();
3593 }
3594 }
3595
3596 @Override
3597 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3598 synchronized (mGlobalLock) {
3599 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3600 if (keepAwake) {
3601 mVoiceWakeLock.acquire();
3602 } else {
3603 mVoiceWakeLock.release();
3604 }
3605 }
3606 }
3607 }
3608
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003609 @Override
3610 public ComponentName getActivityClassForToken(IBinder token) {
3611 synchronized (mGlobalLock) {
3612 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3613 if (r == null) {
3614 return null;
3615 }
3616 return r.intent.getComponent();
3617 }
3618 }
3619
3620 @Override
3621 public String getPackageForToken(IBinder token) {
3622 synchronized (mGlobalLock) {
3623 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3624 if (r == null) {
3625 return null;
3626 }
3627 return r.packageName;
3628 }
3629 }
3630
3631 @Override
3632 public void showLockTaskEscapeMessage(IBinder token) {
3633 synchronized (mGlobalLock) {
3634 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3635 if (r == null) {
3636 return;
3637 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003638 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003639 }
3640 }
3641
3642 @Override
3643 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003644 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003645 final long token = Binder.clearCallingIdentity();
3646 try {
3647 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003648 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003649 }
3650 } finally {
3651 Binder.restoreCallingIdentity(token);
3652 }
3653 }
3654
3655 /**
3656 * Try to place task to provided position. The final position might be different depending on
3657 * current user and stacks state. The task will be moved to target stack if it's currently in
3658 * different stack.
3659 */
3660 @Override
3661 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003662 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003663 synchronized (mGlobalLock) {
3664 long ident = Binder.clearCallingIdentity();
3665 try {
3666 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3667 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003668 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003669 if (task == null) {
3670 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3671 + taskId);
3672 }
3673
Wale Ogunwaled32da472018-11-16 07:19:28 -08003674 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003675
3676 if (stack == null) {
3677 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3678 + stackId);
3679 }
3680 if (!stack.isActivityTypeStandardOrUndefined()) {
3681 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3682 + " the position of task " + taskId + " in/to non-standard stack");
3683 }
3684
3685 // TODO: Have the callers of this API call a separate reparent method if that is
3686 // what they intended to do vs. having this method also do reparenting.
3687 if (task.getStack() == stack) {
3688 // Change position in current stack.
3689 stack.positionChildAt(task, position);
3690 } else {
3691 // Reparent to new stack.
3692 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3693 !DEFER_RESUME, "positionTaskInStack");
3694 }
3695 } finally {
3696 Binder.restoreCallingIdentity(ident);
3697 }
3698 }
3699 }
3700
3701 @Override
3702 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3703 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3704 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3705 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3706 synchronized (mGlobalLock) {
3707 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3708 if (record == null) {
3709 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3710 + "found for: " + token);
3711 }
3712 record.setSizeConfigurations(horizontalSizeConfiguration,
3713 verticalSizeConfigurations, smallestSizeConfigurations);
3714 }
3715 }
3716
3717 /**
3718 * Dismisses split-screen multi-window mode.
3719 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3720 */
3721 @Override
3722 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003723 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003724 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3725 final long ident = Binder.clearCallingIdentity();
3726 try {
3727 synchronized (mGlobalLock) {
3728 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003729 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003730 if (stack == null) {
3731 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3732 return;
3733 }
3734
3735 if (toTop) {
3736 // Caller wants the current split-screen primary stack to be the top stack after
3737 // it goes fullscreen, so move it to the front.
3738 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003739 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 // In this case the current split-screen primary stack shouldn't be the top
3741 // stack after it goes fullscreen, but it current has focus, so we move the
3742 // focus to the top-most split-screen secondary stack next to it.
3743 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3744 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3745 if (otherStack != null) {
3746 otherStack.moveToFront("dismissSplitScreenMode_other");
3747 }
3748 }
3749
Evan Rosky10475742018-09-05 19:02:48 -07003750 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003751 }
3752 } finally {
3753 Binder.restoreCallingIdentity(ident);
3754 }
3755 }
3756
3757 /**
3758 * Dismisses Pip
3759 * @param animate True if the dismissal should be animated.
3760 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3761 * default animation duration should be used.
3762 */
3763 @Override
3764 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003765 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003766 final long ident = Binder.clearCallingIdentity();
3767 try {
3768 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003769 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003770 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003771 if (stack == null) {
3772 Slog.w(TAG, "dismissPip: pinned stack not found.");
3773 return;
3774 }
3775 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3776 throw new IllegalArgumentException("Stack: " + stack
3777 + " doesn't support animated resize.");
3778 }
3779 if (animate) {
3780 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3781 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3782 } else {
3783 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3784 }
3785 }
3786 } finally {
3787 Binder.restoreCallingIdentity(ident);
3788 }
3789 }
3790
3791 @Override
3792 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003793 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003794 synchronized (mGlobalLock) {
3795 mSuppressResizeConfigChanges = suppress;
3796 }
3797 }
3798
3799 /**
3800 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3801 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3802 * activity and clearing the task at the same time.
3803 */
3804 @Override
3805 // TODO: API should just be about changing windowing modes...
3806 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003807 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 "moveTasksToFullscreenStack()");
3809 synchronized (mGlobalLock) {
3810 final long origId = Binder.clearCallingIdentity();
3811 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003812 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003813 if (stack != null){
3814 if (!stack.isActivityTypeStandardOrUndefined()) {
3815 throw new IllegalArgumentException(
3816 "You can't move tasks from non-standard stacks.");
3817 }
3818 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3819 }
3820 } finally {
3821 Binder.restoreCallingIdentity(origId);
3822 }
3823 }
3824 }
3825
3826 /**
3827 * Moves the top activity in the input stackId to the pinned stack.
3828 *
3829 * @param stackId Id of stack to move the top activity to pinned stack.
3830 * @param bounds Bounds to use for pinned stack.
3831 *
3832 * @return True if the top activity of the input stack was successfully moved to the pinned
3833 * stack.
3834 */
3835 @Override
3836 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003837 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003838 "moveTopActivityToPinnedStack()");
3839 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003840 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003841 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3842 + "Device doesn't support picture-in-picture mode");
3843 }
3844
3845 long ident = Binder.clearCallingIdentity();
3846 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003847 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003848 } finally {
3849 Binder.restoreCallingIdentity(ident);
3850 }
3851 }
3852 }
3853
3854 @Override
3855 public boolean isInMultiWindowMode(IBinder token) {
3856 final long origId = Binder.clearCallingIdentity();
3857 try {
3858 synchronized (mGlobalLock) {
3859 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3860 if (r == null) {
3861 return false;
3862 }
3863 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3864 return r.inMultiWindowMode();
3865 }
3866 } finally {
3867 Binder.restoreCallingIdentity(origId);
3868 }
3869 }
3870
3871 @Override
3872 public boolean isInPictureInPictureMode(IBinder token) {
3873 final long origId = Binder.clearCallingIdentity();
3874 try {
3875 synchronized (mGlobalLock) {
3876 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3877 }
3878 } finally {
3879 Binder.restoreCallingIdentity(origId);
3880 }
3881 }
3882
3883 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003884 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3885 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003886 return false;
3887 }
3888
3889 // If we are animating to fullscreen then we have already dispatched the PIP mode
3890 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003891 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3892 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 }
3894
3895 @Override
3896 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3897 final long origId = Binder.clearCallingIdentity();
3898 try {
3899 synchronized (mGlobalLock) {
3900 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3901 "enterPictureInPictureMode", token, params);
3902
3903 // If the activity is already in picture in picture mode, then just return early
3904 if (isInPictureInPictureMode(r)) {
3905 return true;
3906 }
3907
3908 // Activity supports picture-in-picture, now check that we can enter PiP at this
3909 // point, if it is
3910 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3911 false /* beforeStopping */)) {
3912 return false;
3913 }
3914
3915 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003916 synchronized (mGlobalLock) {
3917 // Only update the saved args from the args that are set
3918 r.pictureInPictureArgs.copyOnlySet(params);
3919 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3920 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3921 // Adjust the source bounds by the insets for the transition down
3922 final Rect sourceBounds = new Rect(
3923 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003924 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003925 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003926 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003927 stack.setPictureInPictureAspectRatio(aspectRatio);
3928 stack.setPictureInPictureActions(actions);
3929 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3930 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3931 logPictureInPictureArgs(params);
3932 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003933 };
3934
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003935 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003936 // If the keyguard is showing or occluded, then try and dismiss it before
3937 // entering picture-in-picture (this will prompt the user to authenticate if the
3938 // device is currently locked).
3939 dismissKeyguard(token, new KeyguardDismissCallback() {
3940 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003941 public void onDismissSucceeded() {
3942 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003943 }
3944 }, null /* message */);
3945 } else {
3946 // Enter picture in picture immediately otherwise
3947 enterPipRunnable.run();
3948 }
3949 return true;
3950 }
3951 } finally {
3952 Binder.restoreCallingIdentity(origId);
3953 }
3954 }
3955
3956 @Override
3957 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3958 final long origId = Binder.clearCallingIdentity();
3959 try {
3960 synchronized (mGlobalLock) {
3961 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3962 "setPictureInPictureParams", token, params);
3963
3964 // Only update the saved args from the args that are set
3965 r.pictureInPictureArgs.copyOnlySet(params);
3966 if (r.inPinnedWindowingMode()) {
3967 // If the activity is already in picture-in-picture, update the pinned stack now
3968 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3969 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003970 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 if (!stack.isAnimatingBoundsToFullscreen()) {
3972 stack.setPictureInPictureAspectRatio(
3973 r.pictureInPictureArgs.getAspectRatio());
3974 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3975 }
3976 }
3977 logPictureInPictureArgs(params);
3978 }
3979 } finally {
3980 Binder.restoreCallingIdentity(origId);
3981 }
3982 }
3983
3984 @Override
3985 public int getMaxNumPictureInPictureActions(IBinder token) {
3986 // Currently, this is a static constant, but later, we may change this to be dependent on
3987 // the context of the activity
3988 return 3;
3989 }
3990
3991 private void logPictureInPictureArgs(PictureInPictureParams params) {
3992 if (params.hasSetActions()) {
3993 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3994 params.getActions().size());
3995 }
3996 if (params.hasSetAspectRatio()) {
3997 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3998 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3999 MetricsLogger.action(lm);
4000 }
4001 }
4002
4003 /**
4004 * Checks the state of the system and the activity associated with the given {@param token} to
4005 * verify that picture-in-picture is supported for that activity.
4006 *
4007 * @return the activity record for the given {@param token} if all the checks pass.
4008 */
4009 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4010 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004011 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004012 throw new IllegalStateException(caller
4013 + ": Device doesn't support picture-in-picture mode.");
4014 }
4015
4016 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4017 if (r == null) {
4018 throw new IllegalStateException(caller
4019 + ": Can't find activity for token=" + token);
4020 }
4021
4022 if (!r.supportsPictureInPicture()) {
4023 throw new IllegalStateException(caller
4024 + ": Current activity does not support picture-in-picture.");
4025 }
4026
4027 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004028 && !mWindowManager.isValidPictureInPictureAspectRatio(
4029 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004030 final float minAspectRatio = mContext.getResources().getFloat(
4031 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4032 final float maxAspectRatio = mContext.getResources().getFloat(
4033 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4034 throw new IllegalArgumentException(String.format(caller
4035 + ": Aspect ratio is too extreme (must be between %f and %f).",
4036 minAspectRatio, maxAspectRatio));
4037 }
4038
4039 // Truncate the number of actions if necessary
4040 params.truncateActions(getMaxNumPictureInPictureActions(token));
4041
4042 return r;
4043 }
4044
4045 @Override
4046 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004047 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004048 synchronized (mGlobalLock) {
4049 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4050 if (r == null) {
4051 throw new IllegalArgumentException("Activity does not exist; token="
4052 + activityToken);
4053 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004054 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004055 }
4056 }
4057
4058 @Override
4059 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4060 Rect tempDockedTaskInsetBounds,
4061 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004062 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004063 long ident = Binder.clearCallingIdentity();
4064 try {
4065 synchronized (mGlobalLock) {
4066 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4067 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4068 PRESERVE_WINDOWS);
4069 }
4070 } finally {
4071 Binder.restoreCallingIdentity(ident);
4072 }
4073 }
4074
4075 @Override
4076 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004077 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004078 final long ident = Binder.clearCallingIdentity();
4079 try {
4080 synchronized (mGlobalLock) {
4081 mStackSupervisor.setSplitScreenResizing(resizing);
4082 }
4083 } finally {
4084 Binder.restoreCallingIdentity(ident);
4085 }
4086 }
4087
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004088 /**
4089 * Check that we have the features required for VR-related API calls, and throw an exception if
4090 * not.
4091 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004092 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004093 if (!mContext.getPackageManager().hasSystemFeature(
4094 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4095 throw new UnsupportedOperationException("VR mode not supported on this device!");
4096 }
4097 }
4098
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004099 @Override
4100 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004101 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004102
4103 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4104
4105 ActivityRecord r;
4106 synchronized (mGlobalLock) {
4107 r = ActivityRecord.isInStackLocked(token);
4108 }
4109
4110 if (r == null) {
4111 throw new IllegalArgumentException();
4112 }
4113
4114 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004115 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004116 VrManagerInternal.NO_ERROR) {
4117 return err;
4118 }
4119
4120 // Clear the binder calling uid since this path may call moveToTask().
4121 final long callingId = Binder.clearCallingIdentity();
4122 try {
4123 synchronized (mGlobalLock) {
4124 r.requestedVrComponent = (enabled) ? packageName : null;
4125
4126 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004127 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004128 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004129 }
4130 return 0;
4131 }
4132 } finally {
4133 Binder.restoreCallingIdentity(callingId);
4134 }
4135 }
4136
4137 @Override
4138 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4139 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4140 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004141 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004142 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4143 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4144 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004145 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004146 || activity.voiceSession != null) {
4147 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4148 return;
4149 }
4150 if (activity.pendingVoiceInteractionStart) {
4151 Slog.w(TAG, "Pending start of voice interaction already.");
4152 return;
4153 }
4154 activity.pendingVoiceInteractionStart = true;
4155 }
4156 LocalServices.getService(VoiceInteractionManagerInternal.class)
4157 .startLocalVoiceInteraction(callingActivity, options);
4158 }
4159
4160 @Override
4161 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4162 LocalServices.getService(VoiceInteractionManagerInternal.class)
4163 .stopLocalVoiceInteraction(callingActivity);
4164 }
4165
4166 @Override
4167 public boolean supportsLocalVoiceInteraction() {
4168 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4169 .supportsLocalVoiceInteraction();
4170 }
4171
4172 /** Notifies all listeners when the pinned stack animation starts. */
4173 @Override
4174 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004175 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004176 }
4177
4178 /** Notifies all listeners when the pinned stack animation ends. */
4179 @Override
4180 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004181 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004182 }
4183
4184 @Override
4185 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004186 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 final long ident = Binder.clearCallingIdentity();
4188 try {
4189 synchronized (mGlobalLock) {
4190 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4191 }
4192 } finally {
4193 Binder.restoreCallingIdentity(ident);
4194 }
4195 }
4196
4197 @Override
4198 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004199 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004200
4201 synchronized (mGlobalLock) {
4202 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004203 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004204 // Call might come when display is not yet added or has already been removed.
4205 if (DEBUG_CONFIGURATION) {
4206 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4207 + displayId);
4208 }
4209 return false;
4210 }
4211
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004212 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004213 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004214 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 }
4216
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004217 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004218 final Message msg = PooledLambda.obtainMessage(
4219 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4220 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004221 }
4222
4223 final long origId = Binder.clearCallingIdentity();
4224 try {
4225 if (values != null) {
4226 Settings.System.clearConfiguration(values);
4227 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004228 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004229 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4230 return mTmpUpdateConfigurationResult.changes != 0;
4231 } finally {
4232 Binder.restoreCallingIdentity(origId);
4233 }
4234 }
4235 }
4236
4237 @Override
4238 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004239 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004240
4241 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004242 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004243 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 }
4246
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004247 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004248 final Message msg = PooledLambda.obtainMessage(
4249 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4250 DEFAULT_DISPLAY);
4251 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004252 }
4253
4254 final long origId = Binder.clearCallingIdentity();
4255 try {
4256 if (values != null) {
4257 Settings.System.clearConfiguration(values);
4258 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004259 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004260 UserHandle.USER_NULL, false /* deferResume */,
4261 mTmpUpdateConfigurationResult);
4262 return mTmpUpdateConfigurationResult.changes != 0;
4263 } finally {
4264 Binder.restoreCallingIdentity(origId);
4265 }
4266 }
4267 }
4268
4269 @Override
4270 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4271 CharSequence message) {
4272 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004273 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004274 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4275 }
4276 final long callingId = Binder.clearCallingIdentity();
4277 try {
4278 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004279 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004280 }
4281 } finally {
4282 Binder.restoreCallingIdentity(callingId);
4283 }
4284 }
4285
4286 @Override
4287 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004288 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004289 "cancelTaskWindowTransition()");
4290 final long ident = Binder.clearCallingIdentity();
4291 try {
4292 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004293 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 MATCH_TASK_IN_STACKS_ONLY);
4295 if (task == null) {
4296 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4297 return;
4298 }
4299 task.cancelWindowTransition();
4300 }
4301 } finally {
4302 Binder.restoreCallingIdentity(ident);
4303 }
4304 }
4305
4306 @Override
4307 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004308 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004309 final long ident = Binder.clearCallingIdentity();
4310 try {
4311 final TaskRecord task;
4312 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004313 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4315 if (task == null) {
4316 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4317 return null;
4318 }
4319 }
4320 // Don't call this while holding the lock as this operation might hit the disk.
4321 return task.getSnapshot(reducedResolution);
4322 } finally {
4323 Binder.restoreCallingIdentity(ident);
4324 }
4325 }
4326
4327 @Override
4328 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4329 synchronized (mGlobalLock) {
4330 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4331 if (r == null) {
4332 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4333 + token);
4334 return;
4335 }
4336 final long origId = Binder.clearCallingIdentity();
4337 try {
4338 r.setDisablePreviewScreenshots(disable);
4339 } finally {
4340 Binder.restoreCallingIdentity(origId);
4341 }
4342 }
4343 }
4344
4345 /** Return the user id of the last resumed activity. */
4346 @Override
4347 public @UserIdInt
4348 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004349 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004350 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4351 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004352 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004353 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004354 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004355 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 }
4357 }
4358
4359 @Override
4360 public void updateLockTaskFeatures(int userId, int flags) {
4361 final int callingUid = Binder.getCallingUid();
4362 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004363 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004364 "updateLockTaskFeatures()");
4365 }
4366 synchronized (mGlobalLock) {
4367 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4368 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004369 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004370 }
4371 }
4372
4373 @Override
4374 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4375 synchronized (mGlobalLock) {
4376 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4377 if (r == null) {
4378 return;
4379 }
4380 final long origId = Binder.clearCallingIdentity();
4381 try {
4382 r.setShowWhenLocked(showWhenLocked);
4383 } finally {
4384 Binder.restoreCallingIdentity(origId);
4385 }
4386 }
4387 }
4388
4389 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004390 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4391 synchronized (mGlobalLock) {
4392 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4393 if (r == null) {
4394 return;
4395 }
4396 final long origId = Binder.clearCallingIdentity();
4397 try {
4398 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4399 } finally {
4400 Binder.restoreCallingIdentity(origId);
4401 }
4402 }
4403 }
4404
4405 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004406 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4407 synchronized (mGlobalLock) {
4408 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4409 if (r == null) {
4410 return;
4411 }
4412 final long origId = Binder.clearCallingIdentity();
4413 try {
4414 r.setTurnScreenOn(turnScreenOn);
4415 } finally {
4416 Binder.restoreCallingIdentity(origId);
4417 }
4418 }
4419 }
4420
4421 @Override
4422 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004423 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004424 "registerRemoteAnimations");
4425 definition.setCallingPid(Binder.getCallingPid());
4426 synchronized (mGlobalLock) {
4427 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4428 if (r == null) {
4429 return;
4430 }
4431 final long origId = Binder.clearCallingIdentity();
4432 try {
4433 r.registerRemoteAnimations(definition);
4434 } finally {
4435 Binder.restoreCallingIdentity(origId);
4436 }
4437 }
4438 }
4439
4440 @Override
4441 public void registerRemoteAnimationForNextActivityStart(String packageName,
4442 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004444 "registerRemoteAnimationForNextActivityStart");
4445 adapter.setCallingPid(Binder.getCallingPid());
4446 synchronized (mGlobalLock) {
4447 final long origId = Binder.clearCallingIdentity();
4448 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004449 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004450 packageName, adapter);
4451 } finally {
4452 Binder.restoreCallingIdentity(origId);
4453 }
4454 }
4455 }
4456
Evan Rosky966759f2019-01-15 10:33:58 -08004457 @Override
4458 public void registerRemoteAnimationsForDisplay(int displayId,
4459 RemoteAnimationDefinition definition) {
4460 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4461 "registerRemoteAnimations");
4462 definition.setCallingPid(Binder.getCallingPid());
4463 synchronized (mGlobalLock) {
4464 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4465 if (display == null) {
4466 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4467 return;
4468 }
4469 final long origId = Binder.clearCallingIdentity();
4470 try {
4471 display.mDisplayContent.registerRemoteAnimations(definition);
4472 } finally {
4473 Binder.restoreCallingIdentity(origId);
4474 }
4475 }
4476 }
4477
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004478 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4479 @Override
4480 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4481 synchronized (mGlobalLock) {
4482 final long origId = Binder.clearCallingIdentity();
4483 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004484 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004485 } finally {
4486 Binder.restoreCallingIdentity(origId);
4487 }
4488 }
4489 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004490
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004491 @Override
4492 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004493 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004494 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004495 final int pid = Binder.getCallingPid();
4496 final WindowProcessController wpc = mPidMap.get(pid);
4497 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004498 }
4499 }
4500
4501 @Override
4502 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004503 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004504 != PERMISSION_GRANTED) {
4505 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4506 + Binder.getCallingPid()
4507 + ", uid=" + Binder.getCallingUid()
4508 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4509 Slog.w(TAG, msg);
4510 throw new SecurityException(msg);
4511 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004512 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004513 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004514 final int pid = Binder.getCallingPid();
4515 final WindowProcessController proc = mPidMap.get(pid);
4516 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004517 }
4518 }
4519
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004520 @Override
4521 public void stopAppSwitches() {
4522 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4523 synchronized (mGlobalLock) {
4524 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4525 mDidAppSwitch = false;
4526 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4527 }
4528 }
4529
4530 @Override
4531 public void resumeAppSwitches() {
4532 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4533 synchronized (mGlobalLock) {
4534 // Note that we don't execute any pending app switches... we will
4535 // let those wait until either the timeout, or the next start
4536 // activity request.
4537 mAppSwitchesAllowedTime = 0;
4538 }
4539 }
4540
4541 void onStartActivitySetDidAppSwitch() {
4542 if (mDidAppSwitch) {
4543 // This is the second allowed switch since we stopped switches, so now just generally
4544 // allow switches. Use case:
4545 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4546 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4547 // anyone to switch again).
4548 mAppSwitchesAllowedTime = 0;
4549 } else {
4550 mDidAppSwitch = true;
4551 }
4552 }
4553
4554 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004555 boolean shouldDisableNonVrUiLocked() {
4556 return mVrController.shouldDisableNonVrUiLocked();
4557 }
4558
Wale Ogunwale53783742018-09-16 10:21:51 -07004559 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004560 // VR apps are expected to run in a main display. If an app is turning on VR for
4561 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4562 // fullscreen stack before enabling VR Mode.
4563 // TODO: The goal of this code is to keep the VR app on the main display. When the
4564 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4565 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4566 // option would be a better choice here.
4567 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4568 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4569 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004570 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004571 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004572 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004573 }
4574 mH.post(() -> {
4575 if (!mVrController.onVrModeChanged(r)) {
4576 return;
4577 }
4578 synchronized (mGlobalLock) {
4579 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4580 mWindowManager.disableNonVrUi(disableNonVrUi);
4581 if (disableNonVrUi) {
4582 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4583 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004584 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004585 }
4586 }
4587 });
4588 }
4589
Wale Ogunwale53783742018-09-16 10:21:51 -07004590 @Override
4591 public int getPackageScreenCompatMode(String packageName) {
4592 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4593 synchronized (mGlobalLock) {
4594 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4595 }
4596 }
4597
4598 @Override
4599 public void setPackageScreenCompatMode(String packageName, int mode) {
4600 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4601 "setPackageScreenCompatMode");
4602 synchronized (mGlobalLock) {
4603 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4604 }
4605 }
4606
4607 @Override
4608 public boolean getPackageAskScreenCompat(String packageName) {
4609 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4610 synchronized (mGlobalLock) {
4611 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4612 }
4613 }
4614
4615 @Override
4616 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4617 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4618 "setPackageAskScreenCompat");
4619 synchronized (mGlobalLock) {
4620 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4621 }
4622 }
4623
Wale Ogunwale64258362018-10-16 15:13:37 -07004624 public static String relaunchReasonToString(int relaunchReason) {
4625 switch (relaunchReason) {
4626 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4627 return "window_resize";
4628 case RELAUNCH_REASON_FREE_RESIZE:
4629 return "free_resize";
4630 default:
4631 return null;
4632 }
4633 }
4634
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004635 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004636 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004637 }
4638
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004639 /** Pokes the task persister. */
4640 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4641 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4642 }
4643
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004644 boolean isKeyguardLocked() {
4645 return mKeyguardController.isKeyguardLocked();
4646 }
4647
Garfield Tan01548632018-11-27 10:15:48 -08004648 /**
4649 * Clears launch params for the given package.
4650 * @param packageNames the names of the packages of which the launch params are to be cleared
4651 */
4652 @Override
4653 public void clearLaunchParamsForPackages(List<String> packageNames) {
4654 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4655 "clearLaunchParamsForPackages");
4656 synchronized (mGlobalLock) {
4657 for (int i = 0; i < packageNames.size(); ++i) {
4658 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4659 }
4660 }
4661 }
4662
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004663 /**
4664 * Makes the display with the given id a single task instance display. I.e the display can only
4665 * contain one task.
4666 */
4667 @Override
4668 public void setDisplayToSingleTaskInstance(int displayId) {
4669 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4670 "setDisplayToSingleTaskInstance");
4671 final long origId = Binder.clearCallingIdentity();
4672 try {
4673 final ActivityDisplay display =
4674 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4675 if (display != null) {
4676 display.setDisplayToSingleTaskInstance();
4677 }
4678 } finally {
4679 Binder.restoreCallingIdentity(origId);
4680 }
4681 }
4682
Wale Ogunwale31913b52018-10-13 08:29:31 -07004683 void dumpLastANRLocked(PrintWriter pw) {
4684 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4685 if (mLastANRState == null) {
4686 pw.println(" <no ANR has occurred since boot>");
4687 } else {
4688 pw.println(mLastANRState);
4689 }
4690 }
4691
4692 void dumpLastANRTracesLocked(PrintWriter pw) {
4693 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4694
4695 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4696 if (ArrayUtils.isEmpty(files)) {
4697 pw.println(" <no ANR has occurred since boot>");
4698 return;
4699 }
4700 // Find the latest file.
4701 File latest = null;
4702 for (File f : files) {
4703 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4704 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004705 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004706 }
4707 pw.print("File: ");
4708 pw.print(latest.getName());
4709 pw.println();
4710 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4711 String line;
4712 while ((line = in.readLine()) != null) {
4713 pw.println(line);
4714 }
4715 } catch (IOException e) {
4716 pw.print("Unable to read: ");
4717 pw.print(e);
4718 pw.println();
4719 }
4720 }
4721
4722 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4723 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4724 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4725 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4726 }
4727
4728 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4729 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4730 pw.println(header);
4731
Wale Ogunwaled32da472018-11-16 07:19:28 -08004732 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004733 dumpPackage);
4734 boolean needSep = printedAnything;
4735
4736 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004737 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004738 " ResumedActivity: ");
4739 if (printed) {
4740 printedAnything = true;
4741 needSep = false;
4742 }
4743
4744 if (dumpPackage == null) {
4745 if (needSep) {
4746 pw.println();
4747 }
4748 printedAnything = true;
4749 mStackSupervisor.dump(pw, " ");
4750 }
4751
4752 if (!printedAnything) {
4753 pw.println(" (nothing)");
4754 }
4755 }
4756
4757 void dumpActivityContainersLocked(PrintWriter pw) {
4758 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004759 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004760 pw.println(" ");
4761 }
4762
4763 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4764 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4765 getActivityStartController().dump(pw, "", dumpPackage);
4766 }
4767
4768 /**
4769 * There are three things that cmd can be:
4770 * - a flattened component name that matches an existing activity
4771 * - the cmd arg isn't the flattened component name of an existing activity:
4772 * dump all activity whose component contains the cmd as a substring
4773 * - A hex number of the ActivityRecord object instance.
4774 *
4775 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4776 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4777 */
4778 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4779 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4780 ArrayList<ActivityRecord> activities;
4781
4782 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004783 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004784 dumpFocusedStackOnly);
4785 }
4786
4787 if (activities.size() <= 0) {
4788 return false;
4789 }
4790
4791 String[] newArgs = new String[args.length - opti];
4792 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4793
4794 TaskRecord lastTask = null;
4795 boolean needSep = false;
4796 for (int i = activities.size() - 1; i >= 0; i--) {
4797 ActivityRecord r = activities.get(i);
4798 if (needSep) {
4799 pw.println();
4800 }
4801 needSep = true;
4802 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004803 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004804 if (lastTask != task) {
4805 lastTask = task;
4806 pw.print("TASK "); pw.print(lastTask.affinity);
4807 pw.print(" id="); pw.print(lastTask.taskId);
4808 pw.print(" userId="); pw.println(lastTask.userId);
4809 if (dumpAll) {
4810 lastTask.dump(pw, " ");
4811 }
4812 }
4813 }
4814 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4815 }
4816 return true;
4817 }
4818
4819 /**
4820 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4821 * there is a thread associated with the activity.
4822 */
4823 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4824 final ActivityRecord r, String[] args, boolean dumpAll) {
4825 String innerPrefix = prefix + " ";
4826 synchronized (mGlobalLock) {
4827 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4828 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4829 pw.print(" pid=");
4830 if (r.hasProcess()) pw.println(r.app.getPid());
4831 else pw.println("(not running)");
4832 if (dumpAll) {
4833 r.dump(pw, innerPrefix);
4834 }
4835 }
4836 if (r.attachedToProcess()) {
4837 // flush anything that is already in the PrintWriter since the thread is going
4838 // to write to the file descriptor directly
4839 pw.flush();
4840 try {
4841 TransferPipe tp = new TransferPipe();
4842 try {
4843 r.app.getThread().dumpActivity(tp.getWriteFd(),
4844 r.appToken, innerPrefix, args);
4845 tp.go(fd);
4846 } finally {
4847 tp.kill();
4848 }
4849 } catch (IOException e) {
4850 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4851 } catch (RemoteException e) {
4852 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4853 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004854 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004855 }
4856
sanryhuang498e77e2018-12-06 14:57:01 +08004857 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4858 boolean testPssMode) {
4859 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4860 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4861 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004862 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004863 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4864 st.toString());
4865 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004866 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4867 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4868 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004869 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4870 testPssMode);
4871 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004872 }
4873
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004874 int getCurrentUserId() {
4875 return mAmInternal.getCurrentUserId();
4876 }
4877
4878 private void enforceNotIsolatedCaller(String caller) {
4879 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4880 throw new SecurityException("Isolated process not allowed to call " + caller);
4881 }
4882 }
4883
Wale Ogunwalef6733932018-06-27 05:14:34 -07004884 public Configuration getConfiguration() {
4885 Configuration ci;
4886 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004887 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004888 ci.userSetLocale = false;
4889 }
4890 return ci;
4891 }
4892
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004893 /**
4894 * Current global configuration information. Contains general settings for the entire system,
4895 * also corresponds to the merged configuration of the default display.
4896 */
4897 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004898 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004899 }
4900
4901 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4902 boolean initLocale) {
4903 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4904 }
4905
4906 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4907 boolean initLocale, boolean deferResume) {
4908 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4909 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4910 UserHandle.USER_NULL, deferResume);
4911 }
4912
Wale Ogunwale59507092018-10-29 09:00:30 -07004913 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004914 final long origId = Binder.clearCallingIdentity();
4915 try {
4916 synchronized (mGlobalLock) {
4917 updateConfigurationLocked(values, null, false, true, userId,
4918 false /* deferResume */);
4919 }
4920 } finally {
4921 Binder.restoreCallingIdentity(origId);
4922 }
4923 }
4924
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004925 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4926 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4927 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4928 deferResume, null /* result */);
4929 }
4930
4931 /**
4932 * Do either or both things: (1) change the current configuration, and (2)
4933 * make sure the given activity is running with the (now) current
4934 * configuration. Returns true if the activity has been left running, or
4935 * false if <var>starting</var> is being destroyed to match the new
4936 * configuration.
4937 *
4938 * @param userId is only used when persistent parameter is set to true to persist configuration
4939 * for that particular user
4940 */
4941 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4942 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4943 ActivityTaskManagerService.UpdateConfigurationResult result) {
4944 int changes = 0;
4945 boolean kept = true;
4946
4947 if (mWindowManager != null) {
4948 mWindowManager.deferSurfaceLayout();
4949 }
4950 try {
4951 if (values != null) {
4952 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4953 deferResume);
4954 }
4955
4956 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4957 } finally {
4958 if (mWindowManager != null) {
4959 mWindowManager.continueSurfaceLayout();
4960 }
4961 }
4962
4963 if (result != null) {
4964 result.changes = changes;
4965 result.activityRelaunched = !kept;
4966 }
4967 return kept;
4968 }
4969
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004970 /** Update default (global) configuration and notify listeners about changes. */
4971 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4972 boolean persistent, int userId, boolean deferResume) {
4973 mTempConfig.setTo(getGlobalConfiguration());
4974 final int changes = mTempConfig.updateFrom(values);
4975 if (changes == 0) {
4976 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4977 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4978 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4979 // (even if there are no actual changes) to unfreeze the window.
4980 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4981 return 0;
4982 }
4983
4984 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4985 "Updating global configuration to: " + values);
4986
4987 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4988 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4989 values.colorMode,
4990 values.densityDpi,
4991 values.fontScale,
4992 values.hardKeyboardHidden,
4993 values.keyboard,
4994 values.keyboardHidden,
4995 values.mcc,
4996 values.mnc,
4997 values.navigation,
4998 values.navigationHidden,
4999 values.orientation,
5000 values.screenHeightDp,
5001 values.screenLayout,
5002 values.screenWidthDp,
5003 values.smallestScreenWidthDp,
5004 values.touchscreen,
5005 values.uiMode);
5006
5007
5008 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5009 final LocaleList locales = values.getLocales();
5010 int bestLocaleIndex = 0;
5011 if (locales.size() > 1) {
5012 if (mSupportedSystemLocales == null) {
5013 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5014 }
5015 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5016 }
5017 SystemProperties.set("persist.sys.locale",
5018 locales.get(bestLocaleIndex).toLanguageTag());
5019 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005020
5021 final Message m = PooledLambda.obtainMessage(
5022 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5023 locales.get(bestLocaleIndex));
5024 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005025 }
5026
Yunfan Chen75157d72018-07-27 14:47:21 +09005027 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005028
5029 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005030 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005031
5032 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5033 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005034 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005035
5036 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005037 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005038
5039 AttributeCache ac = AttributeCache.instance();
5040 if (ac != null) {
5041 ac.updateConfiguration(mTempConfig);
5042 }
5043
5044 // Make sure all resources in our process are updated right now, so that anyone who is going
5045 // to retrieve resource values after we return will be sure to get the new ones. This is
5046 // especially important during boot, where the first config change needs to guarantee all
5047 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005048 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005049
5050 // We need another copy of global config because we're scheduling some calls instead of
5051 // running them in place. We need to be sure that object we send will be handled unchanged.
5052 final Configuration configCopy = new Configuration(mTempConfig);
5053 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005054 final Message msg = PooledLambda.obtainMessage(
5055 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5056 this, userId, configCopy);
5057 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005058 }
5059
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005060 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005061 final int pid = mPidMap.keyAt(i);
5062 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005063 if (DEBUG_CONFIGURATION) {
5064 Slog.v(TAG_CONFIGURATION, "Update process config of "
5065 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005066 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005067 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005068 }
5069
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005070 final Message msg = PooledLambda.obtainMessage(
5071 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5072 mAmInternal, changes, initLocale);
5073 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005074
5075 // Override configuration of the default display duplicates global config, so we need to
5076 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005077 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005078 DEFAULT_DISPLAY);
5079
5080 return changes;
5081 }
5082
5083 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5084 boolean deferResume, int displayId) {
5085 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5086 displayId, null /* result */);
5087 }
5088
5089 /**
5090 * Updates override configuration specific for the selected display. If no config is provided,
5091 * new one will be computed in WM based on current display info.
5092 */
5093 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5094 ActivityRecord starting, boolean deferResume, int displayId,
5095 ActivityTaskManagerService.UpdateConfigurationResult result) {
5096 int changes = 0;
5097 boolean kept = true;
5098
5099 if (mWindowManager != null) {
5100 mWindowManager.deferSurfaceLayout();
5101 }
5102 try {
5103 if (values != null) {
5104 if (displayId == DEFAULT_DISPLAY) {
5105 // Override configuration of the default display duplicates global config, so
5106 // we're calling global config update instead for default display. It will also
5107 // apply the correct override config.
5108 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5109 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5110 } else {
5111 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5112 }
5113 }
5114
5115 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5116 } finally {
5117 if (mWindowManager != null) {
5118 mWindowManager.continueSurfaceLayout();
5119 }
5120 }
5121
5122 if (result != null) {
5123 result.changes = changes;
5124 result.activityRelaunched = !kept;
5125 }
5126 return kept;
5127 }
5128
5129 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5130 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005131 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005132 final int changes = mTempConfig.updateFrom(values);
5133 if (changes != 0) {
5134 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5135 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005136 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005137
5138 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5139 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005140 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005141
Wale Ogunwale5c918702018-10-18 11:06:33 -07005142 // Post message to start process to avoid possible deadlock of calling into AMS with
5143 // the ATMS lock held.
5144 final Message msg = PooledLambda.obtainMessage(
5145 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5146 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5147 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005148 }
5149 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005150 return changes;
5151 }
5152
Wale Ogunwalef6733932018-06-27 05:14:34 -07005153 private void updateEventDispatchingLocked(boolean booted) {
5154 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5155 }
5156
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005157 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5158 final ContentResolver resolver = mContext.getContentResolver();
5159 Settings.System.putConfigurationForUser(resolver, config, userId);
5160 }
5161
5162 private void sendLocaleToMountDaemonMsg(Locale l) {
5163 try {
5164 IBinder service = ServiceManager.getService("mount");
5165 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5166 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5167 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5168 } catch (RemoteException e) {
5169 Log.e(TAG, "Error storing locale for decryption UI", e);
5170 }
5171 }
5172
Alison Cichowlas3e340502018-08-07 17:15:01 -04005173 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5174 mStartActivitySources.remove(permissionToken);
5175 mExpiredStartAsCallerTokens.add(permissionToken);
5176 }
5177
5178 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5179 mExpiredStartAsCallerTokens.remove(permissionToken);
5180 }
5181
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005182 boolean isActivityStartsLoggingEnabled() {
5183 return mAmInternal.isActivityStartsLoggingEnabled();
5184 }
5185
Michal Karpinski8596ded2018-11-14 14:43:48 +00005186 boolean isBackgroundActivityStartsEnabled() {
5187 return mAmInternal.isBackgroundActivityStartsEnabled();
5188 }
5189
Wale Ogunwalef6733932018-06-27 05:14:34 -07005190 void enableScreenAfterBoot(boolean booted) {
5191 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5192 SystemClock.uptimeMillis());
5193 mWindowManager.enableScreenAfterBoot();
5194
5195 synchronized (mGlobalLock) {
5196 updateEventDispatchingLocked(booted);
5197 }
5198 }
5199
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005200 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5201 if (r == null || !r.hasProcess()) {
5202 return KEY_DISPATCHING_TIMEOUT_MS;
5203 }
5204 return getInputDispatchingTimeoutLocked(r.app);
5205 }
5206
5207 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005208 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005209 }
5210
Wale Ogunwalef6733932018-06-27 05:14:34 -07005211 /**
5212 * Decide based on the configuration whether we should show the ANR,
5213 * crash, etc dialogs. The idea is that if there is no affordance to
5214 * press the on-screen buttons, or the user experience would be more
5215 * greatly impacted than the crash itself, we shouldn't show the dialog.
5216 *
5217 * A thought: SystemUI might also want to get told about this, the Power
5218 * dialog / global actions also might want different behaviors.
5219 */
5220 private void updateShouldShowDialogsLocked(Configuration config) {
5221 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5222 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5223 && config.navigation == Configuration.NAVIGATION_NONAV);
5224 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5225 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5226 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5227 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5228 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5229 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5230 HIDE_ERROR_DIALOGS, 0) != 0;
5231 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5232 }
5233
5234 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5235 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5236 FONT_SCALE, 1.0f, userId);
5237
5238 synchronized (this) {
5239 if (getGlobalConfiguration().fontScale == scaleFactor) {
5240 return;
5241 }
5242
5243 final Configuration configuration
5244 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5245 configuration.fontScale = scaleFactor;
5246 updatePersistentConfiguration(configuration, userId);
5247 }
5248 }
5249
5250 // Actually is sleeping or shutting down or whatever else in the future
5251 // is an inactive state.
5252 boolean isSleepingOrShuttingDownLocked() {
5253 return isSleepingLocked() || mShuttingDown;
5254 }
5255
5256 boolean isSleepingLocked() {
5257 return mSleeping;
5258 }
5259
Riddle Hsu16567132018-08-16 21:37:47 +08005260 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005261 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005262 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005263 if (task.isActivityTypeStandard()) {
5264 if (mCurAppTimeTracker != r.appTimeTracker) {
5265 // We are switching app tracking. Complete the current one.
5266 if (mCurAppTimeTracker != null) {
5267 mCurAppTimeTracker.stop();
5268 mH.obtainMessage(
5269 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005270 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005271 mCurAppTimeTracker = null;
5272 }
5273 if (r.appTimeTracker != null) {
5274 mCurAppTimeTracker = r.appTimeTracker;
5275 startTimeTrackingFocusedActivityLocked();
5276 }
5277 } else {
5278 startTimeTrackingFocusedActivityLocked();
5279 }
5280 } else {
5281 r.appTimeTracker = null;
5282 }
5283 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5284 // TODO: Probably not, because we don't want to resume voice on switching
5285 // back to this activity
5286 if (task.voiceInteractor != null) {
5287 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5288 } else {
5289 finishRunningVoiceLocked();
5290
5291 if (mLastResumedActivity != null) {
5292 final IVoiceInteractionSession session;
5293
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005294 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005295 if (lastResumedActivityTask != null
5296 && lastResumedActivityTask.voiceSession != null) {
5297 session = lastResumedActivityTask.voiceSession;
5298 } else {
5299 session = mLastResumedActivity.voiceSession;
5300 }
5301
5302 if (session != null) {
5303 // We had been in a voice interaction session, but now focused has
5304 // move to something different. Just finish the session, we can't
5305 // return to it and retain the proper state and synchronization with
5306 // the voice interaction service.
5307 finishVoiceTask(session);
5308 }
5309 }
5310 }
5311
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005312 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5313 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005314 }
5315 updateResumedAppTrace(r);
5316 mLastResumedActivity = r;
5317
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005318 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005319
5320 applyUpdateLockStateLocked(r);
5321 applyUpdateVrModeLocked(r);
5322
5323 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005324 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005325 r == null ? "NULL" : r.shortComponentName,
5326 reason);
5327 }
5328
5329 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5330 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005331 final ActivityTaskManagerInternal.SleepToken token =
5332 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005333 updateSleepIfNeededLocked();
5334 return token;
5335 }
5336 }
5337
5338 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005339 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005340 final boolean wasSleeping = mSleeping;
5341 boolean updateOomAdj = false;
5342
5343 if (!shouldSleep) {
5344 // If wasSleeping is true, we need to wake up activity manager state from when
5345 // we started sleeping. In either case, we need to apply the sleep tokens, which
5346 // will wake up stacks or put them to sleep as appropriate.
5347 if (wasSleeping) {
5348 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005349 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5350 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005351 startTimeTrackingFocusedActivityLocked();
5352 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5353 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5354 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005355 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005356 if (wasSleeping) {
5357 updateOomAdj = true;
5358 }
5359 } else if (!mSleeping && shouldSleep) {
5360 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005361 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5362 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005363 if (mCurAppTimeTracker != null) {
5364 mCurAppTimeTracker.stop();
5365 }
5366 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5367 mStackSupervisor.goingToSleepLocked();
5368 updateResumedAppTrace(null /* resumed */);
5369 updateOomAdj = true;
5370 }
5371 if (updateOomAdj) {
5372 mH.post(mAmInternal::updateOomAdj);
5373 }
5374 }
5375
5376 void updateOomAdj() {
5377 mH.post(mAmInternal::updateOomAdj);
5378 }
5379
Wale Ogunwale53783742018-09-16 10:21:51 -07005380 void updateCpuStats() {
5381 mH.post(mAmInternal::updateCpuStats);
5382 }
5383
Hui Yu03d12402018-12-06 18:00:37 -08005384 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5385 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005386 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5387 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005388 mH.sendMessage(m);
5389 }
5390
Hui Yu03d12402018-12-06 18:00:37 -08005391 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005392 ComponentName taskRoot = null;
5393 final TaskRecord task = activity.getTaskRecord();
5394 if (task != null) {
5395 final ActivityRecord rootActivity = task.getRootActivity();
5396 if (rootActivity != null) {
5397 taskRoot = rootActivity.mActivityComponent;
5398 }
5399 }
5400
Hui Yu03d12402018-12-06 18:00:37 -08005401 final Message m = PooledLambda.obtainMessage(
5402 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005403 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005404 mH.sendMessage(m);
5405 }
5406
Wale Ogunwale53783742018-09-16 10:21:51 -07005407 void setBooting(boolean booting) {
5408 mAmInternal.setBooting(booting);
5409 }
5410
5411 boolean isBooting() {
5412 return mAmInternal.isBooting();
5413 }
5414
5415 void setBooted(boolean booted) {
5416 mAmInternal.setBooted(booted);
5417 }
5418
5419 boolean isBooted() {
5420 return mAmInternal.isBooted();
5421 }
5422
5423 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5424 mH.post(() -> {
5425 if (finishBooting) {
5426 mAmInternal.finishBooting();
5427 }
5428 if (enableScreen) {
5429 mInternal.enableScreenAfterBoot(isBooted());
5430 }
5431 });
5432 }
5433
5434 void setHeavyWeightProcess(ActivityRecord root) {
5435 mHeavyWeightProcess = root.app;
5436 final Message m = PooledLambda.obtainMessage(
5437 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005438 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005439 mH.sendMessage(m);
5440 }
5441
5442 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5443 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5444 return;
5445 }
5446
5447 mHeavyWeightProcess = null;
5448 final Message m = PooledLambda.obtainMessage(
5449 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5450 proc.mUserId);
5451 mH.sendMessage(m);
5452 }
5453
5454 private void cancelHeavyWeightProcessNotification(int userId) {
5455 final INotificationManager inm = NotificationManager.getService();
5456 if (inm == null) {
5457 return;
5458 }
5459 try {
5460 inm.cancelNotificationWithTag("android", null,
5461 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5462 } catch (RuntimeException e) {
5463 Slog.w(TAG, "Error canceling notification for service", e);
5464 } catch (RemoteException e) {
5465 }
5466
5467 }
5468
5469 private void postHeavyWeightProcessNotification(
5470 WindowProcessController proc, Intent intent, int userId) {
5471 if (proc == null) {
5472 return;
5473 }
5474
5475 final INotificationManager inm = NotificationManager.getService();
5476 if (inm == null) {
5477 return;
5478 }
5479
5480 try {
5481 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5482 String text = mContext.getString(R.string.heavy_weight_notification,
5483 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5484 Notification notification =
5485 new Notification.Builder(context,
5486 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5487 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5488 .setWhen(0)
5489 .setOngoing(true)
5490 .setTicker(text)
5491 .setColor(mContext.getColor(
5492 com.android.internal.R.color.system_notification_accent_color))
5493 .setContentTitle(text)
5494 .setContentText(
5495 mContext.getText(R.string.heavy_weight_notification_detail))
5496 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5497 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5498 new UserHandle(userId)))
5499 .build();
5500 try {
5501 inm.enqueueNotificationWithTag("android", "android", null,
5502 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5503 } catch (RuntimeException e) {
5504 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5505 } catch (RemoteException e) {
5506 }
5507 } catch (PackageManager.NameNotFoundException e) {
5508 Slog.w(TAG, "Unable to create context for heavy notification", e);
5509 }
5510
5511 }
5512
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005513 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5514 IBinder token, String resultWho, int requestCode, Intent[] intents,
5515 String[] resolvedTypes, int flags, Bundle bOptions) {
5516
5517 ActivityRecord activity = null;
5518 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5519 activity = ActivityRecord.isInStackLocked(token);
5520 if (activity == null) {
5521 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5522 return null;
5523 }
5524 if (activity.finishing) {
5525 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5526 return null;
5527 }
5528 }
5529
5530 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5531 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5532 bOptions);
5533 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5534 if (noCreate) {
5535 return rec;
5536 }
5537 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5538 if (activity.pendingResults == null) {
5539 activity.pendingResults = new HashSet<>();
5540 }
5541 activity.pendingResults.add(rec.ref);
5542 }
5543 return rec;
5544 }
5545
Andrii Kulian52d255c2018-07-13 11:32:19 -07005546 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005547 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005548 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5550 mCurAppTimeTracker.start(resumedActivity.packageName);
5551 }
5552 }
5553
5554 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5555 if (mTracedResumedActivity != null) {
5556 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5557 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5558 }
5559 if (resumed != null) {
5560 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5561 constructResumedTraceName(resumed.packageName), 0);
5562 }
5563 mTracedResumedActivity = resumed;
5564 }
5565
5566 private String constructResumedTraceName(String packageName) {
5567 return "focused app: " + packageName;
5568 }
5569
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005570 /** Applies latest configuration and/or visibility updates if needed. */
5571 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5572 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005573 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005574 // mainStack is null during startup.
5575 if (mainStack != null) {
5576 if (changes != 0 && starting == null) {
5577 // If the configuration changed, and the caller is not already
5578 // in the process of starting an activity, then find the top
5579 // activity to check if its configuration needs to change.
5580 starting = mainStack.topRunningActivityLocked();
5581 }
5582
5583 if (starting != null) {
5584 kept = starting.ensureActivityConfiguration(changes,
5585 false /* preserveWindow */);
5586 // And we need to make sure at this point that all other activities
5587 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005588 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005589 !PRESERVE_WINDOWS);
5590 }
5591 }
5592
5593 return kept;
5594 }
5595
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005596 void scheduleAppGcsLocked() {
5597 mH.post(() -> mAmInternal.scheduleAppGcs());
5598 }
5599
Wale Ogunwale53783742018-09-16 10:21:51 -07005600 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5601 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5602 }
5603
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005604 /**
5605 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5606 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5607 * on demand.
5608 */
5609 IPackageManager getPackageManager() {
5610 return AppGlobals.getPackageManager();
5611 }
5612
5613 PackageManagerInternal getPackageManagerInternalLocked() {
5614 if (mPmInternal == null) {
5615 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5616 }
5617 return mPmInternal;
5618 }
5619
Wale Ogunwale008163e2018-07-23 23:11:08 -07005620 AppWarnings getAppWarningsLocked() {
5621 return mAppWarnings;
5622 }
5623
Wale Ogunwale214f3482018-10-04 11:00:47 -07005624 Intent getHomeIntent() {
5625 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5626 intent.setComponent(mTopComponent);
5627 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5628 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5629 intent.addCategory(Intent.CATEGORY_HOME);
5630 }
5631 return intent;
5632 }
5633
Chilun2ef71f72018-11-16 17:57:15 +08005634 /**
5635 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5636 * activities.
5637 *
5638 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5639 * component defined in config_secondaryHomeComponent.
5640 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5641 */
5642 Intent getSecondaryHomeIntent(String preferredPackage) {
5643 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5644 if (preferredPackage == null) {
5645 // Using the component stored in config if no package name.
5646 final String secondaryHomeComponent = mContext.getResources().getString(
5647 com.android.internal.R.string.config_secondaryHomeComponent);
5648 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5649 } else {
5650 intent.setPackage(preferredPackage);
5651 }
5652 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5653 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5654 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5655 }
5656 return intent;
5657 }
5658
Wale Ogunwale214f3482018-10-04 11:00:47 -07005659 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5660 if (info == null) return null;
5661 ApplicationInfo newInfo = new ApplicationInfo(info);
5662 newInfo.initForUser(userId);
5663 return newInfo;
5664 }
5665
Wale Ogunwale9c103022018-10-18 07:44:54 -07005666 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005667 if (uid == SYSTEM_UID) {
5668 // The system gets to run in any process. If there are multiple processes with the same
5669 // uid, just pick the first (this should never happen).
5670 final SparseArray<WindowProcessController> procs =
5671 mProcessNames.getMap().get(processName);
5672 if (procs == null) return null;
5673 final int procCount = procs.size();
5674 for (int i = 0; i < procCount; i++) {
5675 final int procUid = procs.keyAt(i);
5676 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5677 // Don't use an app process or different user process for system component.
5678 continue;
5679 }
5680 return procs.valueAt(i);
5681 }
5682 }
5683
5684 return mProcessNames.get(processName, uid);
5685 }
5686
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005687 WindowProcessController getProcessController(IApplicationThread thread) {
5688 if (thread == null) {
5689 return null;
5690 }
5691
5692 final IBinder threadBinder = thread.asBinder();
5693 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5694 for (int i = pmap.size()-1; i >= 0; i--) {
5695 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5696 for (int j = procs.size() - 1; j >= 0; j--) {
5697 final WindowProcessController proc = procs.valueAt(j);
5698 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5699 return proc;
5700 }
5701 }
5702 }
5703
5704 return null;
5705 }
5706
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005707 WindowProcessController getProcessController(int pid, int uid) {
5708 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5709 for (int i = pmap.size()-1; i >= 0; i--) {
5710 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5711 for (int j = procs.size() - 1; j >= 0; j--) {
5712 final WindowProcessController proc = procs.valueAt(j);
5713 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5714 return proc;
5715 }
5716 }
5717 }
5718 return null;
5719 }
5720
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005721 int getUidStateLocked(int uid) {
5722 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5723 }
5724
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005725 boolean isUidForeground(int uid) {
5726 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5727 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5728 }
5729
Michal Karpinski4026cae2019-02-12 11:51:47 +00005730 boolean isDeviceOwner(String packageName) {
5731 if (packageName == null) {
5732 return false;
5733 }
5734 return packageName.equals(mDeviceOwnerPackageName);
5735 }
5736
5737 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5738 mDeviceOwnerPackageName = deviceOwnerPkg;
5739 }
5740
Wale Ogunwale9de19442018-10-18 19:05:03 -07005741 /**
5742 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5743 * the whitelist
5744 */
5745 String getPendingTempWhitelistTagForUidLocked(int uid) {
5746 return mPendingTempWhitelist.get(uid);
5747 }
5748
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005749 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5750 if (true || Build.IS_USER) {
5751 return;
5752 }
5753
5754 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5755 StrictMode.allowThreadDiskWrites();
5756 try {
5757 File tracesDir = new File("/data/anr");
5758 File tracesFile = null;
5759 try {
5760 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5761
5762 StringBuilder sb = new StringBuilder();
5763 Time tobj = new Time();
5764 tobj.set(System.currentTimeMillis());
5765 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5766 sb.append(": ");
5767 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5768 sb.append(" since ");
5769 sb.append(msg);
5770 FileOutputStream fos = new FileOutputStream(tracesFile);
5771 fos.write(sb.toString().getBytes());
5772 if (app == null) {
5773 fos.write("\n*** No application process!".getBytes());
5774 }
5775 fos.close();
5776 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5777 } catch (IOException e) {
5778 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5779 return;
5780 }
5781
5782 if (app != null && app.getPid() > 0) {
5783 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5784 firstPids.add(app.getPid());
5785 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5786 }
5787
5788 File lastTracesFile = null;
5789 File curTracesFile = null;
5790 for (int i=9; i>=0; i--) {
5791 String name = String.format(Locale.US, "slow%02d.txt", i);
5792 curTracesFile = new File(tracesDir, name);
5793 if (curTracesFile.exists()) {
5794 if (lastTracesFile != null) {
5795 curTracesFile.renameTo(lastTracesFile);
5796 } else {
5797 curTracesFile.delete();
5798 }
5799 }
5800 lastTracesFile = curTracesFile;
5801 }
5802 tracesFile.renameTo(curTracesFile);
5803 } finally {
5804 StrictMode.setThreadPolicy(oldPolicy);
5805 }
5806 }
5807
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005808 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005809 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005810
5811
Wale Ogunwale98875612018-10-12 07:53:02 -07005812 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5813 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005814
Riddle Hsud93a6c42018-11-29 21:50:06 +08005815 H(Looper looper) {
5816 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005817 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005818
5819 @Override
5820 public void handleMessage(Message msg) {
5821 switch (msg.what) {
5822 case REPORT_TIME_TRACKER_MSG: {
5823 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5824 tracker.deliverResult(mContext);
5825 } break;
5826 }
5827 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005828 }
5829
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005830 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005831 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005832
5833 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005834 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005835 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005836
5837 @Override
5838 public void handleMessage(Message msg) {
5839 switch (msg.what) {
5840 case DISMISS_DIALOG_UI_MSG: {
5841 final Dialog d = (Dialog) msg.obj;
5842 d.dismiss();
5843 break;
5844 }
5845 }
5846 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005847 }
5848
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005849 final class LocalService extends ActivityTaskManagerInternal {
5850 @Override
5851 public SleepToken acquireSleepToken(String tag, int displayId) {
5852 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005853 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005854 }
5855
5856 @Override
5857 public ComponentName getHomeActivityForUser(int userId) {
5858 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005859 final ActivityRecord homeActivity =
5860 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005861 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005862 }
5863 }
5864
5865 @Override
5866 public void onLocalVoiceInteractionStarted(IBinder activity,
5867 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5868 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005869 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005870 }
5871 }
5872
5873 @Override
5874 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5875 synchronized (mGlobalLock) {
5876 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5877 reasons, timestamp);
5878 }
5879 }
5880
5881 @Override
5882 public void notifyAppTransitionFinished() {
5883 synchronized (mGlobalLock) {
5884 mStackSupervisor.notifyAppTransitionDone();
5885 }
5886 }
5887
5888 @Override
5889 public void notifyAppTransitionCancelled() {
5890 synchronized (mGlobalLock) {
5891 mStackSupervisor.notifyAppTransitionDone();
5892 }
5893 }
5894
5895 @Override
5896 public List<IBinder> getTopVisibleActivities() {
5897 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005898 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005899 }
5900 }
5901
5902 @Override
5903 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5904 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005905 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005906 }
5907 }
5908
5909 @Override
5910 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5911 Bundle bOptions) {
5912 Preconditions.checkNotNull(intents, "intents");
5913 final String[] resolvedTypes = new String[intents.length];
5914
5915 // UID of the package on user userId.
5916 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5917 // packageUid may not be initialized.
5918 int packageUid = 0;
5919 final long ident = Binder.clearCallingIdentity();
5920
5921 try {
5922 for (int i = 0; i < intents.length; i++) {
5923 resolvedTypes[i] =
5924 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5925 }
5926
5927 packageUid = AppGlobals.getPackageManager().getPackageUid(
5928 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5929 } catch (RemoteException e) {
5930 // Shouldn't happen.
5931 } finally {
5932 Binder.restoreCallingIdentity(ident);
5933 }
5934
5935 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005936 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005937 packageUid, packageName,
5938 intents, resolvedTypes, null /* resultTo */,
5939 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005940 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5941 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005942 }
5943 }
5944
5945 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005946 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5947 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5948 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5949 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005950 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005951 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005952 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5953 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5954 userId, validateIncomingUser, originatingPendingIntent,
5955 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005956 }
5957 }
5958
5959 @Override
5960 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5961 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5962 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5963 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005964 PendingIntentRecord originatingPendingIntent,
5965 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005966 synchronized (mGlobalLock) {
5967 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5968 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5969 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005970 validateIncomingUser, originatingPendingIntent,
5971 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005972 }
5973 }
5974
5975 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005976 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5977 Intent intent, Bundle options, int userId) {
5978 return ActivityTaskManagerService.this.startActivityAsUser(
5979 caller, callerPacakge, intent,
5980 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5981 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5982 false /*validateIncomingUser*/);
5983 }
5984
5985 @Override
lumark588a3e82018-07-20 18:53:54 +08005986 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005987 synchronized (mGlobalLock) {
5988
5989 // We might change the visibilities here, so prepare an empty app transition which
5990 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005991 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005992 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005993 if (activityDisplay == null) {
5994 return;
5995 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005996 final DisplayContent dc = activityDisplay.mDisplayContent;
5997 final boolean wasTransitionSet =
5998 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005999 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006000 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006001 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006002 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003
6004 // If there was a transition set already we don't want to interfere with it as we
6005 // might be starting it too early.
6006 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006007 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006008 }
6009 }
6010 if (callback != null) {
6011 callback.run();
6012 }
6013 }
6014
6015 @Override
6016 public void notifyKeyguardTrustedChanged() {
6017 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006018 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006019 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006020 }
6021 }
6022 }
6023
6024 /**
6025 * Called after virtual display Id is updated by
6026 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6027 * {@param vrVr2dDisplayId}.
6028 */
6029 @Override
6030 public void setVr2dDisplayId(int vr2dDisplayId) {
6031 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6032 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006033 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006034 }
6035 }
6036
6037 @Override
6038 public void setFocusedActivity(IBinder token) {
6039 synchronized (mGlobalLock) {
6040 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6041 if (r == null) {
6042 throw new IllegalArgumentException(
6043 "setFocusedActivity: No activity record matching token=" + token);
6044 }
Louis Chang19443452018-10-09 12:10:21 +08006045 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006046 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006047 }
6048 }
6049 }
6050
6051 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006052 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006053 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006054 }
6055
6056 @Override
6057 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006058 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006059 }
6060
6061 @Override
6062 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006063 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006064 }
6065
6066 @Override
6067 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6068 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6069 }
6070
6071 @Override
6072 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006073 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006074 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006075
6076 @Override
6077 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6078 synchronized (mGlobalLock) {
6079 mActiveVoiceInteractionServiceComponent = component;
6080 }
6081 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006082
6083 @Override
6084 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6085 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6086 return;
6087 }
6088 synchronized (mGlobalLock) {
6089 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6090 if (types == null) {
6091 if (uid < 0) {
6092 return;
6093 }
6094 types = new ArrayMap<>();
6095 mAllowAppSwitchUids.put(userId, types);
6096 }
6097 if (uid < 0) {
6098 types.remove(type);
6099 } else {
6100 types.put(type, uid);
6101 }
6102 }
6103 }
6104
6105 @Override
6106 public void onUserStopped(int userId) {
6107 synchronized (mGlobalLock) {
6108 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6109 mAllowAppSwitchUids.remove(userId);
6110 }
6111 }
6112
6113 @Override
6114 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6115 synchronized (mGlobalLock) {
6116 return ActivityTaskManagerService.this.isGetTasksAllowed(
6117 caller, callingPid, callingUid);
6118 }
6119 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006120
6121 @Override
6122 public void onProcessAdded(WindowProcessController proc) {
6123 synchronized (mGlobalLock) {
6124 mProcessNames.put(proc.mName, proc.mUid, proc);
6125 }
6126 }
6127
6128 @Override
6129 public void onProcessRemoved(String name, int uid) {
6130 synchronized (mGlobalLock) {
6131 mProcessNames.remove(name, uid);
6132 }
6133 }
6134
6135 @Override
6136 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6137 synchronized (mGlobalLock) {
6138 if (proc == mHomeProcess) {
6139 mHomeProcess = null;
6140 }
6141 if (proc == mPreviousProcess) {
6142 mPreviousProcess = null;
6143 }
6144 }
6145 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006146
6147 @Override
6148 public int getTopProcessState() {
6149 synchronized (mGlobalLock) {
6150 return mTopProcessState;
6151 }
6152 }
6153
6154 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006155 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6156 synchronized (mGlobalLock) {
6157 return proc == mHeavyWeightProcess;
6158 }
6159 }
6160
6161 @Override
6162 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6163 synchronized (mGlobalLock) {
6164 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6165 }
6166 }
6167
6168 @Override
6169 public void finishHeavyWeightApp() {
6170 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006171 if (mHeavyWeightProcess != null) {
6172 mHeavyWeightProcess.finishActivities();
6173 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006174 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6175 mHeavyWeightProcess);
6176 }
6177 }
6178
6179 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006180 public boolean isSleeping() {
6181 synchronized (mGlobalLock) {
6182 return isSleepingLocked();
6183 }
6184 }
6185
6186 @Override
6187 public boolean isShuttingDown() {
6188 synchronized (mGlobalLock) {
6189 return mShuttingDown;
6190 }
6191 }
6192
6193 @Override
6194 public boolean shuttingDown(boolean booted, int timeout) {
6195 synchronized (mGlobalLock) {
6196 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006197 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006198 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006199 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006200 return mStackSupervisor.shutdownLocked(timeout);
6201 }
6202 }
6203
6204 @Override
6205 public void enableScreenAfterBoot(boolean booted) {
6206 synchronized (mGlobalLock) {
6207 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6208 SystemClock.uptimeMillis());
6209 mWindowManager.enableScreenAfterBoot();
6210 updateEventDispatchingLocked(booted);
6211 }
6212 }
6213
6214 @Override
6215 public boolean showStrictModeViolationDialog() {
6216 synchronized (mGlobalLock) {
6217 return mShowDialogs && !mSleeping && !mShuttingDown;
6218 }
6219 }
6220
6221 @Override
6222 public void showSystemReadyErrorDialogsIfNeeded() {
6223 synchronized (mGlobalLock) {
6224 try {
6225 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6226 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6227 + " data partition or your device will be unstable.");
6228 mUiHandler.post(() -> {
6229 if (mShowDialogs) {
6230 AlertDialog d = new BaseErrorDialog(mUiContext);
6231 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6232 d.setCancelable(false);
6233 d.setTitle(mUiContext.getText(R.string.android_system_label));
6234 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6235 d.setButton(DialogInterface.BUTTON_POSITIVE,
6236 mUiContext.getText(R.string.ok),
6237 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6238 d.show();
6239 }
6240 });
6241 }
6242 } catch (RemoteException e) {
6243 }
6244
6245 if (!Build.isBuildConsistent()) {
6246 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6247 mUiHandler.post(() -> {
6248 if (mShowDialogs) {
6249 AlertDialog d = new BaseErrorDialog(mUiContext);
6250 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6251 d.setCancelable(false);
6252 d.setTitle(mUiContext.getText(R.string.android_system_label));
6253 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6254 d.setButton(DialogInterface.BUTTON_POSITIVE,
6255 mUiContext.getText(R.string.ok),
6256 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6257 d.show();
6258 }
6259 });
6260 }
6261 }
6262 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006263
6264 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006265 public void onProcessMapped(int pid, WindowProcessController proc) {
6266 synchronized (mGlobalLock) {
6267 mPidMap.put(pid, proc);
6268 }
6269 }
6270
6271 @Override
6272 public void onProcessUnMapped(int pid) {
6273 synchronized (mGlobalLock) {
6274 mPidMap.remove(pid);
6275 }
6276 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006277
6278 @Override
6279 public void onPackageDataCleared(String name) {
6280 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006281 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006282 mAppWarnings.onPackageDataCleared(name);
6283 }
6284 }
6285
6286 @Override
6287 public void onPackageUninstalled(String name) {
6288 synchronized (mGlobalLock) {
6289 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006290 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006291 }
6292 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006293
6294 @Override
6295 public void onPackageAdded(String name, boolean replacing) {
6296 synchronized (mGlobalLock) {
6297 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6298 }
6299 }
6300
6301 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006302 public void onPackageReplaced(ApplicationInfo aInfo) {
6303 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006304 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006305 }
6306 }
6307
6308 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006309 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6310 synchronized (mGlobalLock) {
6311 return compatibilityInfoForPackageLocked(ai);
6312 }
6313 }
6314
Yunfan Chen75157d72018-07-27 14:47:21 +09006315 /**
6316 * Set the corresponding display information for the process global configuration. To be
6317 * called when we need to show IME on a different display.
6318 *
6319 * @param pid The process id associated with the IME window.
6320 * @param displayId The ID of the display showing the IME.
6321 */
6322 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006323 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006324 if (pid == MY_PID || pid < 0) {
6325 if (DEBUG_CONFIGURATION) {
6326 Slog.w(TAG,
6327 "Trying to update display configuration for system/invalid process.");
6328 }
6329 return;
6330 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006331 synchronized (mGlobalLock) {
6332 final ActivityDisplay activityDisplay =
6333 mRootActivityContainer.getActivityDisplay(displayId);
6334 if (activityDisplay == null) {
6335 // Call might come when display is not yet added or has been removed.
6336 if (DEBUG_CONFIGURATION) {
6337 Slog.w(TAG, "Trying to update display configuration for non-existing "
6338 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006339 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006340 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006341 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006342 final WindowProcessController process = mPidMap.get(pid);
6343 if (process == null) {
6344 if (DEBUG_CONFIGURATION) {
6345 Slog.w(TAG, "Trying to update display configuration for invalid "
6346 + "process, pid=" + pid);
6347 }
6348 return;
6349 }
6350 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6351 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006352 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006353
6354 @Override
6355 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6356 int requestCode, int resultCode, Intent data) {
6357 synchronized (mGlobalLock) {
6358 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006359 if (r != null && r.getActivityStack() != null) {
6360 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6361 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006362 }
6363 }
6364 }
6365
6366 @Override
6367 public void clearPendingResultForActivity(IBinder activityToken,
6368 WeakReference<PendingIntentRecord> pir) {
6369 synchronized (mGlobalLock) {
6370 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6371 if (r != null && r.pendingResults != null) {
6372 r.pendingResults.remove(pir);
6373 }
6374 }
6375 }
6376
6377 @Override
6378 public IIntentSender getIntentSender(int type, String packageName,
6379 int callingUid, int userId, IBinder token, String resultWho,
6380 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6381 Bundle bOptions) {
6382 synchronized (mGlobalLock) {
6383 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6384 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6385 }
6386 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006387
6388 @Override
6389 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6390 synchronized (mGlobalLock) {
6391 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6392 if (r == null) {
6393 return null;
6394 }
6395 if (r.mServiceConnectionsHolder == null) {
6396 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6397 ActivityTaskManagerService.this, r);
6398 }
6399
6400 return r.mServiceConnectionsHolder;
6401 }
6402 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006403
6404 @Override
6405 public Intent getHomeIntent() {
6406 synchronized (mGlobalLock) {
6407 return ActivityTaskManagerService.this.getHomeIntent();
6408 }
6409 }
6410
6411 @Override
6412 public boolean startHomeActivity(int userId, String reason) {
6413 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006414 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006415 }
6416 }
6417
6418 @Override
6419 public boolean startHomeOnAllDisplays(int userId, String reason) {
6420 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006421 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006422 }
6423 }
6424
6425 @Override
6426 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6427 synchronized (mGlobalLock) {
6428 if (mFactoryTest == FACTORY_TEST_OFF) {
6429 return false;
6430 }
6431 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6432 && wpc.mName.equals(mTopComponent.getPackageName())) {
6433 return true;
6434 }
6435 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6436 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6437 }
6438 }
6439
6440 @Override
6441 public void updateTopComponentForFactoryTest() {
6442 synchronized (mGlobalLock) {
6443 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6444 return;
6445 }
6446 final ResolveInfo ri = mContext.getPackageManager()
6447 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6448 final CharSequence errorMsg;
6449 if (ri != null) {
6450 final ActivityInfo ai = ri.activityInfo;
6451 final ApplicationInfo app = ai.applicationInfo;
6452 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6453 mTopAction = Intent.ACTION_FACTORY_TEST;
6454 mTopData = null;
6455 mTopComponent = new ComponentName(app.packageName, ai.name);
6456 errorMsg = null;
6457 } else {
6458 errorMsg = mContext.getResources().getText(
6459 com.android.internal.R.string.factorytest_not_system);
6460 }
6461 } else {
6462 errorMsg = mContext.getResources().getText(
6463 com.android.internal.R.string.factorytest_no_action);
6464 }
6465 if (errorMsg == null) {
6466 return;
6467 }
6468
6469 mTopAction = null;
6470 mTopData = null;
6471 mTopComponent = null;
6472 mUiHandler.post(() -> {
6473 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6474 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006475 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006476 });
6477 }
6478 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006479
6480 @Override
6481 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6482 Runnable finishInstrumentationCallback) {
6483 synchronized (mGlobalLock) {
6484 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006485 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006486
6487 wpc.clearRecentTasks();
6488 wpc.clearActivities();
6489
6490 if (wpc.isInstrumenting()) {
6491 finishInstrumentationCallback.run();
6492 }
6493
Jorim Jaggid0752812018-10-16 16:07:20 +02006494 if (!restarting && hasVisibleActivities) {
6495 mWindowManager.deferSurfaceLayout();
6496 try {
6497 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6498 // If there was nothing to resume, and we are not already restarting
6499 // this process, but there is a visible activity that is hosted by the
6500 // process...then make sure all visible activities are running, taking
6501 // care of restarting this process.
6502 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6503 !PRESERVE_WINDOWS);
6504 }
6505 } finally {
6506 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006507 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006508 }
6509 }
6510 }
6511
6512 @Override
6513 public void closeSystemDialogs(String reason) {
6514 enforceNotIsolatedCaller("closeSystemDialogs");
6515
6516 final int pid = Binder.getCallingPid();
6517 final int uid = Binder.getCallingUid();
6518 final long origId = Binder.clearCallingIdentity();
6519 try {
6520 synchronized (mGlobalLock) {
6521 // Only allow this from foreground processes, so that background
6522 // applications can't abuse it to prevent system UI from being shown.
6523 if (uid >= FIRST_APPLICATION_UID) {
6524 final WindowProcessController proc = mPidMap.get(pid);
6525 if (!proc.isPerceptible()) {
6526 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6527 + " from background process " + proc);
6528 return;
6529 }
6530 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006531 mWindowManager.closeSystemDialogs(reason);
6532
Wale Ogunwaled32da472018-11-16 07:19:28 -08006533 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006534 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006535 // Call into AM outside the synchronized block.
6536 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006537 } finally {
6538 Binder.restoreCallingIdentity(origId);
6539 }
6540 }
6541
6542 @Override
6543 public void cleanupDisabledPackageComponents(
6544 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6545 synchronized (mGlobalLock) {
6546 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006547 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006548 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006549 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006550 mStackSupervisor.scheduleIdleLocked();
6551 }
6552
6553 // Clean-up disabled tasks
6554 getRecentTasks().cleanupDisabledPackageTasksLocked(
6555 packageName, disabledClasses, userId);
6556 }
6557 }
6558
6559 @Override
6560 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6561 int userId) {
6562 synchronized (mGlobalLock) {
6563
6564 boolean didSomething =
6565 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006566 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006567 null, doit, evenPersistent, userId);
6568 return didSomething;
6569 }
6570 }
6571
6572 @Override
6573 public void resumeTopActivities(boolean scheduleIdle) {
6574 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006575 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006576 if (scheduleIdle) {
6577 mStackSupervisor.scheduleIdleLocked();
6578 }
6579 }
6580 }
6581
6582 @Override
6583 public void preBindApplication(WindowProcessController wpc) {
6584 synchronized (mGlobalLock) {
6585 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6586 }
6587 }
6588
6589 @Override
6590 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6591 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006592 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006593 }
6594 }
6595
6596 @Override
6597 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6598 try {
6599 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6600 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6601 }
6602 } catch (RemoteException ex) {
6603 throw new SecurityException("Fail to check is caller a privileged app", ex);
6604 }
6605
6606 synchronized (mGlobalLock) {
6607 final long ident = Binder.clearCallingIdentity();
6608 try {
6609 if (mAmInternal.shouldConfirmCredentials(userId)) {
6610 if (mKeyguardController.isKeyguardLocked()) {
6611 // Showing launcher to avoid user entering credential twice.
6612 startHomeActivity(currentUserId, "notifyLockedProfile");
6613 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006614 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006615 }
6616 } finally {
6617 Binder.restoreCallingIdentity(ident);
6618 }
6619 }
6620 }
6621
6622 @Override
6623 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6624 mAmInternal.enforceCallingPermission(
6625 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6626
6627 synchronized (mGlobalLock) {
6628 final long ident = Binder.clearCallingIdentity();
6629 try {
6630 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6631 FLAG_ACTIVITY_TASK_ON_HOME);
6632 ActivityOptions activityOptions = options != null
6633 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006634 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006635 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006636 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006637 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006638 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006639 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6640 UserHandle.CURRENT);
6641 } finally {
6642 Binder.restoreCallingIdentity(ident);
6643 }
6644 }
6645 }
6646
6647 @Override
6648 public void writeActivitiesToProto(ProtoOutputStream proto) {
6649 synchronized (mGlobalLock) {
6650 // The output proto of "activity --proto activities"
6651 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006652 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006653 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6654 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006655 }
6656 }
6657
6658 @Override
6659 public void saveANRState(String reason) {
6660 synchronized (mGlobalLock) {
6661 final StringWriter sw = new StringWriter();
6662 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6663 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6664 if (reason != null) {
6665 pw.println(" Reason: " + reason);
6666 }
6667 pw.println();
6668 getActivityStartController().dump(pw, " ", null);
6669 pw.println();
6670 pw.println("-------------------------------------------------------------------------------");
6671 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6672 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6673 "" /* header */);
6674 pw.println();
6675 pw.close();
6676
6677 mLastANRState = sw.toString();
6678 }
6679 }
6680
6681 @Override
6682 public void clearSavedANRState() {
6683 synchronized (mGlobalLock) {
6684 mLastANRState = null;
6685 }
6686 }
6687
6688 @Override
6689 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6690 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6691 synchronized (mGlobalLock) {
6692 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6693 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6694 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6695 dumpLastANRLocked(pw);
6696 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6697 dumpLastANRTracesLocked(pw);
6698 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6699 dumpActivityStarterLocked(pw, dumpPackage);
6700 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6701 dumpActivityContainersLocked(pw);
6702 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6703 if (getRecentTasks() != null) {
6704 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6705 }
6706 }
6707 }
6708 }
6709
6710 @Override
6711 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6712 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6713 int wakefulness) {
6714 synchronized (mGlobalLock) {
6715 if (mHomeProcess != null && (dumpPackage == null
6716 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6717 if (needSep) {
6718 pw.println();
6719 needSep = false;
6720 }
6721 pw.println(" mHomeProcess: " + mHomeProcess);
6722 }
6723 if (mPreviousProcess != null && (dumpPackage == null
6724 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6725 if (needSep) {
6726 pw.println();
6727 needSep = false;
6728 }
6729 pw.println(" mPreviousProcess: " + mPreviousProcess);
6730 }
6731 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6732 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6733 StringBuilder sb = new StringBuilder(128);
6734 sb.append(" mPreviousProcessVisibleTime: ");
6735 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6736 pw.println(sb);
6737 }
6738 if (mHeavyWeightProcess != null && (dumpPackage == null
6739 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6740 if (needSep) {
6741 pw.println();
6742 needSep = false;
6743 }
6744 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6745 }
6746 if (dumpPackage == null) {
6747 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006748 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006749 }
6750 if (dumpAll) {
6751 if (dumpPackage == null) {
6752 pw.println(" mConfigWillChange: "
6753 + getTopDisplayFocusedStack().mConfigWillChange);
6754 }
6755 if (mCompatModePackages.getPackages().size() > 0) {
6756 boolean printed = false;
6757 for (Map.Entry<String, Integer> entry
6758 : mCompatModePackages.getPackages().entrySet()) {
6759 String pkg = entry.getKey();
6760 int mode = entry.getValue();
6761 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6762 continue;
6763 }
6764 if (!printed) {
6765 pw.println(" mScreenCompatPackages:");
6766 printed = true;
6767 }
6768 pw.println(" " + pkg + ": " + mode);
6769 }
6770 }
6771 }
6772
6773 if (dumpPackage == null) {
6774 pw.println(" mWakefulness="
6775 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006776 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006777 if (mRunningVoice != null) {
6778 pw.println(" mRunningVoice=" + mRunningVoice);
6779 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6780 }
6781 pw.println(" mSleeping=" + mSleeping);
6782 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6783 pw.println(" mVrController=" + mVrController);
6784 }
6785 if (mCurAppTimeTracker != null) {
6786 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6787 }
6788 if (mAllowAppSwitchUids.size() > 0) {
6789 boolean printed = false;
6790 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6791 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6792 for (int j = 0; j < types.size(); j++) {
6793 if (dumpPackage == null ||
6794 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6795 if (needSep) {
6796 pw.println();
6797 needSep = false;
6798 }
6799 if (!printed) {
6800 pw.println(" mAllowAppSwitchUids:");
6801 printed = true;
6802 }
6803 pw.print(" User ");
6804 pw.print(mAllowAppSwitchUids.keyAt(i));
6805 pw.print(": Type ");
6806 pw.print(types.keyAt(j));
6807 pw.print(" = ");
6808 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6809 pw.println();
6810 }
6811 }
6812 }
6813 }
6814 if (dumpPackage == null) {
6815 if (mController != null) {
6816 pw.println(" mController=" + mController
6817 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6818 }
6819 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6820 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6821 }
6822
6823 return needSep;
6824 }
6825 }
6826
6827 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006828 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6829 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006830 synchronized (mGlobalLock) {
6831 if (dumpPackage == null) {
6832 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6833 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006834 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6835 if (mRunningVoice != null) {
6836 final long vrToken = proto.start(
6837 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6838 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6839 mRunningVoice.toString());
6840 mVoiceWakeLock.writeToProto(
6841 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6842 proto.end(vrToken);
6843 }
6844 mVrController.writeToProto(proto,
6845 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006846 if (mController != null) {
6847 final long token = proto.start(CONTROLLER);
6848 proto.write(CONTROLLER, mController.toString());
6849 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6850 proto.end(token);
6851 }
6852 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6853 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6854 }
6855
6856 if (mHomeProcess != null && (dumpPackage == null
6857 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006858 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006859 }
6860
6861 if (mPreviousProcess != null && (dumpPackage == null
6862 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006863 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006864 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6865 }
6866
6867 if (mHeavyWeightProcess != null && (dumpPackage == null
6868 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006869 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006870 }
6871
6872 for (Map.Entry<String, Integer> entry
6873 : mCompatModePackages.getPackages().entrySet()) {
6874 String pkg = entry.getKey();
6875 int mode = entry.getValue();
6876 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6877 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6878 proto.write(PACKAGE, pkg);
6879 proto.write(MODE, mode);
6880 proto.end(compatToken);
6881 }
6882 }
6883
6884 if (mCurAppTimeTracker != null) {
6885 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6886 }
6887
6888 }
6889 }
6890
6891 @Override
6892 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6893 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6894 boolean dumpFocusedStackOnly) {
6895 synchronized (mGlobalLock) {
6896 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6897 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6898 }
6899 }
6900
6901 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006902 public void dumpForOom(PrintWriter pw) {
6903 synchronized (mGlobalLock) {
6904 pw.println(" mHomeProcess: " + mHomeProcess);
6905 pw.println(" mPreviousProcess: " + mPreviousProcess);
6906 if (mHeavyWeightProcess != null) {
6907 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6908 }
6909 }
6910 }
6911
6912 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006913 public boolean canGcNow() {
6914 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006915 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006916 }
6917 }
6918
6919 @Override
6920 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006921 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006922 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006923 return top != null ? top.app : null;
6924 }
6925 }
6926
6927 @Override
6928 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006929 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006930 if (mRootActivityContainer != null) {
6931 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006932 }
6933 }
6934 }
6935
6936 @Override
6937 public void scheduleDestroyAllActivities(String reason) {
6938 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006939 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006940 }
6941 }
6942
6943 @Override
6944 public void removeUser(int userId) {
6945 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006946 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006947 }
6948 }
6949
6950 @Override
6951 public boolean switchUser(int userId, UserState userState) {
6952 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006953 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006954 }
6955 }
6956
6957 @Override
6958 public void onHandleAppCrash(WindowProcessController wpc) {
6959 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006960 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006961 }
6962 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006963
6964 @Override
6965 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6966 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006967 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006968 }
6969 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006970
6971 @Override
6972 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006973 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006974 mActiveUids.put(uid, procState);
6975 }
6976 }
6977
6978 @Override
6979 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006980 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006981 mActiveUids.remove(uid);
6982 }
6983 }
6984
6985 @Override
6986 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006987 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006988 mActiveUids.clear();
6989 }
6990 }
6991
6992 @Override
6993 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006994 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006995 if (mActiveUids.get(uid) != null) {
6996 mActiveUids.put(uid, procState);
6997 }
6998 }
6999 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007000
7001 @Override
7002 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007003 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007004 mPendingTempWhitelist.put(uid, tag);
7005 }
7006 }
7007
7008 @Override
7009 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007010 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007011 mPendingTempWhitelist.remove(uid);
7012 }
7013 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007014
7015 @Override
7016 public boolean handleAppCrashInActivityController(String processName, int pid,
7017 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7018 Runnable killCrashingAppCallback) {
7019 synchronized (mGlobalLock) {
7020 if (mController == null) {
7021 return false;
7022 }
7023
7024 try {
7025 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7026 stackTrace)) {
7027 killCrashingAppCallback.run();
7028 return true;
7029 }
7030 } catch (RemoteException e) {
7031 mController = null;
7032 Watchdog.getInstance().setActivityController(null);
7033 }
7034 return false;
7035 }
7036 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007037
7038 @Override
7039 public void removeRecentTasksByPackageName(String packageName, int userId) {
7040 synchronized (mGlobalLock) {
7041 mRecentTasks.removeTasksByPackageName(packageName, userId);
7042 }
7043 }
7044
7045 @Override
7046 public void cleanupRecentTasksForUser(int userId) {
7047 synchronized (mGlobalLock) {
7048 mRecentTasks.cleanupLocked(userId);
7049 }
7050 }
7051
7052 @Override
7053 public void loadRecentTasksForUser(int userId) {
7054 synchronized (mGlobalLock) {
7055 mRecentTasks.loadUserRecentsLocked(userId);
7056 }
7057 }
7058
7059 @Override
7060 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7061 synchronized (mGlobalLock) {
7062 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7063 }
7064 }
7065
7066 @Override
7067 public void flushRecentTasks() {
7068 mRecentTasks.flush();
7069 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007070
7071 @Override
7072 public WindowProcessController getHomeProcess() {
7073 synchronized (mGlobalLock) {
7074 return mHomeProcess;
7075 }
7076 }
7077
7078 @Override
7079 public WindowProcessController getPreviousProcess() {
7080 synchronized (mGlobalLock) {
7081 return mPreviousProcess;
7082 }
7083 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007084
7085 @Override
7086 public void clearLockedTasks(String reason) {
7087 synchronized (mGlobalLock) {
7088 getLockTaskController().clearLockedTasks(reason);
7089 }
7090 }
7091
7092 @Override
7093 public void updateUserConfiguration() {
7094 synchronized (mGlobalLock) {
7095 final Configuration configuration = new Configuration(getGlobalConfiguration());
7096 final int currentUserId = mAmInternal.getCurrentUserId();
7097 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7098 configuration, currentUserId, Settings.System.canWrite(mContext));
7099 updateConfigurationLocked(configuration, null /* starting */,
7100 false /* initLocale */, false /* persistent */, currentUserId,
7101 false /* deferResume */);
7102 }
7103 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007104
7105 @Override
7106 public boolean canShowErrorDialogs() {
7107 synchronized (mGlobalLock) {
7108 return mShowDialogs && !mSleeping && !mShuttingDown
7109 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7110 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7111 mAmInternal.getCurrentUserId())
7112 && !(UserManager.isDeviceInDemoMode(mContext)
7113 && mAmInternal.getCurrentUser().isDemo());
7114 }
7115 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007116
7117 @Override
7118 public void setProfileApp(String profileApp) {
7119 synchronized (mGlobalLock) {
7120 mProfileApp = profileApp;
7121 }
7122 }
7123
7124 @Override
7125 public void setProfileProc(WindowProcessController wpc) {
7126 synchronized (mGlobalLock) {
7127 mProfileProc = wpc;
7128 }
7129 }
7130
7131 @Override
7132 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7133 synchronized (mGlobalLock) {
7134 mProfilerInfo = profilerInfo;
7135 }
7136 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007137
7138 @Override
7139 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7140 synchronized (mGlobalLock) {
7141 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7142 }
7143 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007144
7145 @Override
7146 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7147 synchronized (mGlobalLock) {
7148 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7149 }
7150 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007151
7152 @Override
7153 public boolean isUidForeground(int uid) {
7154 synchronized (mGlobalLock) {
7155 return ActivityTaskManagerService.this.isUidForeground(uid);
7156 }
7157 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007158
7159 @Override
7160 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7161 synchronized (mGlobalLock) {
7162 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7163 }
7164 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007165 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007166}