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