blob: 05aef68d7b2256889cb944e920819b41d1c94a67 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
88import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.server.LocalServices;
248import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700249import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700252import com.android.server.am.ActivityManagerService;
253import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
254import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
255import com.android.server.am.AppTimeTracker;
256import com.android.server.am.BaseErrorDialog;
257import com.android.server.am.EventLogTags;
258import com.android.server.am.PendingIntentController;
259import com.android.server.am.PendingIntentRecord;
260import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900261import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700262import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700263import com.android.server.pm.UserManagerService;
264import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700265import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266
Wale Ogunwale31913b52018-10-13 08:29:31 -0700267import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700270import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700273import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700274import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700275import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700277import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700278import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400280import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700283import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Map;
285import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286
287/**
288 * System service for managing activities and their containers (task, stacks, displays,... ).
289 *
290 * {@hide}
291 */
292public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700293 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700295 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
296 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
297 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
298 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
299 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700300 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700302 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700303 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 /** Used to indicate that an app transition should be animated. */
308 static final boolean ANIMATE = true;
309
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700310 /** Hardware-reported OpenGLES version. */
311 final int GL_ES_VERSION;
312
Wale Ogunwale31913b52018-10-13 08:29:31 -0700313 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
314 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
315 public static final String DUMP_LASTANR_CMD = "lastanr" ;
316 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
317 public static final String DUMP_STARTER_CMD = "starter" ;
318 public static final String DUMP_CONTAINERS_CMD = "containers" ;
319 public static final String DUMP_RECENTS_CMD = "recents" ;
320 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
321
Wale Ogunwale64258362018-10-16 15:13:37 -0700322 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
323 public static final int RELAUNCH_REASON_NONE = 0;
324 /** This activity is being relaunched due to windowing mode change. */
325 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
326 /** This activity is being relaunched due to a free-resize operation. */
327 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
328
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700329 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700330
Wale Ogunwalef6733932018-06-27 05:14:34 -0700331 /**
332 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
333 * change at runtime. Use mContext for non-UI purposes.
334 */
335 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700336 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700337 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700338 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700340 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700341 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800342 @VisibleForTesting
343 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 PowerManagerInternal mPowerManagerInternal;
345 private UsageStatsManagerInternal mUsageStatsInternal;
346
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700347 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 IntentFirewall mIntentFirewall;
349
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700350 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800351 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Riddle Hsud7088f82019-01-30 13:04:50 +0800352 /**
353 * It is the same instance as {@link mGlobalLock}, just declared as a type that the
354 * locked-region-code-injection does't recognize it. It is used to skip wrapping priority
355 * booster for places that are already in the scope of another booster (e.g. computing oom-adj).
356 *
357 * @see WindowManagerThreadPriorityBooster
358 */
359 final Object mGlobalLockWithoutBoost = mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700360 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800361 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700362 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700363 private UserManagerService mUserManager;
364 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700365 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700366 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
367 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700368 /** All processes currently running that might have a window organized by name. */
369 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700370 /** All processes we currently have running mapped by pid */
371 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700372 /** This is the process holding what we currently consider to be the "home" activity. */
373 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700374 /** The currently running heavy-weight process, if any. */
375 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700376 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700377 /**
378 * This is the process holding the activity the user last visited that is in a different process
379 * from the one they are currently in.
380 */
381 WindowProcessController mPreviousProcess;
382 /** The time at which the previous process was last visible. */
383 long mPreviousProcessVisibleTime;
384
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700385 /** List of intents that were used to start the most recent tasks. */
386 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700387 /** State of external calls telling us if the device is awake or asleep. */
388 private boolean mKeyguardShown = false;
389
390 // Wrapper around VoiceInteractionServiceManager
391 private AssistUtils mAssistUtils;
392
393 // VoiceInteraction session ID that changes for each new request except when
394 // being called for multi-window assist in a single session.
395 private int mViSessionId = 1000;
396
397 // How long to wait in getAssistContextExtras for the activity and foreground services
398 // to respond with the result.
399 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
400
401 // How long top wait when going through the modern assist (which doesn't need to block
402 // on getting this result before starting to launch its UI).
403 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
404
405 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
406 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
407
Alison Cichowlas3e340502018-08-07 17:15:01 -0400408 // Permission tokens are used to temporarily granted a trusted app the ability to call
409 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
410 // showing any appropriate error messages to the user.
411 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
412 10 * MINUTE_IN_MILLIS;
413
414 // How long before the service actually expires a token. This is slightly longer than
415 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
416 // expiration exception.
417 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
418 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
419
420 // How long the service will remember expired tokens, for the purpose of providing error
421 // messaging when a client uses an expired token.
422 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
423 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
424
425 // Activity tokens of system activities that are delegating their call to
426 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
427 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
428
429 // Permission tokens that have expired, but we remember for error reporting.
430 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
431
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700432 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
433
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700434 // Keeps track of the active voice interaction service component, notified from
435 // VoiceInteractionManagerService
436 ComponentName mActiveVoiceInteractionServiceComponent;
437
Wale Ogunwalee2172292018-10-25 10:11:10 -0700438 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700439 KeyguardController mKeyguardController;
440 private final ClientLifecycleManager mLifecycleManager;
441 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700442 /** The controller for all operations related to locktask. */
443 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700444 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700445
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700446 boolean mSuppressResizeConfigChanges;
447
448 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
449 new UpdateConfigurationResult();
450
451 static final class UpdateConfigurationResult {
452 // Configuration changes that were updated.
453 int changes;
454 // If the activity was relaunched to match the new configuration.
455 boolean activityRelaunched;
456
457 void reset() {
458 changes = 0;
459 activityRelaunched = false;
460 }
461 }
462
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700463 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700464 private int mConfigurationSeq;
465 // To cache the list of supported system locales
466 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700467
468 /**
469 * Temp object used when global and/or display override configuration is updated. It is also
470 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
471 * anyone...
472 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700473 private Configuration mTempConfig = new Configuration();
474
Wale Ogunwalef6733932018-06-27 05:14:34 -0700475 /** Temporary to avoid allocations. */
476 final StringBuilder mStringBuilder = new StringBuilder(256);
477
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700478 // Amount of time after a call to stopAppSwitches() during which we will
479 // prevent further untrusted switches from happening.
480 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
481
482 /**
483 * The time at which we will allow normal application switches again,
484 * after a call to {@link #stopAppSwitches()}.
485 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700486 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700487 /**
488 * This is set to true after the first switch after mAppSwitchesAllowedTime
489 * is set; any switches after that will clear the time.
490 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700491 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700492
493 IActivityController mController = null;
494 boolean mControllerIsAMonkey = false;
495
Wale Ogunwale214f3482018-10-04 11:00:47 -0700496 final int mFactoryTest;
497
498 /** Used to control how we initialize the service. */
499 ComponentName mTopComponent;
500 String mTopAction = Intent.ACTION_MAIN;
501 String mTopData;
502
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800503 /** Profiling app information. */
504 String mProfileApp = null;
505 WindowProcessController mProfileProc = null;
506 ProfilerInfo mProfilerInfo = null;
507
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700508 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700509 * Dump of the activity state at the time of the last ANR. Cleared after
510 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
511 */
512 String mLastANRState;
513
514 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700515 * Used to retain an update lock when the foreground activity is in
516 * immersive mode.
517 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700518 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700519
520 /**
521 * Packages that are being allowed to perform unrestricted app switches. Mapping is
522 * User -> Type -> uid.
523 */
524 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
525
526 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700527 private int mThumbnailWidth;
528 private int mThumbnailHeight;
529 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700530
531 /**
532 * Flag that indicates if multi-window is enabled.
533 *
534 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
535 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
536 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
537 * At least one of the forms of multi-window must be enabled in order for this flag to be
538 * initialized to 'true'.
539 *
540 * @see #mSupportsSplitScreenMultiWindow
541 * @see #mSupportsFreeformWindowManagement
542 * @see #mSupportsPictureInPicture
543 * @see #mSupportsMultiDisplay
544 */
545 boolean mSupportsMultiWindow;
546 boolean mSupportsSplitScreenMultiWindow;
547 boolean mSupportsFreeformWindowManagement;
548 boolean mSupportsPictureInPicture;
549 boolean mSupportsMultiDisplay;
550 boolean mForceResizableActivities;
551
552 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
553
554 // VR Vr2d Display Id.
555 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700556
Wale Ogunwalef6733932018-06-27 05:14:34 -0700557 /**
558 * Set while we are wanting to sleep, to prevent any
559 * activities from being started/resumed.
560 *
561 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
562 *
563 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
564 * while in the sleep state until there is a pending transition out of sleep, in which case
565 * mSleeping is set to false, and remains false while awake.
566 *
567 * Whether mSleeping can quickly toggled between true/false without the device actually
568 * display changing states is undefined.
569 */
570 private boolean mSleeping = false;
571
572 /**
573 * The process state used for processes that are running the top activities.
574 * This changes between TOP and TOP_SLEEPING to following mSleeping.
575 */
576 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
577
578 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
579 // automatically. Important for devices without direct input devices.
580 private boolean mShowDialogs = true;
581
582 /** Set if we are shutting down the system, similar to sleeping. */
583 boolean mShuttingDown = false;
584
585 /**
586 * We want to hold a wake lock while running a voice interaction session, since
587 * this may happen with the screen off and we need to keep the CPU running to
588 * be able to continue to interact with the user.
589 */
590 PowerManager.WakeLock mVoiceWakeLock;
591
592 /**
593 * Set while we are running a voice interaction. This overrides sleeping while it is active.
594 */
595 IVoiceInteractionSession mRunningVoice;
596
597 /**
598 * The last resumed activity. This is identical to the current resumed activity most
599 * of the time but could be different when we're pausing one activity before we resume
600 * another activity.
601 */
602 ActivityRecord mLastResumedActivity;
603
604 /**
605 * The activity that is currently being traced as the active resumed activity.
606 *
607 * @see #updateResumedAppTrace
608 */
609 private @Nullable ActivityRecord mTracedResumedActivity;
610
611 /** If non-null, we are tracking the time the user spends in the currently focused app. */
612 AppTimeTracker mCurAppTimeTracker;
613
Wale Ogunwale008163e2018-07-23 23:11:08 -0700614 private AppWarnings mAppWarnings;
615
Wale Ogunwale53783742018-09-16 10:21:51 -0700616 /**
617 * Packages that the user has asked to have run in screen size
618 * compatibility mode instead of filling the screen.
619 */
620 CompatModePackages mCompatModePackages;
621
Wale Ogunwalef6733932018-06-27 05:14:34 -0700622 private FontScaleSettingObserver mFontScaleSettingObserver;
623
Michal Karpinski4026cae2019-02-12 11:51:47 +0000624 private String mDeviceOwnerPackageName;
625
Wale Ogunwalef6733932018-06-27 05:14:34 -0700626 private final class FontScaleSettingObserver extends ContentObserver {
627 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
628 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
629
630 public FontScaleSettingObserver() {
631 super(mH);
632 final ContentResolver resolver = mContext.getContentResolver();
633 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
634 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
635 UserHandle.USER_ALL);
636 }
637
638 @Override
639 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
640 if (mFontScaleUri.equals(uri)) {
641 updateFontScaleIfNeeded(userId);
642 } else if (mHideErrorDialogsUri.equals(uri)) {
643 synchronized (mGlobalLock) {
644 updateShouldShowDialogsLocked(getGlobalConfiguration());
645 }
646 }
647 }
648 }
649
Charles Chen8d98dd22018-12-26 17:36:54 +0800650 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
651 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700652 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700653 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700654 mSystemThread = ActivityThread.currentActivityThread();
655 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700656 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800657 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700658 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700659 }
660
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700661 public void onSystemReady() {
662 synchronized (mGlobalLock) {
663 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
664 PackageManager.FEATURE_CANT_SAVE_STATE);
665 mAssistUtils = new AssistUtils(mContext);
666 mVrController.onSystemReady();
667 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700668 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700669 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void onInitPowerManagement() {
673 synchronized (mGlobalLock) {
674 mStackSupervisor.initPowerManagement();
675 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
676 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
677 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
678 mVoiceWakeLock.setReferenceCounted(false);
679 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700680 }
681
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700682 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700683 mFontScaleSettingObserver = new FontScaleSettingObserver();
684 }
685
Wale Ogunwale59507092018-10-29 09:00:30 -0700686 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700687 final boolean freeformWindowManagement =
688 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
689 || Settings.Global.getInt(
690 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
691
692 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
693 final boolean supportsPictureInPicture = supportsMultiWindow &&
694 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
695 final boolean supportsSplitScreenMultiWindow =
696 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
697 final boolean supportsMultiDisplay = mContext.getPackageManager()
698 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700699 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
700 final boolean forceResizable = Settings.Global.getInt(
701 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700702 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700703
704 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900705 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700706
707 final Configuration configuration = new Configuration();
708 Settings.System.getConfiguration(resolver, configuration);
709 if (forceRtl) {
710 // This will take care of setting the correct layout direction flags
711 configuration.setLayoutDirection(configuration.locale);
712 }
713
714 synchronized (mGlobalLock) {
715 mForceResizableActivities = forceResizable;
716 final boolean multiWindowFormEnabled = freeformWindowManagement
717 || supportsSplitScreenMultiWindow
718 || supportsPictureInPicture
719 || supportsMultiDisplay;
720 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
721 mSupportsMultiWindow = true;
722 mSupportsFreeformWindowManagement = freeformWindowManagement;
723 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
724 mSupportsPictureInPicture = supportsPictureInPicture;
725 mSupportsMultiDisplay = supportsMultiDisplay;
726 } else {
727 mSupportsMultiWindow = false;
728 mSupportsFreeformWindowManagement = false;
729 mSupportsSplitScreenMultiWindow = false;
730 mSupportsPictureInPicture = false;
731 mSupportsMultiDisplay = false;
732 }
733 mWindowManager.setForceResizableTasks(mForceResizableActivities);
734 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700735 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
736 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700737 // This happens before any activities are started, so we can change global configuration
738 // in-place.
739 updateConfigurationLocked(configuration, null, true);
740 final Configuration globalConfig = getGlobalConfiguration();
741 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
742
743 // Load resources only after the current configuration has been set.
744 final Resources res = mContext.getResources();
745 mThumbnailWidth = res.getDimensionPixelSize(
746 com.android.internal.R.dimen.thumbnail_width);
747 mThumbnailHeight = res.getDimensionPixelSize(
748 com.android.internal.R.dimen.thumbnail_height);
749
750 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
751 mFullscreenThumbnailScale = (float) res
752 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
753 (float) globalConfig.screenWidthDp;
754 } else {
755 mFullscreenThumbnailScale = res.getFraction(
756 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
757 }
758 }
759 }
760
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800761 public WindowManagerGlobalLock getGlobalLock() {
762 return mGlobalLock;
763 }
764
Riddle Hsud93a6c42018-11-29 21:50:06 +0800765 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
766 Looper looper) {
767 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700768 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700769 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700770 final File systemDir = SystemServiceManager.ensureSystemDir();
771 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
772 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700773 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700774
775 mTempConfig.setToDefaults();
776 mTempConfig.setLocales(LocaleList.getDefault());
777 mConfigurationSeq = mTempConfig.seq = 1;
778 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800779 mRootActivityContainer = new RootActivityContainer(this);
780 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700781
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700782 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700783 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700784 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700785 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700786 mRecentTasks = createRecentTasks();
787 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700788 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700789 mKeyguardController = mStackSupervisor.getKeyguardController();
790 }
791
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700792 public void onActivityManagerInternalAdded() {
793 synchronized (mGlobalLock) {
794 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
795 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
796 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700797 }
798
Yunfan Chen75157d72018-07-27 14:47:21 +0900799 int increaseConfigurationSeqLocked() {
800 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
801 return mConfigurationSeq;
802 }
803
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700804 protected ActivityStackSupervisor createStackSupervisor() {
805 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
806 supervisor.initialize();
807 return supervisor;
808 }
809
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700810 public void setWindowManager(WindowManagerService wm) {
811 synchronized (mGlobalLock) {
812 mWindowManager = wm;
813 mLockTaskController.setWindowManager(wm);
814 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800815 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700816 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700817 }
818
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700819 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
820 synchronized (mGlobalLock) {
821 mUsageStatsInternal = usageStatsManager;
822 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700823 }
824
Wale Ogunwalef6733932018-06-27 05:14:34 -0700825 UserManagerService getUserManager() {
826 if (mUserManager == null) {
827 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
828 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
829 }
830 return mUserManager;
831 }
832
833 AppOpsService getAppOpsService() {
834 if (mAppOpsService == null) {
835 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
836 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
837 }
838 return mAppOpsService;
839 }
840
841 boolean hasUserRestriction(String restriction, int userId) {
842 return getUserManager().hasUserRestriction(restriction, userId);
843 }
844
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700845 protected RecentTasks createRecentTasks() {
846 return new RecentTasks(this, mStackSupervisor);
847 }
848
849 RecentTasks getRecentTasks() {
850 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700851 }
852
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700853 ClientLifecycleManager getLifecycleManager() {
854 return mLifecycleManager;
855 }
856
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700857 ActivityStartController getActivityStartController() {
858 return mActivityStartController;
859 }
860
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700861 TaskChangeNotificationController getTaskChangeNotificationController() {
862 return mTaskChangeNotificationController;
863 }
864
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700865 LockTaskController getLockTaskController() {
866 return mLockTaskController;
867 }
868
Yunfan Chen75157d72018-07-27 14:47:21 +0900869 /**
870 * Return the global configuration used by the process corresponding to the input pid. This is
871 * usually the global configuration with some overrides specific to that process.
872 */
873 Configuration getGlobalConfigurationForCallingPid() {
874 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800875 return getGlobalConfigurationForPid(pid);
876 }
877
878 /**
879 * Return the global configuration used by the process corresponding to the given pid.
880 */
881 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900882 if (pid == MY_PID || pid < 0) {
883 return getGlobalConfiguration();
884 }
885 synchronized (mGlobalLock) {
886 final WindowProcessController app = mPidMap.get(pid);
887 return app != null ? app.getConfiguration() : getGlobalConfiguration();
888 }
889 }
890
891 /**
892 * Return the device configuration info used by the process corresponding to the input pid.
893 * The value is consistent with the global configuration for the process.
894 */
895 @Override
896 public ConfigurationInfo getDeviceConfigurationInfo() {
897 ConfigurationInfo config = new ConfigurationInfo();
898 synchronized (mGlobalLock) {
899 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
900 config.reqTouchScreen = globalConfig.touchscreen;
901 config.reqKeyboardType = globalConfig.keyboard;
902 config.reqNavigation = globalConfig.navigation;
903 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
904 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
905 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
906 }
907 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
908 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
909 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
910 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700911 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900912 }
913 return config;
914 }
915
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700916 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700917 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700918 }
919
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700920 public static final class Lifecycle extends SystemService {
921 private final ActivityTaskManagerService mService;
922
923 public Lifecycle(Context context) {
924 super(context);
925 mService = new ActivityTaskManagerService(context);
926 }
927
928 @Override
929 public void onStart() {
930 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700931 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700932 }
933
Garfield Tan891146c2018-10-09 12:14:00 -0700934 @Override
935 public void onUnlockUser(int userId) {
936 synchronized (mService.getGlobalLock()) {
937 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
938 }
939 }
940
941 @Override
942 public void onCleanupUser(int userId) {
943 synchronized (mService.getGlobalLock()) {
944 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
945 }
946 }
947
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700948 public ActivityTaskManagerService getService() {
949 return mService;
950 }
951 }
952
953 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700954 public final int startActivity(IApplicationThread caller, String callingPackage,
955 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
956 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
957 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
958 resultWho, requestCode, startFlags, profilerInfo, bOptions,
959 UserHandle.getCallingUserId());
960 }
961
962 @Override
963 public final int startActivities(IApplicationThread caller, String callingPackage,
964 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
965 int userId) {
966 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700967 enforceNotIsolatedCaller(reason);
968 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700969 // TODO: Switch to user app stacks here.
Michal Karpinski84d9ebd2019-01-17 18:28:59 +0000970 return getActivityStartController().startActivities(caller, -1, 0, -1, callingPackage,
971 intents, resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId,
972 reason, null /* originatingPendingIntent */,
973 false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700974 }
975
976 @Override
977 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
978 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
979 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
980 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
981 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
982 true /*validateIncomingUser*/);
983 }
984
985 int startActivityAsUser(IApplicationThread caller, String callingPackage,
986 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
987 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
988 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700989 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700990
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700991 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700992 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
993
994 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700995 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700996 .setCaller(caller)
997 .setCallingPackage(callingPackage)
998 .setResolvedType(resolvedType)
999 .setResultTo(resultTo)
1000 .setResultWho(resultWho)
1001 .setRequestCode(requestCode)
1002 .setStartFlags(startFlags)
1003 .setProfilerInfo(profilerInfo)
1004 .setActivityOptions(bOptions)
1005 .setMayWait(userId)
1006 .execute();
1007
1008 }
1009
1010 @Override
1011 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1012 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001013 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1014 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001015 // Refuse possible leaked file descriptors
1016 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1017 throw new IllegalArgumentException("File descriptors passed in Intent");
1018 }
1019
1020 if (!(target instanceof PendingIntentRecord)) {
1021 throw new IllegalArgumentException("Bad PendingIntent object");
1022 }
1023
1024 PendingIntentRecord pir = (PendingIntentRecord)target;
1025
1026 synchronized (mGlobalLock) {
1027 // If this is coming from the currently resumed activity, it is
1028 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001029 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001030 if (stack.mResumedActivity != null &&
1031 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001032 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001033 }
1034 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001035 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001036 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001037 }
1038
1039 @Override
1040 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1041 Bundle bOptions) {
1042 // Refuse possible leaked file descriptors
1043 if (intent != null && intent.hasFileDescriptors()) {
1044 throw new IllegalArgumentException("File descriptors passed in Intent");
1045 }
1046 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1047
1048 synchronized (mGlobalLock) {
1049 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1050 if (r == null) {
1051 SafeActivityOptions.abort(options);
1052 return false;
1053 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001054 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001055 // The caller is not running... d'oh!
1056 SafeActivityOptions.abort(options);
1057 return false;
1058 }
1059 intent = new Intent(intent);
1060 // The caller is not allowed to change the data.
1061 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1062 // And we are resetting to find the next component...
1063 intent.setComponent(null);
1064
1065 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1066
1067 ActivityInfo aInfo = null;
1068 try {
1069 List<ResolveInfo> resolves =
1070 AppGlobals.getPackageManager().queryIntentActivities(
1071 intent, r.resolvedType,
1072 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1073 UserHandle.getCallingUserId()).getList();
1074
1075 // Look for the original activity in the list...
1076 final int N = resolves != null ? resolves.size() : 0;
1077 for (int i=0; i<N; i++) {
1078 ResolveInfo rInfo = resolves.get(i);
1079 if (rInfo.activityInfo.packageName.equals(r.packageName)
1080 && rInfo.activityInfo.name.equals(r.info.name)) {
1081 // We found the current one... the next matching is
1082 // after it.
1083 i++;
1084 if (i<N) {
1085 aInfo = resolves.get(i).activityInfo;
1086 }
1087 if (debug) {
1088 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1089 + "/" + r.info.name);
1090 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1091 ? "null" : aInfo.packageName + "/" + aInfo.name));
1092 }
1093 break;
1094 }
1095 }
1096 } catch (RemoteException e) {
1097 }
1098
1099 if (aInfo == null) {
1100 // Nobody who is next!
1101 SafeActivityOptions.abort(options);
1102 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1103 return false;
1104 }
1105
1106 intent.setComponent(new ComponentName(
1107 aInfo.applicationInfo.packageName, aInfo.name));
1108 intent.setFlags(intent.getFlags()&~(
1109 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1110 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1111 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1112 FLAG_ACTIVITY_NEW_TASK));
1113
1114 // Okay now we need to start the new activity, replacing the currently running activity.
1115 // This is a little tricky because we want to start the new one as if the current one is
1116 // finished, but not finish the current one first so that there is no flicker.
1117 // And thus...
1118 final boolean wasFinishing = r.finishing;
1119 r.finishing = true;
1120
1121 // Propagate reply information over to the new activity.
1122 final ActivityRecord resultTo = r.resultTo;
1123 final String resultWho = r.resultWho;
1124 final int requestCode = r.requestCode;
1125 r.resultTo = null;
1126 if (resultTo != null) {
1127 resultTo.removeResultsLocked(r, resultWho, requestCode);
1128 }
1129
1130 final long origId = Binder.clearCallingIdentity();
1131 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001132 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001133 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001134 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001135 .setResolvedType(r.resolvedType)
1136 .setActivityInfo(aInfo)
1137 .setResultTo(resultTo != null ? resultTo.appToken : null)
1138 .setResultWho(resultWho)
1139 .setRequestCode(requestCode)
1140 .setCallingPid(-1)
1141 .setCallingUid(r.launchedFromUid)
1142 .setCallingPackage(r.launchedFromPackage)
1143 .setRealCallingPid(-1)
1144 .setRealCallingUid(r.launchedFromUid)
1145 .setActivityOptions(options)
1146 .execute();
1147 Binder.restoreCallingIdentity(origId);
1148
1149 r.finishing = wasFinishing;
1150 if (res != ActivityManager.START_SUCCESS) {
1151 return false;
1152 }
1153 return true;
1154 }
1155 }
1156
1157 @Override
1158 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1159 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1160 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1161 final WaitResult res = new WaitResult();
1162 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001163 enforceNotIsolatedCaller("startActivityAndWait");
1164 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1165 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001166 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001167 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001168 .setCaller(caller)
1169 .setCallingPackage(callingPackage)
1170 .setResolvedType(resolvedType)
1171 .setResultTo(resultTo)
1172 .setResultWho(resultWho)
1173 .setRequestCode(requestCode)
1174 .setStartFlags(startFlags)
1175 .setActivityOptions(bOptions)
1176 .setMayWait(userId)
1177 .setProfilerInfo(profilerInfo)
1178 .setWaitResult(res)
1179 .execute();
1180 }
1181 return res;
1182 }
1183
1184 @Override
1185 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1186 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1187 int startFlags, Configuration config, Bundle bOptions, int userId) {
1188 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001189 enforceNotIsolatedCaller("startActivityWithConfig");
1190 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1191 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001192 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001193 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 .setCaller(caller)
1195 .setCallingPackage(callingPackage)
1196 .setResolvedType(resolvedType)
1197 .setResultTo(resultTo)
1198 .setResultWho(resultWho)
1199 .setRequestCode(requestCode)
1200 .setStartFlags(startFlags)
1201 .setGlobalConfiguration(config)
1202 .setActivityOptions(bOptions)
1203 .setMayWait(userId)
1204 .execute();
1205 }
1206 }
1207
Alison Cichowlas3e340502018-08-07 17:15:01 -04001208
1209 @Override
1210 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1211 int callingUid = Binder.getCallingUid();
1212 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1213 throw new SecurityException("Only the system process can request a permission token, "
1214 + "received request from uid: " + callingUid);
1215 }
1216 IBinder permissionToken = new Binder();
1217 synchronized (mGlobalLock) {
1218 mStartActivitySources.put(permissionToken, delegatorToken);
1219 }
1220
1221 Message expireMsg = PooledLambda.obtainMessage(
1222 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1223 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1224
1225 Message forgetMsg = PooledLambda.obtainMessage(
1226 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1227 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1228
1229 return permissionToken;
1230 }
1231
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001232 @Override
1233 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1234 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001235 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1236 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001237 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001238 // permission grants) as any app that may launch one of your own activities. So we only
1239 // allow this in two cases:
1240 // 1) The caller is an activity that is part of the core framework, and then only when it
1241 // is running as the system.
1242 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1243 // can only be requested by a system activity, which may then delegate this call to
1244 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001245 final ActivityRecord sourceRecord;
1246 final int targetUid;
1247 final String targetPackage;
1248 final boolean isResolver;
1249 synchronized (mGlobalLock) {
1250 if (resultTo == null) {
1251 throw new SecurityException("Must be called from an activity");
1252 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001253 final IBinder sourceToken;
1254 if (permissionToken != null) {
1255 // To even attempt to use a permissionToken, an app must also have this signature
1256 // permission.
1257 mAmInternal.enforceCallingPermission(
1258 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1259 "startActivityAsCaller");
1260 // If called with a permissionToken, we want the sourceRecord from the delegator
1261 // activity that requested this token.
1262 sourceToken = mStartActivitySources.remove(permissionToken);
1263 if (sourceToken == null) {
1264 // Invalid permissionToken, check if it recently expired.
1265 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1266 throw new SecurityException("Called with expired permission token: "
1267 + permissionToken);
1268 } else {
1269 throw new SecurityException("Called with invalid permission token: "
1270 + permissionToken);
1271 }
1272 }
1273 } else {
1274 // This method was called directly by the source.
1275 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001276 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001277
Wale Ogunwaled32da472018-11-16 07:19:28 -08001278 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001279 if (sourceRecord == null) {
1280 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281 }
1282 if (sourceRecord.app == null) {
1283 throw new SecurityException("Called without a process attached to activity");
1284 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001285
1286 // Whether called directly or from a delegate, the source activity must be from the
1287 // android package.
1288 if (!sourceRecord.info.packageName.equals("android")) {
1289 throw new SecurityException("Must be called from an activity that is "
1290 + "declared in the android package");
1291 }
1292
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001293 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001294 // This is still okay, as long as this activity is running under the
1295 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001296 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001297 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001298 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001299 + " must be system uid or original calling uid "
1300 + sourceRecord.launchedFromUid);
1301 }
1302 }
1303 if (ignoreTargetSecurity) {
1304 if (intent.getComponent() == null) {
1305 throw new SecurityException(
1306 "Component must be specified with ignoreTargetSecurity");
1307 }
1308 if (intent.getSelector() != null) {
1309 throw new SecurityException(
1310 "Selector not allowed with ignoreTargetSecurity");
1311 }
1312 }
1313 targetUid = sourceRecord.launchedFromUid;
1314 targetPackage = sourceRecord.launchedFromPackage;
1315 isResolver = sourceRecord.isResolverOrChildActivity();
1316 }
1317
1318 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001319 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001320 }
1321
1322 // TODO: Switch to user app stacks here.
1323 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001324 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001325 .setCallingUid(targetUid)
1326 .setCallingPackage(targetPackage)
1327 .setResolvedType(resolvedType)
1328 .setResultTo(resultTo)
1329 .setResultWho(resultWho)
1330 .setRequestCode(requestCode)
1331 .setStartFlags(startFlags)
1332 .setActivityOptions(bOptions)
1333 .setMayWait(userId)
1334 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1335 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1336 .execute();
1337 } catch (SecurityException e) {
1338 // XXX need to figure out how to propagate to original app.
1339 // A SecurityException here is generally actually a fault of the original
1340 // calling activity (such as a fairly granting permissions), so propagate it
1341 // back to them.
1342 /*
1343 StringBuilder msg = new StringBuilder();
1344 msg.append("While launching");
1345 msg.append(intent.toString());
1346 msg.append(": ");
1347 msg.append(e.getMessage());
1348 */
1349 throw e;
1350 }
1351 }
1352
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001353 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1354 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1355 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1356 }
1357
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001358 @Override
1359 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1360 Intent intent, String resolvedType, IVoiceInteractionSession session,
1361 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1362 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001363 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001364 if (session == null || interactor == null) {
1365 throw new NullPointerException("null session or interactor");
1366 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001367 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001368 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001369 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001370 .setCallingUid(callingUid)
1371 .setCallingPackage(callingPackage)
1372 .setResolvedType(resolvedType)
1373 .setVoiceSession(session)
1374 .setVoiceInteractor(interactor)
1375 .setStartFlags(startFlags)
1376 .setProfilerInfo(profilerInfo)
1377 .setActivityOptions(bOptions)
1378 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001379 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001380 .execute();
1381 }
1382
1383 @Override
1384 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1385 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001386 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1387 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001388
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001389 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 .setCallingUid(callingUid)
1391 .setCallingPackage(callingPackage)
1392 .setResolvedType(resolvedType)
1393 .setActivityOptions(bOptions)
1394 .setMayWait(userId)
Michal Karpinski85fa2022019-02-08 12:05:09 +00001395 .setAllowBackgroundActivityStart(true)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396 .execute();
1397 }
1398
1399 @Override
1400 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1401 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001402 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001403 final int callingPid = Binder.getCallingPid();
1404 final long origId = Binder.clearCallingIdentity();
1405 try {
1406 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001407 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1408 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001409
1410 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001411 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1412 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001413 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1414 recentsUid, assistDataReceiver);
1415 }
1416 } finally {
1417 Binder.restoreCallingIdentity(origId);
1418 }
1419 }
1420
1421 @Override
1422 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001423 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001424 "startActivityFromRecents()");
1425
1426 final int callingPid = Binder.getCallingPid();
1427 final int callingUid = Binder.getCallingUid();
1428 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1429 final long origId = Binder.clearCallingIdentity();
1430 try {
1431 synchronized (mGlobalLock) {
1432 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1433 safeOptions);
1434 }
1435 } finally {
1436 Binder.restoreCallingIdentity(origId);
1437 }
1438 }
1439
1440 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001441 * Public API to check if the client is allowed to start an activity on specified display.
1442 *
1443 * If the target display is private or virtual, some restrictions will apply.
1444 *
1445 * @param displayId Target display id.
1446 * @param intent Intent used to launch the activity.
1447 * @param resolvedType The MIME type of the intent.
1448 * @param userId The id of the user for whom the call is made.
1449 * @return {@code true} if a call to start an activity on the target display should succeed and
1450 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1451 */
1452 @Override
1453 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1454 String resolvedType, int userId) {
1455 final int callingUid = Binder.getCallingUid();
1456 final int callingPid = Binder.getCallingPid();
1457 final long origId = Binder.clearCallingIdentity();
1458
1459 try {
1460 // Collect information about the target of the Intent.
1461 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1462 0 /* startFlags */, null /* profilerInfo */, userId,
1463 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1464 UserHandle.USER_NULL));
1465 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1466
1467 synchronized (mGlobalLock) {
1468 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1469 aInfo);
1470 }
1471 } finally {
1472 Binder.restoreCallingIdentity(origId);
1473 }
1474 }
1475
1476 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001477 * This is the internal entry point for handling Activity.finish().
1478 *
1479 * @param token The Binder token referencing the Activity we want to finish.
1480 * @param resultCode Result code, if any, from this Activity.
1481 * @param resultData Result data (Intent), if any, from this Activity.
1482 * @param finishTask Whether to finish the task associated with this Activity.
1483 *
1484 * @return Returns true if the activity successfully finished, or false if it is still running.
1485 */
1486 @Override
1487 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1488 int finishTask) {
1489 // Refuse possible leaked file descriptors
1490 if (resultData != null && resultData.hasFileDescriptors()) {
1491 throw new IllegalArgumentException("File descriptors passed in Intent");
1492 }
1493
1494 synchronized (mGlobalLock) {
1495 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1496 if (r == null) {
1497 return true;
1498 }
1499 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001500 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001501 ActivityRecord rootR = tr.getRootActivity();
1502 if (rootR == null) {
1503 Slog.w(TAG, "Finishing task with all activities already finished");
1504 }
1505 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1506 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001507 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 return false;
1509 }
1510
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001511 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1512 // We should consolidate.
1513 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001514 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001515 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001516 if (next != null) {
1517 // ask watcher if this is allowed
1518 boolean resumeOK = true;
1519 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001520 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001521 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001522 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001523 Watchdog.getInstance().setActivityController(null);
1524 }
1525
1526 if (!resumeOK) {
1527 Slog.i(TAG, "Not finishing activity because controller resumed");
1528 return false;
1529 }
1530 }
1531 }
1532 final long origId = Binder.clearCallingIdentity();
1533 try {
1534 boolean res;
1535 final boolean finishWithRootActivity =
1536 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1537 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1538 || (finishWithRootActivity && r == rootR)) {
1539 // If requested, remove the task that is associated to this activity only if it
1540 // was the root activity in the task. The result code and data is ignored
1541 // because we don't support returning them across task boundaries. Also, to
1542 // keep backwards compatibility we remove the task from recents when finishing
1543 // task with root activity.
1544 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1545 finishWithRootActivity, "finish-activity");
1546 if (!res) {
1547 Slog.i(TAG, "Removing task failed to finish activity");
1548 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001549 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001550 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001551 } else {
1552 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1553 resultData, "app-request", true);
1554 if (!res) {
1555 Slog.i(TAG, "Failed to finish by app-request");
1556 }
1557 }
1558 return res;
1559 } finally {
1560 Binder.restoreCallingIdentity(origId);
1561 }
1562 }
1563 }
1564
1565 @Override
1566 public boolean finishActivityAffinity(IBinder token) {
1567 synchronized (mGlobalLock) {
1568 final long origId = Binder.clearCallingIdentity();
1569 try {
1570 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1571 if (r == null) {
1572 return false;
1573 }
1574
1575 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1576 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001577 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001578 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001579 return false;
1580 }
1581 return task.getStack().finishActivityAffinityLocked(r);
1582 } finally {
1583 Binder.restoreCallingIdentity(origId);
1584 }
1585 }
1586 }
1587
1588 @Override
1589 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1590 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001591 try {
1592 WindowProcessController proc = null;
1593 synchronized (mGlobalLock) {
1594 ActivityStack stack = ActivityRecord.getStackLocked(token);
1595 if (stack == null) {
1596 return;
1597 }
1598 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1599 false /* fromTimeout */, false /* processPausingActivities */, config);
1600 if (r != null) {
1601 proc = r.app;
1602 }
1603 if (stopProfiling && proc != null) {
1604 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 }
1606 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001607 } finally {
1608 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001609 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001610 }
1611
1612 @Override
1613 public final void activityResumed(IBinder token) {
1614 final long origId = Binder.clearCallingIdentity();
1615 synchronized (mGlobalLock) {
1616 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001617 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001618 }
1619 Binder.restoreCallingIdentity(origId);
1620 }
1621
1622 @Override
1623 public final void activityPaused(IBinder token) {
1624 final long origId = Binder.clearCallingIdentity();
1625 synchronized (mGlobalLock) {
1626 ActivityStack stack = ActivityRecord.getStackLocked(token);
1627 if (stack != null) {
1628 stack.activityPausedLocked(token, false);
1629 }
1630 }
1631 Binder.restoreCallingIdentity(origId);
1632 }
1633
1634 @Override
1635 public final void activityStopped(IBinder token, Bundle icicle,
1636 PersistableBundle persistentState, CharSequence description) {
1637 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1638
1639 // Refuse possible leaked file descriptors
1640 if (icicle != null && icicle.hasFileDescriptors()) {
1641 throw new IllegalArgumentException("File descriptors passed in Bundle");
1642 }
1643
1644 final long origId = Binder.clearCallingIdentity();
1645
1646 synchronized (mGlobalLock) {
1647 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1648 if (r != null) {
1649 r.activityStoppedLocked(icicle, persistentState, description);
1650 }
1651 }
1652
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001653 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001654
1655 Binder.restoreCallingIdentity(origId);
1656 }
1657
1658 @Override
1659 public final void activityDestroyed(IBinder token) {
1660 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1661 synchronized (mGlobalLock) {
1662 ActivityStack stack = ActivityRecord.getStackLocked(token);
1663 if (stack != null) {
1664 stack.activityDestroyedLocked(token, "activityDestroyed");
1665 }
1666 }
1667 }
1668
1669 @Override
1670 public final void activityRelaunched(IBinder token) {
1671 final long origId = Binder.clearCallingIdentity();
1672 synchronized (mGlobalLock) {
1673 mStackSupervisor.activityRelaunchedLocked(token);
1674 }
1675 Binder.restoreCallingIdentity(origId);
1676 }
1677
1678 public final void activitySlept(IBinder token) {
1679 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1680
1681 final long origId = Binder.clearCallingIdentity();
1682
1683 synchronized (mGlobalLock) {
1684 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1685 if (r != null) {
1686 mStackSupervisor.activitySleptLocked(r);
1687 }
1688 }
1689
1690 Binder.restoreCallingIdentity(origId);
1691 }
1692
1693 @Override
1694 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1695 synchronized (mGlobalLock) {
1696 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1697 if (r == null) {
1698 return;
1699 }
1700 final long origId = Binder.clearCallingIdentity();
1701 try {
1702 r.setRequestedOrientation(requestedOrientation);
1703 } finally {
1704 Binder.restoreCallingIdentity(origId);
1705 }
1706 }
1707 }
1708
1709 @Override
1710 public int getRequestedOrientation(IBinder token) {
1711 synchronized (mGlobalLock) {
1712 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1713 if (r == null) {
1714 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1715 }
Riddle Hsu0a343c32018-12-21 00:40:48 +08001716 return r.getOrientation();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001717 }
1718 }
1719
1720 @Override
1721 public void setImmersive(IBinder token, boolean immersive) {
1722 synchronized (mGlobalLock) {
1723 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1724 if (r == null) {
1725 throw new IllegalArgumentException();
1726 }
1727 r.immersive = immersive;
1728
1729 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001730 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001731 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001732 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001733 }
1734 }
1735 }
1736
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001737 void applyUpdateLockStateLocked(ActivityRecord r) {
1738 // Modifications to the UpdateLock state are done on our handler, outside
1739 // the activity manager's locks. The new state is determined based on the
1740 // state *now* of the relevant activity record. The object is passed to
1741 // the handler solely for logging detail, not to be consulted/modified.
1742 final boolean nextState = r != null && r.immersive;
1743 mH.post(() -> {
1744 if (mUpdateLock.isHeld() != nextState) {
1745 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1746 "Applying new update lock state '" + nextState + "' for " + r);
1747 if (nextState) {
1748 mUpdateLock.acquire();
1749 } else {
1750 mUpdateLock.release();
1751 }
1752 }
1753 });
1754 }
1755
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001756 @Override
1757 public boolean isImmersive(IBinder token) {
1758 synchronized (mGlobalLock) {
1759 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1760 if (r == null) {
1761 throw new IllegalArgumentException();
1762 }
1763 return r.immersive;
1764 }
1765 }
1766
1767 @Override
1768 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001769 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001770 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001771 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001772 return (r != null) ? r.immersive : false;
1773 }
1774 }
1775
1776 @Override
1777 public void overridePendingTransition(IBinder token, String packageName,
1778 int enterAnim, int exitAnim) {
1779 synchronized (mGlobalLock) {
1780 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1781 if (self == null) {
1782 return;
1783 }
1784
1785 final long origId = Binder.clearCallingIdentity();
1786
1787 if (self.isState(
1788 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001789 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001790 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001791 }
1792
1793 Binder.restoreCallingIdentity(origId);
1794 }
1795 }
1796
1797 @Override
1798 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001799 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001801 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001802 if (r == null) {
1803 return ActivityManager.COMPAT_MODE_UNKNOWN;
1804 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001805 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001806 }
1807 }
1808
1809 @Override
1810 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001811 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001812 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001813 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001814 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001815 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001816 if (r == null) {
1817 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1818 return;
1819 }
1820 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001821 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001822 }
1823 }
1824
1825 @Override
1826 public int getLaunchedFromUid(IBinder activityToken) {
1827 ActivityRecord srec;
1828 synchronized (mGlobalLock) {
1829 srec = ActivityRecord.forTokenLocked(activityToken);
1830 }
1831 if (srec == null) {
1832 return -1;
1833 }
1834 return srec.launchedFromUid;
1835 }
1836
1837 @Override
1838 public String getLaunchedFromPackage(IBinder activityToken) {
1839 ActivityRecord srec;
1840 synchronized (mGlobalLock) {
1841 srec = ActivityRecord.forTokenLocked(activityToken);
1842 }
1843 if (srec == null) {
1844 return null;
1845 }
1846 return srec.launchedFromPackage;
1847 }
1848
1849 @Override
1850 public boolean convertFromTranslucent(IBinder token) {
1851 final long origId = Binder.clearCallingIdentity();
1852 try {
1853 synchronized (mGlobalLock) {
1854 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1855 if (r == null) {
1856 return false;
1857 }
1858 final boolean translucentChanged = r.changeWindowTranslucency(true);
1859 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001860 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001861 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001862 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001863 return translucentChanged;
1864 }
1865 } finally {
1866 Binder.restoreCallingIdentity(origId);
1867 }
1868 }
1869
1870 @Override
1871 public boolean convertToTranslucent(IBinder token, Bundle options) {
1872 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1873 final long origId = Binder.clearCallingIdentity();
1874 try {
1875 synchronized (mGlobalLock) {
1876 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1877 if (r == null) {
1878 return false;
1879 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001880 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001881 int index = task.mActivities.lastIndexOf(r);
1882 if (index > 0) {
1883 ActivityRecord under = task.mActivities.get(index - 1);
1884 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1885 }
1886 final boolean translucentChanged = r.changeWindowTranslucency(false);
1887 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001888 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001889 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001890 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001891 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001892 return translucentChanged;
1893 }
1894 } finally {
1895 Binder.restoreCallingIdentity(origId);
1896 }
1897 }
1898
1899 @Override
1900 public void notifyActivityDrawn(IBinder token) {
1901 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1902 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001903 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001904 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001905 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001906 }
1907 }
1908 }
1909
1910 @Override
1911 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1912 synchronized (mGlobalLock) {
1913 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1914 if (r == null) {
1915 return;
1916 }
1917 r.reportFullyDrawnLocked(restoredFromBundle);
1918 }
1919 }
1920
1921 @Override
1922 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1923 synchronized (mGlobalLock) {
1924 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1925 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1926 return stack.mDisplayId;
1927 }
1928 return DEFAULT_DISPLAY;
1929 }
1930 }
1931
1932 @Override
1933 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001934 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001935 long ident = Binder.clearCallingIdentity();
1936 try {
1937 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001938 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001940 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001941 }
1942 return null;
1943 }
1944 } finally {
1945 Binder.restoreCallingIdentity(ident);
1946 }
1947 }
1948
1949 @Override
1950 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001951 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001952 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1953 final long callingId = Binder.clearCallingIdentity();
1954 try {
1955 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001956 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001957 if (stack == null) {
1958 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1959 return;
1960 }
1961 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001962 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001963 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001964 }
1965 }
1966 } finally {
1967 Binder.restoreCallingIdentity(callingId);
1968 }
1969 }
1970
1971 @Override
1972 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001973 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001974 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1975 final long callingId = Binder.clearCallingIdentity();
1976 try {
1977 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001978 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001979 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001980 if (task == null) {
1981 return;
1982 }
1983 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001984 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001985 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001986 }
1987 }
1988 } finally {
1989 Binder.restoreCallingIdentity(callingId);
1990 }
1991 }
1992
1993 @Override
1994 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001995 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001996 synchronized (mGlobalLock) {
1997 final long ident = Binder.clearCallingIdentity();
1998 try {
1999 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
2000 "remove-task");
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
2003 }
2004 }
2005 }
2006
2007 @Override
Winson Chunge6439102018-07-30 15:48:01 -07002008 public void removeAllVisibleRecentTasks() {
2009 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
2010 synchronized (mGlobalLock) {
2011 final long ident = Binder.clearCallingIdentity();
2012 try {
2013 getRecentTasks().removeAllVisibleTasks();
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017 }
2018 }
2019
2020 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002021 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2022 synchronized (mGlobalLock) {
2023 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2024 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002025 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002026 }
2027 }
2028 return false;
2029 }
2030
2031 @Override
2032 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2033 Intent resultData) {
2034
2035 synchronized (mGlobalLock) {
2036 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2037 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002038 return r.getActivityStack().navigateUpToLocked(
2039 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002040 }
2041 return false;
2042 }
2043 }
2044
2045 /**
2046 * Attempts to move a task backwards in z-order (the order of activities within the task is
2047 * unchanged).
2048 *
2049 * There are several possible results of this call:
2050 * - if the task is locked, then we will show the lock toast
2051 * - if there is a task behind the provided task, then that task is made visible and resumed as
2052 * this task is moved to the back
2053 * - otherwise, if there are no other tasks in the stack:
2054 * - if this task is in the pinned stack, then we remove the stack completely, which will
2055 * have the effect of moving the task to the top or bottom of the fullscreen stack
2056 * (depending on whether it is visible)
2057 * - otherwise, we simply return home and hide this task
2058 *
2059 * @param token A reference to the activity we wish to move
2060 * @param nonRoot If false then this only works if the activity is the root
2061 * of a task; if true it will work for any activity in a task.
2062 * @return Returns true if the move completed, false if not.
2063 */
2064 @Override
2065 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002066 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002067 synchronized (mGlobalLock) {
2068 final long origId = Binder.clearCallingIdentity();
2069 try {
2070 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002071 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 if (task != null) {
2073 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2074 }
2075 } finally {
2076 Binder.restoreCallingIdentity(origId);
2077 }
2078 }
2079 return false;
2080 }
2081
2082 @Override
2083 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002084 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002085 long ident = Binder.clearCallingIdentity();
2086 Rect rect = new Rect();
2087 try {
2088 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002089 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002090 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2091 if (task == null) {
2092 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2093 return rect;
2094 }
2095 if (task.getStack() != null) {
2096 // Return the bounds from window manager since it will be adjusted for various
2097 // things like the presense of a docked stack for tasks that aren't resizeable.
2098 task.getWindowContainerBounds(rect);
2099 } else {
2100 // Task isn't in window manager yet since it isn't associated with a stack.
2101 // Return the persist value from activity manager
2102 if (!task.matchParentBounds()) {
2103 rect.set(task.getBounds());
2104 } else if (task.mLastNonFullscreenBounds != null) {
2105 rect.set(task.mLastNonFullscreenBounds);
2106 }
2107 }
2108 }
2109 } finally {
2110 Binder.restoreCallingIdentity(ident);
2111 }
2112 return rect;
2113 }
2114
2115 @Override
2116 public ActivityManager.TaskDescription getTaskDescription(int id) {
2117 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002118 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002119 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002120 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002121 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2122 if (tr != null) {
2123 return tr.lastTaskDescription;
2124 }
2125 }
2126 return null;
2127 }
2128
2129 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002130 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2131 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2132 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2133 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2134 return;
2135 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002136 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002137 synchronized (mGlobalLock) {
2138 final long ident = Binder.clearCallingIdentity();
2139 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002140 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002141 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002142 if (task == null) {
2143 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2144 return;
2145 }
2146
2147 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2148 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2149
2150 if (!task.isActivityTypeStandardOrUndefined()) {
2151 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2152 + " non-standard task " + taskId + " to windowing mode="
2153 + windowingMode);
2154 }
2155
2156 final ActivityStack stack = task.getStack();
2157 if (toTop) {
2158 stack.moveToFront("setTaskWindowingMode", task);
2159 }
2160 stack.setWindowingMode(windowingMode);
2161 } finally {
2162 Binder.restoreCallingIdentity(ident);
2163 }
2164 }
2165 }
2166
2167 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002168 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002169 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002170 ActivityRecord r = getCallingRecordLocked(token);
2171 return r != null ? r.info.packageName : null;
2172 }
2173 }
2174
2175 @Override
2176 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002177 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002178 ActivityRecord r = getCallingRecordLocked(token);
2179 return r != null ? r.intent.getComponent() : null;
2180 }
2181 }
2182
2183 private ActivityRecord getCallingRecordLocked(IBinder token) {
2184 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2185 if (r == null) {
2186 return null;
2187 }
2188 return r.resultTo;
2189 }
2190
2191 @Override
2192 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002193 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002194
2195 synchronized (mGlobalLock) {
2196 final long origId = Binder.clearCallingIdentity();
2197 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002198 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002199 } finally {
2200 Binder.restoreCallingIdentity(origId);
2201 }
2202 }
2203 }
2204
2205 /**
2206 * TODO: Add mController hook
2207 */
2208 @Override
2209 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002210 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002211
2212 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2213 synchronized (mGlobalLock) {
2214 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2215 false /* fromRecents */);
2216 }
2217 }
2218
2219 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2220 boolean fromRecents) {
2221
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002222 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 Binder.getCallingUid(), -1, -1, "Task to front")) {
2224 SafeActivityOptions.abort(options);
2225 return;
2226 }
2227 final long origId = Binder.clearCallingIdentity();
2228 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002229 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002230 if (task == null) {
2231 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002232 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002233 return;
2234 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002235 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002236 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002237 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002238 return;
2239 }
2240 ActivityOptions realOptions = options != null
2241 ? options.getOptions(mStackSupervisor)
2242 : null;
2243 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2244 false /* forceNonResizable */);
2245
2246 final ActivityRecord topActivity = task.getTopActivity();
2247 if (topActivity != null) {
2248
2249 // We are reshowing a task, use a starting window to hide the initial draw delay
2250 // so the transition can start earlier.
2251 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2252 true /* taskSwitch */, fromRecents);
2253 }
2254 } finally {
2255 Binder.restoreCallingIdentity(origId);
2256 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002257 }
2258
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002259 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2260 int callingPid, int callingUid, String name) {
2261 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2262 return true;
2263 }
2264
2265 if (getRecentTasks().isCallerRecents(sourceUid)) {
2266 return true;
2267 }
2268
2269 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2270 if (perm == PackageManager.PERMISSION_GRANTED) {
2271 return true;
2272 }
2273 if (checkAllowAppSwitchUid(sourceUid)) {
2274 return true;
2275 }
2276
2277 // If the actual IPC caller is different from the logical source, then
2278 // also see if they are allowed to control app switches.
2279 if (callingUid != -1 && callingUid != sourceUid) {
2280 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2281 if (perm == PackageManager.PERMISSION_GRANTED) {
2282 return true;
2283 }
2284 if (checkAllowAppSwitchUid(callingUid)) {
2285 return true;
2286 }
2287 }
2288
2289 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2290 return false;
2291 }
2292
2293 private boolean checkAllowAppSwitchUid(int uid) {
2294 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2295 if (types != null) {
2296 for (int i = types.size() - 1; i >= 0; i--) {
2297 if (types.valueAt(i).intValue() == uid) {
2298 return true;
2299 }
2300 }
2301 }
2302 return false;
2303 }
2304
2305 @Override
2306 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2307 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2308 "setActivityController()");
2309 synchronized (mGlobalLock) {
2310 mController = controller;
2311 mControllerIsAMonkey = imAMonkey;
2312 Watchdog.getInstance().setActivityController(controller);
2313 }
2314 }
2315
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002316 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002317 synchronized (mGlobalLock) {
2318 return mController != null && mControllerIsAMonkey;
2319 }
2320 }
2321
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002322 @Override
2323 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2324 synchronized (mGlobalLock) {
2325 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2326 }
2327 }
2328
2329 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002330 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2331 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2332 }
2333
2334 @Override
2335 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2336 @WindowConfiguration.ActivityType int ignoreActivityType,
2337 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2338 final int callingUid = Binder.getCallingUid();
2339 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2340
2341 synchronized (mGlobalLock) {
2342 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2343
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002344 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002345 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002346 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002347 ignoreWindowingMode, callingUid, allowed);
2348 }
2349
2350 return list;
2351 }
2352
2353 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002354 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2355 synchronized (mGlobalLock) {
2356 final long origId = Binder.clearCallingIdentity();
2357 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2358 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002359 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002360 }
2361 Binder.restoreCallingIdentity(origId);
2362 }
2363 }
2364
2365 @Override
2366 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002367 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002368 ActivityStack stack = ActivityRecord.getStackLocked(token);
2369 if (stack != null) {
2370 return stack.willActivityBeVisibleLocked(token);
2371 }
2372 return false;
2373 }
2374 }
2375
2376 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002377 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002378 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 synchronized (mGlobalLock) {
2380 final long ident = Binder.clearCallingIdentity();
2381 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002382 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002383 if (task == null) {
2384 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2385 return;
2386 }
2387
2388 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2389 + " to stackId=" + stackId + " toTop=" + toTop);
2390
Wale Ogunwaled32da472018-11-16 07:19:28 -08002391 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002392 if (stack == null) {
2393 throw new IllegalStateException(
2394 "moveTaskToStack: No stack for stackId=" + stackId);
2395 }
2396 if (!stack.isActivityTypeStandardOrUndefined()) {
2397 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2398 + taskId + " to stack " + stackId);
2399 }
2400 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002401 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002402 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2403 }
2404 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2405 "moveTaskToStack");
2406 } finally {
2407 Binder.restoreCallingIdentity(ident);
2408 }
2409 }
2410 }
2411
2412 @Override
2413 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2414 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002415 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002416
2417 final long ident = Binder.clearCallingIdentity();
2418 try {
2419 synchronized (mGlobalLock) {
2420 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002421 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002422 if (stack == null) {
2423 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2424 return;
2425 }
2426 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2427 throw new IllegalArgumentException("Stack: " + stackId
2428 + " doesn't support animated resize.");
2429 }
2430 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2431 animationDuration, false /* fromFullscreen */);
2432 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002433 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002434 if (stack == null) {
2435 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2436 return;
2437 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002438 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002439 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2440 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2441 }
2442 }
2443 } finally {
2444 Binder.restoreCallingIdentity(ident);
2445 }
2446 }
2447
wilsonshih5c4cf522019-01-25 09:03:47 +08002448 @Override
2449 public void offsetPinnedStackBounds(int stackId, Rect compareBounds, int xOffset, int yOffset,
2450 int animationDuration) {
2451 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "offsetPinnedStackBounds()");
2452
2453 final long ident = Binder.clearCallingIdentity();
2454 try {
2455 synchronized (mGlobalLock) {
2456 if (xOffset == 0 && yOffset == 0) {
2457 return;
2458 }
2459 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
2460 if (stack == null) {
2461 Slog.w(TAG, "offsetPinnedStackBounds: stackId " + stackId + " not found.");
2462 return;
2463 }
2464 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2465 throw new IllegalArgumentException("Stack: " + stackId
2466 + " doesn't support animated resize.");
2467 }
2468 final Rect destBounds = new Rect();
2469 stack.getAnimationOrCurrentBounds(destBounds);
2470 if (!destBounds.isEmpty() || !destBounds.equals(compareBounds)) {
2471 Slog.w(TAG, "The current stack bounds does not matched! It may be obsolete.");
2472 return;
2473 }
2474 destBounds.offset(xOffset, yOffset);
2475 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2476 animationDuration, false /* fromFullscreen */);
2477 }
2478 } finally {
2479 Binder.restoreCallingIdentity(ident);
2480 }
2481 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002482 /**
2483 * Moves the specified task to the primary-split-screen stack.
2484 *
2485 * @param taskId Id of task to move.
2486 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2487 * exist already. See
2488 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2489 * and
2490 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2491 * @param toTop If the task and stack should be moved to the top.
2492 * @param animate Whether we should play an animation for the moving the task.
2493 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2494 * stack. Pass {@code null} to use default bounds.
2495 * @param showRecents If the recents activity should be shown on the other side of the task
2496 * going into split-screen mode.
2497 */
2498 @Override
2499 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2500 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002501 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002502 "setTaskWindowingModeSplitScreenPrimary()");
2503 synchronized (mGlobalLock) {
2504 final long ident = Binder.clearCallingIdentity();
2505 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002506 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002507 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002508 if (task == null) {
2509 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2510 return false;
2511 }
2512 if (DEBUG_STACK) Slog.d(TAG_STACK,
2513 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2514 + " to createMode=" + createMode + " toTop=" + toTop);
2515 if (!task.isActivityTypeStandardOrUndefined()) {
2516 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2517 + " non-standard task " + taskId + " to split-screen windowing mode");
2518 }
2519
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002520 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002521 final int windowingMode = task.getWindowingMode();
2522 final ActivityStack stack = task.getStack();
2523 if (toTop) {
2524 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2525 }
2526 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002527 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2528 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002529 return windowingMode != task.getWindowingMode();
2530 } finally {
2531 Binder.restoreCallingIdentity(ident);
2532 }
2533 }
2534 }
2535
2536 /**
2537 * Removes stacks in the input windowing modes from the system if they are of activity type
2538 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2539 */
2540 @Override
2541 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002542 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002543 "removeStacksInWindowingModes()");
2544
2545 synchronized (mGlobalLock) {
2546 final long ident = Binder.clearCallingIdentity();
2547 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002548 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002549 } finally {
2550 Binder.restoreCallingIdentity(ident);
2551 }
2552 }
2553 }
2554
2555 @Override
2556 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002557 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002558 "removeStacksWithActivityTypes()");
2559
2560 synchronized (mGlobalLock) {
2561 final long ident = Binder.clearCallingIdentity();
2562 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002563 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002564 } finally {
2565 Binder.restoreCallingIdentity(ident);
2566 }
2567 }
2568 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002569
2570 @Override
2571 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2572 int userId) {
2573 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002574 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2575 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002577 final boolean detailed = checkGetTasksPermission(
2578 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2579 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002580 == PackageManager.PERMISSION_GRANTED;
2581
2582 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002583 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002584 callingUid);
2585 }
2586 }
2587
2588 @Override
2589 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002590 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002591 long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002594 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002595 }
2596 } finally {
2597 Binder.restoreCallingIdentity(ident);
2598 }
2599 }
2600
2601 @Override
2602 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002603 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002604 long ident = Binder.clearCallingIdentity();
2605 try {
2606 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002607 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002608 }
2609 } finally {
2610 Binder.restoreCallingIdentity(ident);
2611 }
2612 }
2613
2614 @Override
2615 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002616 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002617 final long callingUid = Binder.getCallingUid();
2618 final long origId = Binder.clearCallingIdentity();
2619 try {
2620 synchronized (mGlobalLock) {
2621 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002622 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002623 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2624 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2625 }
2626 } finally {
2627 Binder.restoreCallingIdentity(origId);
2628 }
2629 }
2630
2631 @Override
2632 public void startLockTaskModeByToken(IBinder token) {
2633 synchronized (mGlobalLock) {
2634 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2635 if (r == null) {
2636 return;
2637 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002638 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002639 }
2640 }
2641
2642 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002643 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002644 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002645 // This makes inner call to look as if it was initiated by system.
2646 long ident = Binder.clearCallingIdentity();
2647 try {
2648 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002649 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002650 MATCH_TASK_IN_STACKS_ONLY);
2651 if (task == null) {
2652 return;
2653 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002654
2655 // When starting lock task mode the stack must be in front and focused
2656 task.getStack().moveToFront("startSystemLockTaskMode");
2657 startLockTaskModeLocked(task, true /* isSystemCaller */);
2658 }
2659 } finally {
2660 Binder.restoreCallingIdentity(ident);
2661 }
2662 }
2663
2664 @Override
2665 public void stopLockTaskModeByToken(IBinder token) {
2666 synchronized (mGlobalLock) {
2667 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2668 if (r == null) {
2669 return;
2670 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002671 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002672 }
2673 }
2674
2675 /**
2676 * This API should be called by SystemUI only when user perform certain action to dismiss
2677 * lock task mode. We should only dismiss pinned lock task mode in this case.
2678 */
2679 @Override
2680 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002681 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002682 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2683 }
2684
2685 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2686 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2687 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2688 return;
2689 }
2690
Wale Ogunwaled32da472018-11-16 07:19:28 -08002691 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002692 if (stack == null || task != stack.topTask()) {
2693 throw new IllegalArgumentException("Invalid task, not in foreground");
2694 }
2695
2696 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2697 // system or a specific app.
2698 // * System-initiated requests will only start the pinned mode (screen pinning)
2699 // * App-initiated requests
2700 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2701 // - will start the pinned mode, otherwise
2702 final int callingUid = Binder.getCallingUid();
2703 long ident = Binder.clearCallingIdentity();
2704 try {
2705 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002706 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002707
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002708 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002709 } finally {
2710 Binder.restoreCallingIdentity(ident);
2711 }
2712 }
2713
2714 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2715 final int callingUid = Binder.getCallingUid();
2716 long ident = Binder.clearCallingIdentity();
2717 try {
2718 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002719 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 }
2721 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2722 // task and jumping straight into a call in the case of emergency call back.
2723 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2724 if (tm != null) {
2725 tm.showInCallScreen(false);
2726 }
2727 } finally {
2728 Binder.restoreCallingIdentity(ident);
2729 }
2730 }
2731
2732 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002733 public void updateLockTaskPackages(int userId, String[] packages) {
2734 final int callingUid = Binder.getCallingUid();
2735 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2736 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2737 "updateLockTaskPackages()");
2738 }
2739 synchronized (this) {
2740 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2741 + Arrays.toString(packages));
2742 getLockTaskController().updateLockTaskPackages(userId, packages);
2743 }
2744 }
2745
2746 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002747 public boolean isInLockTaskMode() {
2748 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2749 }
2750
2751 @Override
2752 public int getLockTaskModeState() {
2753 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002754 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002755 }
2756 }
2757
2758 @Override
2759 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2760 synchronized (mGlobalLock) {
2761 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2762 if (r != null) {
2763 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002764 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002765 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002766 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002767 }
2768 }
2769 }
2770
2771 @Override
2772 public Bundle getActivityOptions(IBinder token) {
2773 final long origId = Binder.clearCallingIdentity();
2774 try {
2775 synchronized (mGlobalLock) {
2776 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2777 if (r != null) {
2778 final ActivityOptions activityOptions = r.takeOptionsLocked();
2779 return activityOptions == null ? null : activityOptions.toBundle();
2780 }
2781 return null;
2782 }
2783 } finally {
2784 Binder.restoreCallingIdentity(origId);
2785 }
2786 }
2787
2788 @Override
2789 public List<IBinder> getAppTasks(String callingPackage) {
2790 int callingUid = Binder.getCallingUid();
2791 long ident = Binder.clearCallingIdentity();
2792 try {
2793 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002794 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(ident);
2798 }
2799 }
2800
2801 @Override
2802 public void finishVoiceTask(IVoiceInteractionSession session) {
2803 synchronized (mGlobalLock) {
2804 final long origId = Binder.clearCallingIdentity();
2805 try {
2806 // TODO: VI Consider treating local voice interactions and voice tasks
2807 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002808 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002809 } finally {
2810 Binder.restoreCallingIdentity(origId);
2811 }
2812 }
2813
2814 }
2815
2816 @Override
2817 public boolean isTopOfTask(IBinder token) {
2818 synchronized (mGlobalLock) {
2819 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002820 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002821 }
2822 }
2823
2824 @Override
2825 public void notifyLaunchTaskBehindComplete(IBinder token) {
2826 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2827 }
2828
2829 @Override
2830 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002831 mH.post(() -> {
2832 synchronized (mGlobalLock) {
2833 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002834 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002835 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002836 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002837 } catch (RemoteException e) {
2838 }
2839 }
2840 }
2841
2842 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002843 }
2844
2845 /** Called from an app when assist data is ready. */
2846 @Override
2847 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2848 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002849 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002850 synchronized (pae) {
2851 pae.result = extras;
2852 pae.structure = structure;
2853 pae.content = content;
2854 if (referrer != null) {
2855 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2856 }
2857 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002858 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002859 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2860 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002861 structure.setHomeActivity(pae.isHome);
2862 }
2863 pae.haveResult = true;
2864 pae.notifyAll();
2865 if (pae.intent == null && pae.receiver == null) {
2866 // Caller is just waiting for the result.
2867 return;
2868 }
2869 }
2870 // We are now ready to launch the assist activity.
2871 IAssistDataReceiver sendReceiver = null;
2872 Bundle sendBundle = null;
2873 synchronized (mGlobalLock) {
2874 buildAssistBundleLocked(pae, extras);
2875 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002876 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002877 if (!exists) {
2878 // Timed out.
2879 return;
2880 }
2881
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002882 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002883 // Caller wants result sent back to them.
2884 sendBundle = new Bundle();
2885 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2886 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2887 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2888 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2889 }
2890 }
2891 if (sendReceiver != null) {
2892 try {
2893 sendReceiver.onHandleAssistData(sendBundle);
2894 } catch (RemoteException e) {
2895 }
2896 return;
2897 }
2898
2899 final long ident = Binder.clearCallingIdentity();
2900 try {
2901 if (TextUtils.equals(pae.intent.getAction(),
2902 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2903 pae.intent.putExtras(pae.extras);
2904 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2905 } else {
2906 pae.intent.replaceExtras(pae.extras);
2907 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2908 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2909 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002910 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002911
2912 try {
2913 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2914 } catch (ActivityNotFoundException e) {
2915 Slog.w(TAG, "No activity to handle assist action.", e);
2916 }
2917 }
2918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
2921 }
2922
2923 @Override
2924 public int addAppTask(IBinder activityToken, Intent intent,
2925 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2926 final int callingUid = Binder.getCallingUid();
2927 final long callingIdent = Binder.clearCallingIdentity();
2928
2929 try {
2930 synchronized (mGlobalLock) {
2931 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2932 if (r == null) {
2933 throw new IllegalArgumentException("Activity does not exist; token="
2934 + activityToken);
2935 }
2936 ComponentName comp = intent.getComponent();
2937 if (comp == null) {
2938 throw new IllegalArgumentException("Intent " + intent
2939 + " must specify explicit component");
2940 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002941 if (thumbnail.getWidth() != mThumbnailWidth
2942 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002943 throw new IllegalArgumentException("Bad thumbnail size: got "
2944 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002945 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002946 }
2947 if (intent.getSelector() != null) {
2948 intent.setSelector(null);
2949 }
2950 if (intent.getSourceBounds() != null) {
2951 intent.setSourceBounds(null);
2952 }
2953 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2954 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2955 // The caller has added this as an auto-remove task... that makes no
2956 // sense, so turn off auto-remove.
2957 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2958 }
2959 }
2960 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2961 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2962 if (ainfo.applicationInfo.uid != callingUid) {
2963 throw new SecurityException(
2964 "Can't add task for another application: target uid="
2965 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2966 }
2967
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002968 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002970 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002971 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002972 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002973 // The app has too many tasks already and we can't add any more
2974 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2975 return INVALID_TASK_ID;
2976 }
2977 task.lastTaskDescription.copyFrom(description);
2978
2979 // TODO: Send the thumbnail to WM to store it.
2980
2981 return task.taskId;
2982 }
2983 } finally {
2984 Binder.restoreCallingIdentity(callingIdent);
2985 }
2986 }
2987
2988 @Override
2989 public Point getAppTaskThumbnailSize() {
2990 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002991 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002992 }
2993 }
2994
2995 @Override
2996 public void setTaskResizeable(int taskId, int resizeableMode) {
2997 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002998 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002999 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
3000 if (task == null) {
3001 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
3002 return;
3003 }
3004 task.setResizeMode(resizeableMode);
3005 }
3006 }
3007
3008 @Override
3009 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003010 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003011 long ident = Binder.clearCallingIdentity();
3012 try {
3013 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003014 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08003015 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003016 if (task == null) {
3017 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
3018 return;
3019 }
3020 // Place the task in the right stack if it isn't there already based on
3021 // the requested bounds.
3022 // The stack transition logic is:
3023 // - a null bounds on a freeform task moves that task to fullscreen
3024 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
3025 // that task to freeform
3026 // - otherwise the task is not moved
3027 ActivityStack stack = task.getStack();
3028 if (!task.getWindowConfiguration().canResizeTask()) {
3029 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
3030 }
3031 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
3032 stack = stack.getDisplay().getOrCreateStack(
3033 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
3034 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
3035 stack = stack.getDisplay().getOrCreateStack(
3036 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
3037 }
3038
3039 // Reparent the task to the right stack if necessary
3040 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
3041 if (stack != task.getStack()) {
3042 // Defer resume until the task is resized below
3043 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
3044 DEFER_RESUME, "resizeTask");
3045 preserveWindow = false;
3046 }
3047
3048 // After reparenting (which only resizes the task to the stack bounds), resize the
3049 // task to the actual bounds provided
3050 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3051 }
3052 } finally {
3053 Binder.restoreCallingIdentity(ident);
3054 }
3055 }
3056
3057 @Override
3058 public boolean releaseActivityInstance(IBinder token) {
3059 synchronized (mGlobalLock) {
3060 final long origId = Binder.clearCallingIdentity();
3061 try {
3062 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3063 if (r == null) {
3064 return false;
3065 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003066 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003067 } finally {
3068 Binder.restoreCallingIdentity(origId);
3069 }
3070 }
3071 }
3072
3073 @Override
3074 public void releaseSomeActivities(IApplicationThread appInt) {
3075 synchronized (mGlobalLock) {
3076 final long origId = Binder.clearCallingIdentity();
3077 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003078 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003079 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 } finally {
3081 Binder.restoreCallingIdentity(origId);
3082 }
3083 }
3084 }
3085
3086 @Override
3087 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003088 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003089 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003090 != PackageManager.PERMISSION_GRANTED) {
3091 throw new SecurityException("Requires permission "
3092 + android.Manifest.permission.DEVICE_POWER);
3093 }
3094
3095 synchronized (mGlobalLock) {
3096 long ident = Binder.clearCallingIdentity();
3097 if (mKeyguardShown != keyguardShowing) {
3098 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003099 final Message msg = PooledLambda.obtainMessage(
3100 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3101 keyguardShowing);
3102 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003103 }
3104 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003105 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003106 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003107 } finally {
3108 Binder.restoreCallingIdentity(ident);
3109 }
3110 }
3111
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003112 mH.post(() -> {
3113 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3114 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3115 }
3116 });
3117 }
3118
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003119 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003120 mH.post(() -> {
3121 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3122 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3123 }
3124 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003125 }
3126
3127 @Override
3128 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003129 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3130 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003131
3132 final File passedIconFile = new File(filePath);
3133 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3134 passedIconFile.getName());
3135 if (!legitIconFile.getPath().equals(filePath)
3136 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3137 throw new IllegalArgumentException("Bad file path: " + filePath
3138 + " passed for userId " + userId);
3139 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003140 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003141 }
3142
3143 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003144 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003145 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3146 final ActivityOptions activityOptions = safeOptions != null
3147 ? safeOptions.getOptions(mStackSupervisor)
3148 : null;
3149 if (activityOptions == null
3150 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3151 || activityOptions.getCustomInPlaceResId() == 0) {
3152 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3153 "with valid animation");
3154 }
lumark588a3e82018-07-20 18:53:54 +08003155 // Get top display of front most application.
3156 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3157 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003158 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3159 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3160 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003161 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003162 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003163 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003164 }
3165
3166 @Override
3167 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003168 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003169 synchronized (mGlobalLock) {
3170 final long ident = Binder.clearCallingIdentity();
3171 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003172 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003173 if (stack == null) {
3174 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3175 return;
3176 }
3177 if (!stack.isActivityTypeStandardOrUndefined()) {
3178 throw new IllegalArgumentException(
3179 "Removing non-standard stack is not allowed.");
3180 }
3181 mStackSupervisor.removeStack(stack);
3182 } finally {
3183 Binder.restoreCallingIdentity(ident);
3184 }
3185 }
3186 }
3187
3188 @Override
3189 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003190 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003191
3192 synchronized (mGlobalLock) {
3193 final long ident = Binder.clearCallingIdentity();
3194 try {
3195 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3196 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003197 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003198 } finally {
3199 Binder.restoreCallingIdentity(ident);
3200 }
3201 }
3202 }
3203
3204 @Override
Yunfan Chend967af82019-01-17 18:30:18 +09003205 public void toggleFreeformWindowingMode(IBinder token) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 synchronized (mGlobalLock) {
3207 long ident = Binder.clearCallingIdentity();
3208 try {
3209 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3210 if (r == null) {
3211 throw new IllegalArgumentException(
Yunfan Chend967af82019-01-17 18:30:18 +09003212 "toggleFreeformWindowingMode: No activity record matching token="
3213 + token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003214 }
3215
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003216 final ActivityStack stack = r.getActivityStack();
Yunfan Chend967af82019-01-17 18:30:18 +09003217 if (stack == null) {
3218 throw new IllegalStateException("toggleFreeformWindowingMode: the activity "
3219 + "doesn't have a stack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003220 }
3221
Yunfan Chend967af82019-01-17 18:30:18 +09003222 if (!stack.inFreeformWindowingMode()
3223 && stack.getWindowingMode() != WINDOWING_MODE_FULLSCREEN) {
3224 throw new IllegalStateException("toggleFreeformWindowingMode: You can only "
3225 + "toggle between fullscreen and freeform.");
3226 }
3227
3228 if (stack.inFreeformWindowingMode()) {
3229 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3230 } else {
3231 stack.setWindowingMode(WINDOWING_MODE_FREEFORM);
3232 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003233 } finally {
3234 Binder.restoreCallingIdentity(ident);
3235 }
3236 }
3237 }
3238
3239 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3240 @Override
3241 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003242 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003243 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003244 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003245 }
3246
3247 /** Unregister a task stack listener so that it stops receiving callbacks. */
3248 @Override
3249 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003250 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003251 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003252 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003253 }
3254
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003255 @Override
3256 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3257 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3258 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3259 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3260 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3261 }
3262
3263 @Override
3264 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3265 IBinder activityToken, int flags) {
3266 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3267 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3268 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3269 }
3270
3271 @Override
3272 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3273 Bundle args) {
3274 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3275 true /* focused */, true /* newSessionId */, userHandle, args,
3276 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3277 }
3278
3279 @Override
3280 public Bundle getAssistContextExtras(int requestType) {
3281 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3282 null, null, true /* focused */, true /* newSessionId */,
3283 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3284 if (pae == null) {
3285 return null;
3286 }
3287 synchronized (pae) {
3288 while (!pae.haveResult) {
3289 try {
3290 pae.wait();
3291 } catch (InterruptedException e) {
3292 }
3293 }
3294 }
3295 synchronized (mGlobalLock) {
3296 buildAssistBundleLocked(pae, pae.result);
3297 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003298 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003299 }
3300 return pae.extras;
3301 }
3302
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003303 /**
3304 * Binder IPC calls go through the public entry point.
3305 * This can be called with or without the global lock held.
3306 */
3307 private static int checkCallingPermission(String permission) {
3308 return checkPermission(
3309 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3310 }
3311
3312 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003313 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003314 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3315 mAmInternal.enforceCallingPermission(permission, func);
3316 }
3317 }
3318
3319 @VisibleForTesting
3320 int checkGetTasksPermission(String permission, int pid, int uid) {
3321 return checkPermission(permission, pid, uid);
3322 }
3323
3324 static int checkPermission(String permission, int pid, int uid) {
3325 if (permission == null) {
3326 return PackageManager.PERMISSION_DENIED;
3327 }
3328 return checkComponentPermission(permission, pid, uid, -1, true);
3329 }
3330
Wale Ogunwale214f3482018-10-04 11:00:47 -07003331 public static int checkComponentPermission(String permission, int pid, int uid,
3332 int owningUid, boolean exported) {
3333 return ActivityManagerService.checkComponentPermission(
3334 permission, pid, uid, owningUid, exported);
3335 }
3336
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003337 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3338 if (getRecentTasks().isCallerRecents(callingUid)) {
3339 // Always allow the recents component to get tasks
3340 return true;
3341 }
3342
3343 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3344 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3345 if (!allowed) {
3346 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3347 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3348 // Temporary compatibility: some existing apps on the system image may
3349 // still be requesting the old permission and not switched to the new
3350 // one; if so, we'll still allow them full access. This means we need
3351 // to see if they are holding the old permission and are a system app.
3352 try {
3353 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3354 allowed = true;
3355 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3356 + " is using old GET_TASKS but privileged; allowing");
3357 }
3358 } catch (RemoteException e) {
3359 }
3360 }
3361 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3362 + " does not hold REAL_GET_TASKS; limiting output");
3363 }
3364 return allowed;
3365 }
3366
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003367 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3368 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3369 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3370 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003371 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003372 "enqueueAssistContext()");
3373
3374 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003375 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003376 if (activity == null) {
3377 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3378 return null;
3379 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003380 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003381 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3382 return null;
3383 }
3384 if (focused) {
3385 if (activityToken != null) {
3386 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3387 if (activity != caller) {
3388 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3389 + " is not current top " + activity);
3390 return null;
3391 }
3392 }
3393 } else {
3394 activity = ActivityRecord.forTokenLocked(activityToken);
3395 if (activity == null) {
3396 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3397 + " couldn't be found");
3398 return null;
3399 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003400 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003401 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3402 return null;
3403 }
3404 }
3405
3406 PendingAssistExtras pae;
3407 Bundle extras = new Bundle();
3408 if (args != null) {
3409 extras.putAll(args);
3410 }
3411 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003412 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003413
3414 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3415 userHandle);
3416 pae.isHome = activity.isActivityTypeHome();
3417
3418 // Increment the sessionId if necessary
3419 if (newSessionId) {
3420 mViSessionId++;
3421 }
3422 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003423 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3424 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003425 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003426 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003427 } catch (RemoteException e) {
3428 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3429 return null;
3430 }
3431 return pae;
3432 }
3433 }
3434
3435 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3436 if (result != null) {
3437 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3438 }
3439 if (pae.hint != null) {
3440 pae.extras.putBoolean(pae.hint, true);
3441 }
3442 }
3443
3444 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3445 IAssistDataReceiver receiver;
3446 synchronized (mGlobalLock) {
3447 mPendingAssistExtras.remove(pae);
3448 receiver = pae.receiver;
3449 }
3450 if (receiver != null) {
3451 // Caller wants result sent back to them.
3452 Bundle sendBundle = new Bundle();
3453 // At least return the receiver extras
3454 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3455 try {
3456 pae.receiver.onHandleAssistData(sendBundle);
3457 } catch (RemoteException e) {
3458 }
3459 }
3460 }
3461
3462 public class PendingAssistExtras extends Binder implements Runnable {
3463 public final ActivityRecord activity;
3464 public boolean isHome;
3465 public final Bundle extras;
3466 public final Intent intent;
3467 public final String hint;
3468 public final IAssistDataReceiver receiver;
3469 public final int userHandle;
3470 public boolean haveResult = false;
3471 public Bundle result = null;
3472 public AssistStructure structure = null;
3473 public AssistContent content = null;
3474 public Bundle receiverExtras;
3475
3476 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3477 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3478 int _userHandle) {
3479 activity = _activity;
3480 extras = _extras;
3481 intent = _intent;
3482 hint = _hint;
3483 receiver = _receiver;
3484 receiverExtras = _receiverExtras;
3485 userHandle = _userHandle;
3486 }
3487
3488 @Override
3489 public void run() {
3490 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3491 synchronized (this) {
3492 haveResult = true;
3493 notifyAll();
3494 }
3495 pendingAssistExtrasTimedOut(this);
3496 }
3497 }
3498
3499 @Override
3500 public boolean isAssistDataAllowedOnCurrentActivity() {
3501 int userId;
3502 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003503 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003504 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3505 return false;
3506 }
3507
3508 final ActivityRecord activity = focusedStack.getTopActivity();
3509 if (activity == null) {
3510 return false;
3511 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003512 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003513 }
3514 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3515 }
3516
3517 @Override
3518 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3519 long ident = Binder.clearCallingIdentity();
3520 try {
3521 synchronized (mGlobalLock) {
3522 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003523 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003524 if (top != caller) {
3525 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3526 + " is not current top " + top);
3527 return false;
3528 }
3529 if (!top.nowVisible) {
3530 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3531 + " is not visible");
3532 return false;
3533 }
3534 }
3535 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3536 token);
3537 } finally {
3538 Binder.restoreCallingIdentity(ident);
3539 }
3540 }
3541
3542 @Override
3543 public boolean isRootVoiceInteraction(IBinder token) {
3544 synchronized (mGlobalLock) {
3545 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3546 if (r == null) {
3547 return false;
3548 }
3549 return r.rootVoiceInteraction;
3550 }
3551 }
3552
Wale Ogunwalef6733932018-06-27 05:14:34 -07003553 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3554 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3555 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3556 if (activityToCallback == null) return;
3557 activityToCallback.setVoiceSessionLocked(voiceSession);
3558
3559 // Inform the activity
3560 try {
3561 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3562 voiceInteractor);
3563 long token = Binder.clearCallingIdentity();
3564 try {
3565 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3566 } finally {
3567 Binder.restoreCallingIdentity(token);
3568 }
3569 // TODO: VI Should we cache the activity so that it's easier to find later
3570 // rather than scan through all the stacks and activities?
3571 } catch (RemoteException re) {
3572 activityToCallback.clearVoiceSessionLocked();
3573 // TODO: VI Should this terminate the voice session?
3574 }
3575 }
3576
3577 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3578 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3579 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3580 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3581 boolean wasRunningVoice = mRunningVoice != null;
3582 mRunningVoice = session;
3583 if (!wasRunningVoice) {
3584 mVoiceWakeLock.acquire();
3585 updateSleepIfNeededLocked();
3586 }
3587 }
3588 }
3589
3590 void finishRunningVoiceLocked() {
3591 if (mRunningVoice != null) {
3592 mRunningVoice = null;
3593 mVoiceWakeLock.release();
3594 updateSleepIfNeededLocked();
3595 }
3596 }
3597
3598 @Override
3599 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3600 synchronized (mGlobalLock) {
3601 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3602 if (keepAwake) {
3603 mVoiceWakeLock.acquire();
3604 } else {
3605 mVoiceWakeLock.release();
3606 }
3607 }
3608 }
3609 }
3610
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003611 @Override
3612 public ComponentName getActivityClassForToken(IBinder token) {
3613 synchronized (mGlobalLock) {
3614 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3615 if (r == null) {
3616 return null;
3617 }
3618 return r.intent.getComponent();
3619 }
3620 }
3621
3622 @Override
3623 public String getPackageForToken(IBinder token) {
3624 synchronized (mGlobalLock) {
3625 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3626 if (r == null) {
3627 return null;
3628 }
3629 return r.packageName;
3630 }
3631 }
3632
3633 @Override
3634 public void showLockTaskEscapeMessage(IBinder token) {
3635 synchronized (mGlobalLock) {
3636 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3637 if (r == null) {
3638 return;
3639 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003640 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003641 }
3642 }
3643
3644 @Override
3645 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003646 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003647 final long token = Binder.clearCallingIdentity();
3648 try {
3649 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003650 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003651 }
3652 } finally {
3653 Binder.restoreCallingIdentity(token);
3654 }
3655 }
3656
3657 /**
3658 * Try to place task to provided position. The final position might be different depending on
3659 * current user and stacks state. The task will be moved to target stack if it's currently in
3660 * different stack.
3661 */
3662 @Override
3663 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003664 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003665 synchronized (mGlobalLock) {
3666 long ident = Binder.clearCallingIdentity();
3667 try {
3668 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3669 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003670 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003671 if (task == null) {
3672 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3673 + taskId);
3674 }
3675
Wale Ogunwaled32da472018-11-16 07:19:28 -08003676 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003677
3678 if (stack == null) {
3679 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3680 + stackId);
3681 }
3682 if (!stack.isActivityTypeStandardOrUndefined()) {
3683 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3684 + " the position of task " + taskId + " in/to non-standard stack");
3685 }
3686
3687 // TODO: Have the callers of this API call a separate reparent method if that is
3688 // what they intended to do vs. having this method also do reparenting.
3689 if (task.getStack() == stack) {
3690 // Change position in current stack.
3691 stack.positionChildAt(task, position);
3692 } else {
3693 // Reparent to new stack.
3694 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3695 !DEFER_RESUME, "positionTaskInStack");
3696 }
3697 } finally {
3698 Binder.restoreCallingIdentity(ident);
3699 }
3700 }
3701 }
3702
3703 @Override
3704 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3705 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3706 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3707 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3708 synchronized (mGlobalLock) {
3709 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3710 if (record == null) {
3711 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3712 + "found for: " + token);
3713 }
3714 record.setSizeConfigurations(horizontalSizeConfiguration,
3715 verticalSizeConfigurations, smallestSizeConfigurations);
3716 }
3717 }
3718
3719 /**
3720 * Dismisses split-screen multi-window mode.
3721 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3722 */
3723 @Override
3724 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003725 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003726 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3727 final long ident = Binder.clearCallingIdentity();
3728 try {
3729 synchronized (mGlobalLock) {
3730 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003731 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003732 if (stack == null) {
3733 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3734 return;
3735 }
3736
3737 if (toTop) {
3738 // Caller wants the current split-screen primary stack to be the top stack after
3739 // it goes fullscreen, so move it to the front.
3740 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003741 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003742 // In this case the current split-screen primary stack shouldn't be the top
3743 // stack after it goes fullscreen, but it current has focus, so we move the
3744 // focus to the top-most split-screen secondary stack next to it.
3745 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3746 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3747 if (otherStack != null) {
3748 otherStack.moveToFront("dismissSplitScreenMode_other");
3749 }
3750 }
3751
Evan Rosky10475742018-09-05 19:02:48 -07003752 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003753 }
3754 } finally {
3755 Binder.restoreCallingIdentity(ident);
3756 }
3757 }
3758
3759 /**
3760 * Dismisses Pip
3761 * @param animate True if the dismissal should be animated.
3762 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3763 * default animation duration should be used.
3764 */
3765 @Override
3766 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003767 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003768 final long ident = Binder.clearCallingIdentity();
3769 try {
3770 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003771 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003772 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003773 if (stack == null) {
3774 Slog.w(TAG, "dismissPip: pinned stack not found.");
3775 return;
3776 }
3777 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3778 throw new IllegalArgumentException("Stack: " + stack
3779 + " doesn't support animated resize.");
3780 }
3781 if (animate) {
3782 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3783 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3784 } else {
3785 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3786 }
3787 }
3788 } finally {
3789 Binder.restoreCallingIdentity(ident);
3790 }
3791 }
3792
3793 @Override
3794 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003795 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003796 synchronized (mGlobalLock) {
3797 mSuppressResizeConfigChanges = suppress;
3798 }
3799 }
3800
3801 /**
3802 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3803 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3804 * activity and clearing the task at the same time.
3805 */
3806 @Override
3807 // TODO: API should just be about changing windowing modes...
3808 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003809 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003810 "moveTasksToFullscreenStack()");
3811 synchronized (mGlobalLock) {
3812 final long origId = Binder.clearCallingIdentity();
3813 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003814 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003815 if (stack != null){
3816 if (!stack.isActivityTypeStandardOrUndefined()) {
3817 throw new IllegalArgumentException(
3818 "You can't move tasks from non-standard stacks.");
3819 }
3820 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3821 }
3822 } finally {
3823 Binder.restoreCallingIdentity(origId);
3824 }
3825 }
3826 }
3827
3828 /**
3829 * Moves the top activity in the input stackId to the pinned stack.
3830 *
3831 * @param stackId Id of stack to move the top activity to pinned stack.
3832 * @param bounds Bounds to use for pinned stack.
3833 *
3834 * @return True if the top activity of the input stack was successfully moved to the pinned
3835 * stack.
3836 */
3837 @Override
3838 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003839 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003840 "moveTopActivityToPinnedStack()");
3841 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003842 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003843 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3844 + "Device doesn't support picture-in-picture mode");
3845 }
3846
3847 long ident = Binder.clearCallingIdentity();
3848 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003849 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003850 } finally {
3851 Binder.restoreCallingIdentity(ident);
3852 }
3853 }
3854 }
3855
3856 @Override
3857 public boolean isInMultiWindowMode(IBinder token) {
3858 final long origId = Binder.clearCallingIdentity();
3859 try {
3860 synchronized (mGlobalLock) {
3861 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3862 if (r == null) {
3863 return false;
3864 }
3865 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3866 return r.inMultiWindowMode();
3867 }
3868 } finally {
3869 Binder.restoreCallingIdentity(origId);
3870 }
3871 }
3872
3873 @Override
3874 public boolean isInPictureInPictureMode(IBinder token) {
3875 final long origId = Binder.clearCallingIdentity();
3876 try {
3877 synchronized (mGlobalLock) {
3878 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3879 }
3880 } finally {
3881 Binder.restoreCallingIdentity(origId);
3882 }
3883 }
3884
3885 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003886 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3887 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003888 return false;
3889 }
3890
3891 // If we are animating to fullscreen then we have already dispatched the PIP mode
3892 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003893 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3894 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003895 }
3896
3897 @Override
3898 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3899 final long origId = Binder.clearCallingIdentity();
3900 try {
3901 synchronized (mGlobalLock) {
3902 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3903 "enterPictureInPictureMode", token, params);
3904
3905 // If the activity is already in picture in picture mode, then just return early
3906 if (isInPictureInPictureMode(r)) {
3907 return true;
3908 }
3909
3910 // Activity supports picture-in-picture, now check that we can enter PiP at this
3911 // point, if it is
3912 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3913 false /* beforeStopping */)) {
3914 return false;
3915 }
3916
3917 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003918 synchronized (mGlobalLock) {
3919 // Only update the saved args from the args that are set
3920 r.pictureInPictureArgs.copyOnlySet(params);
3921 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3922 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3923 // Adjust the source bounds by the insets for the transition down
3924 final Rect sourceBounds = new Rect(
3925 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003926 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003927 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003928 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003929 stack.setPictureInPictureAspectRatio(aspectRatio);
3930 stack.setPictureInPictureActions(actions);
3931 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3932 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3933 logPictureInPictureArgs(params);
3934 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003935 };
3936
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003937 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003938 // If the keyguard is showing or occluded, then try and dismiss it before
3939 // entering picture-in-picture (this will prompt the user to authenticate if the
3940 // device is currently locked).
3941 dismissKeyguard(token, new KeyguardDismissCallback() {
3942 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003943 public void onDismissSucceeded() {
3944 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003945 }
3946 }, null /* message */);
3947 } else {
3948 // Enter picture in picture immediately otherwise
3949 enterPipRunnable.run();
3950 }
3951 return true;
3952 }
3953 } finally {
3954 Binder.restoreCallingIdentity(origId);
3955 }
3956 }
3957
3958 @Override
3959 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3960 final long origId = Binder.clearCallingIdentity();
3961 try {
3962 synchronized (mGlobalLock) {
3963 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3964 "setPictureInPictureParams", token, params);
3965
3966 // Only update the saved args from the args that are set
3967 r.pictureInPictureArgs.copyOnlySet(params);
3968 if (r.inPinnedWindowingMode()) {
3969 // If the activity is already in picture-in-picture, update the pinned stack now
3970 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3971 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003972 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003973 if (!stack.isAnimatingBoundsToFullscreen()) {
3974 stack.setPictureInPictureAspectRatio(
3975 r.pictureInPictureArgs.getAspectRatio());
3976 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3977 }
3978 }
3979 logPictureInPictureArgs(params);
3980 }
3981 } finally {
3982 Binder.restoreCallingIdentity(origId);
3983 }
3984 }
3985
3986 @Override
3987 public int getMaxNumPictureInPictureActions(IBinder token) {
3988 // Currently, this is a static constant, but later, we may change this to be dependent on
3989 // the context of the activity
3990 return 3;
3991 }
3992
3993 private void logPictureInPictureArgs(PictureInPictureParams params) {
3994 if (params.hasSetActions()) {
3995 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3996 params.getActions().size());
3997 }
3998 if (params.hasSetAspectRatio()) {
3999 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
4000 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
4001 MetricsLogger.action(lm);
4002 }
4003 }
4004
4005 /**
4006 * Checks the state of the system and the activity associated with the given {@param token} to
4007 * verify that picture-in-picture is supported for that activity.
4008 *
4009 * @return the activity record for the given {@param token} if all the checks pass.
4010 */
4011 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
4012 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004013 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004014 throw new IllegalStateException(caller
4015 + ": Device doesn't support picture-in-picture mode.");
4016 }
4017
4018 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
4019 if (r == null) {
4020 throw new IllegalStateException(caller
4021 + ": Can't find activity for token=" + token);
4022 }
4023
4024 if (!r.supportsPictureInPicture()) {
4025 throw new IllegalStateException(caller
4026 + ": Current activity does not support picture-in-picture.");
4027 }
4028
4029 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004030 && !mWindowManager.isValidPictureInPictureAspectRatio(
4031 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004032 final float minAspectRatio = mContext.getResources().getFloat(
4033 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
4034 final float maxAspectRatio = mContext.getResources().getFloat(
4035 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
4036 throw new IllegalArgumentException(String.format(caller
4037 + ": Aspect ratio is too extreme (must be between %f and %f).",
4038 minAspectRatio, maxAspectRatio));
4039 }
4040
4041 // Truncate the number of actions if necessary
4042 params.truncateActions(getMaxNumPictureInPictureActions(token));
4043
4044 return r;
4045 }
4046
4047 @Override
4048 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004049 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004050 synchronized (mGlobalLock) {
4051 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
4052 if (r == null) {
4053 throw new IllegalArgumentException("Activity does not exist; token="
4054 + activityToken);
4055 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07004056 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004057 }
4058 }
4059
4060 @Override
4061 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4062 Rect tempDockedTaskInsetBounds,
4063 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004064 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004065 long ident = Binder.clearCallingIdentity();
4066 try {
4067 synchronized (mGlobalLock) {
4068 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4069 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4070 PRESERVE_WINDOWS);
4071 }
4072 } finally {
4073 Binder.restoreCallingIdentity(ident);
4074 }
4075 }
4076
4077 @Override
4078 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004079 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004080 final long ident = Binder.clearCallingIdentity();
4081 try {
4082 synchronized (mGlobalLock) {
4083 mStackSupervisor.setSplitScreenResizing(resizing);
4084 }
4085 } finally {
4086 Binder.restoreCallingIdentity(ident);
4087 }
4088 }
4089
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004090 /**
4091 * Check that we have the features required for VR-related API calls, and throw an exception if
4092 * not.
4093 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004094 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004095 if (!mContext.getPackageManager().hasSystemFeature(
4096 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4097 throw new UnsupportedOperationException("VR mode not supported on this device!");
4098 }
4099 }
4100
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004101 @Override
4102 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004103 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004104
4105 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4106
4107 ActivityRecord r;
4108 synchronized (mGlobalLock) {
4109 r = ActivityRecord.isInStackLocked(token);
4110 }
4111
4112 if (r == null) {
4113 throw new IllegalArgumentException();
4114 }
4115
4116 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004117 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004118 VrManagerInternal.NO_ERROR) {
4119 return err;
4120 }
4121
4122 // Clear the binder calling uid since this path may call moveToTask().
4123 final long callingId = Binder.clearCallingIdentity();
4124 try {
4125 synchronized (mGlobalLock) {
4126 r.requestedVrComponent = (enabled) ? packageName : null;
4127
4128 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004129 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004130 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004131 }
4132 return 0;
4133 }
4134 } finally {
4135 Binder.restoreCallingIdentity(callingId);
4136 }
4137 }
4138
4139 @Override
4140 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4141 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4142 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004143 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4145 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4146 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004147 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 || activity.voiceSession != null) {
4149 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4150 return;
4151 }
4152 if (activity.pendingVoiceInteractionStart) {
4153 Slog.w(TAG, "Pending start of voice interaction already.");
4154 return;
4155 }
4156 activity.pendingVoiceInteractionStart = true;
4157 }
4158 LocalServices.getService(VoiceInteractionManagerInternal.class)
4159 .startLocalVoiceInteraction(callingActivity, options);
4160 }
4161
4162 @Override
4163 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4164 LocalServices.getService(VoiceInteractionManagerInternal.class)
4165 .stopLocalVoiceInteraction(callingActivity);
4166 }
4167
4168 @Override
4169 public boolean supportsLocalVoiceInteraction() {
4170 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4171 .supportsLocalVoiceInteraction();
4172 }
4173
4174 /** Notifies all listeners when the pinned stack animation starts. */
4175 @Override
4176 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004177 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004178 }
4179
4180 /** Notifies all listeners when the pinned stack animation ends. */
4181 @Override
4182 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004183 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004184 }
4185
4186 @Override
4187 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 final long ident = Binder.clearCallingIdentity();
4190 try {
4191 synchronized (mGlobalLock) {
4192 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4193 }
4194 } finally {
4195 Binder.restoreCallingIdentity(ident);
4196 }
4197 }
4198
4199 @Override
4200 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004201 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004202
4203 synchronized (mGlobalLock) {
4204 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004205 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004206 // Call might come when display is not yet added or has already been removed.
4207 if (DEBUG_CONFIGURATION) {
4208 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4209 + displayId);
4210 }
4211 return false;
4212 }
4213
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004214 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004215 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004216 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004217 }
4218
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004219 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004220 final Message msg = PooledLambda.obtainMessage(
4221 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4222 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004223 }
4224
4225 final long origId = Binder.clearCallingIdentity();
4226 try {
4227 if (values != null) {
4228 Settings.System.clearConfiguration(values);
4229 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004230 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004231 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4232 return mTmpUpdateConfigurationResult.changes != 0;
4233 } finally {
4234 Binder.restoreCallingIdentity(origId);
4235 }
4236 }
4237 }
4238
4239 @Override
4240 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004241 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004242
4243 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004244 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004245 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004246 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004247 }
4248
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004249 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004250 final Message msg = PooledLambda.obtainMessage(
4251 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4252 DEFAULT_DISPLAY);
4253 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004254 }
4255
4256 final long origId = Binder.clearCallingIdentity();
4257 try {
4258 if (values != null) {
4259 Settings.System.clearConfiguration(values);
4260 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004261 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004262 UserHandle.USER_NULL, false /* deferResume */,
4263 mTmpUpdateConfigurationResult);
4264 return mTmpUpdateConfigurationResult.changes != 0;
4265 } finally {
4266 Binder.restoreCallingIdentity(origId);
4267 }
4268 }
4269 }
4270
4271 @Override
4272 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4273 CharSequence message) {
4274 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004275 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004276 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4277 }
4278 final long callingId = Binder.clearCallingIdentity();
4279 try {
4280 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004281 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004282 }
4283 } finally {
4284 Binder.restoreCallingIdentity(callingId);
4285 }
4286 }
4287
4288 @Override
4289 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004290 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004291 "cancelTaskWindowTransition()");
4292 final long ident = Binder.clearCallingIdentity();
4293 try {
4294 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004295 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004296 MATCH_TASK_IN_STACKS_ONLY);
4297 if (task == null) {
4298 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4299 return;
4300 }
4301 task.cancelWindowTransition();
4302 }
4303 } finally {
4304 Binder.restoreCallingIdentity(ident);
4305 }
4306 }
4307
4308 @Override
4309 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004310 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004311 final long ident = Binder.clearCallingIdentity();
4312 try {
4313 final TaskRecord task;
4314 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004315 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004316 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4317 if (task == null) {
4318 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4319 return null;
4320 }
4321 }
4322 // Don't call this while holding the lock as this operation might hit the disk.
4323 return task.getSnapshot(reducedResolution);
4324 } finally {
4325 Binder.restoreCallingIdentity(ident);
4326 }
4327 }
4328
4329 @Override
4330 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4331 synchronized (mGlobalLock) {
4332 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4333 if (r == null) {
4334 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4335 + token);
4336 return;
4337 }
4338 final long origId = Binder.clearCallingIdentity();
4339 try {
4340 r.setDisablePreviewScreenshots(disable);
4341 } finally {
4342 Binder.restoreCallingIdentity(origId);
4343 }
4344 }
4345 }
4346
4347 /** Return the user id of the last resumed activity. */
4348 @Override
4349 public @UserIdInt
4350 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004351 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004352 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4353 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004354 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004355 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004356 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004357 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004358 }
4359 }
4360
4361 @Override
4362 public void updateLockTaskFeatures(int userId, int flags) {
4363 final int callingUid = Binder.getCallingUid();
4364 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004365 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004366 "updateLockTaskFeatures()");
4367 }
4368 synchronized (mGlobalLock) {
4369 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4370 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004371 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004372 }
4373 }
4374
4375 @Override
4376 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4377 synchronized (mGlobalLock) {
4378 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4379 if (r == null) {
4380 return;
4381 }
4382 final long origId = Binder.clearCallingIdentity();
4383 try {
4384 r.setShowWhenLocked(showWhenLocked);
4385 } finally {
4386 Binder.restoreCallingIdentity(origId);
4387 }
4388 }
4389 }
4390
4391 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004392 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4393 synchronized (mGlobalLock) {
4394 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4395 if (r == null) {
4396 return;
4397 }
4398 final long origId = Binder.clearCallingIdentity();
4399 try {
4400 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4401 } finally {
4402 Binder.restoreCallingIdentity(origId);
4403 }
4404 }
4405 }
4406
4407 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4409 synchronized (mGlobalLock) {
4410 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4411 if (r == null) {
4412 return;
4413 }
4414 final long origId = Binder.clearCallingIdentity();
4415 try {
4416 r.setTurnScreenOn(turnScreenOn);
4417 } finally {
4418 Binder.restoreCallingIdentity(origId);
4419 }
4420 }
4421 }
4422
4423 @Override
4424 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004425 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004426 "registerRemoteAnimations");
4427 definition.setCallingPid(Binder.getCallingPid());
4428 synchronized (mGlobalLock) {
4429 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4430 if (r == null) {
4431 return;
4432 }
4433 final long origId = Binder.clearCallingIdentity();
4434 try {
4435 r.registerRemoteAnimations(definition);
4436 } finally {
4437 Binder.restoreCallingIdentity(origId);
4438 }
4439 }
4440 }
4441
4442 @Override
4443 public void registerRemoteAnimationForNextActivityStart(String packageName,
4444 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004445 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004446 "registerRemoteAnimationForNextActivityStart");
4447 adapter.setCallingPid(Binder.getCallingPid());
4448 synchronized (mGlobalLock) {
4449 final long origId = Binder.clearCallingIdentity();
4450 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004451 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004452 packageName, adapter);
4453 } finally {
4454 Binder.restoreCallingIdentity(origId);
4455 }
4456 }
4457 }
4458
Evan Rosky966759f2019-01-15 10:33:58 -08004459 @Override
4460 public void registerRemoteAnimationsForDisplay(int displayId,
4461 RemoteAnimationDefinition definition) {
4462 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
4463 "registerRemoteAnimations");
4464 definition.setCallingPid(Binder.getCallingPid());
4465 synchronized (mGlobalLock) {
4466 final ActivityDisplay display = mRootActivityContainer.getActivityDisplay(displayId);
4467 if (display == null) {
4468 Slog.e(TAG, "Couldn't find display with id: " + displayId);
4469 return;
4470 }
4471 final long origId = Binder.clearCallingIdentity();
4472 try {
4473 display.mDisplayContent.registerRemoteAnimations(definition);
4474 } finally {
4475 Binder.restoreCallingIdentity(origId);
4476 }
4477 }
4478 }
4479
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004480 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4481 @Override
4482 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4483 synchronized (mGlobalLock) {
4484 final long origId = Binder.clearCallingIdentity();
4485 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004486 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004487 } finally {
4488 Binder.restoreCallingIdentity(origId);
4489 }
4490 }
4491 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004492
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004493 @Override
4494 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004495 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004496 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004497 final int pid = Binder.getCallingPid();
4498 final WindowProcessController wpc = mPidMap.get(pid);
4499 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004500 }
4501 }
4502
4503 @Override
4504 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004505 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004506 != PERMISSION_GRANTED) {
4507 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4508 + Binder.getCallingPid()
4509 + ", uid=" + Binder.getCallingUid()
4510 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4511 Slog.w(TAG, msg);
4512 throw new SecurityException(msg);
4513 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004514 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004515 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004516 final int pid = Binder.getCallingPid();
4517 final WindowProcessController proc = mPidMap.get(pid);
4518 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004519 }
4520 }
4521
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004522 @Override
4523 public void stopAppSwitches() {
4524 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4525 synchronized (mGlobalLock) {
4526 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4527 mDidAppSwitch = false;
4528 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4529 }
4530 }
4531
4532 @Override
4533 public void resumeAppSwitches() {
4534 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4535 synchronized (mGlobalLock) {
4536 // Note that we don't execute any pending app switches... we will
4537 // let those wait until either the timeout, or the next start
4538 // activity request.
4539 mAppSwitchesAllowedTime = 0;
4540 }
4541 }
4542
4543 void onStartActivitySetDidAppSwitch() {
4544 if (mDidAppSwitch) {
4545 // This is the second allowed switch since we stopped switches, so now just generally
4546 // allow switches. Use case:
4547 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4548 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4549 // anyone to switch again).
4550 mAppSwitchesAllowedTime = 0;
4551 } else {
4552 mDidAppSwitch = true;
4553 }
4554 }
4555
4556 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004557 boolean shouldDisableNonVrUiLocked() {
4558 return mVrController.shouldDisableNonVrUiLocked();
4559 }
4560
Wale Ogunwale53783742018-09-16 10:21:51 -07004561 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004562 // VR apps are expected to run in a main display. If an app is turning on VR for
4563 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4564 // fullscreen stack before enabling VR Mode.
4565 // TODO: The goal of this code is to keep the VR app on the main display. When the
4566 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4567 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4568 // option would be a better choice here.
4569 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4570 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4571 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004572 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004573 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004574 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004575 }
4576 mH.post(() -> {
4577 if (!mVrController.onVrModeChanged(r)) {
4578 return;
4579 }
4580 synchronized (mGlobalLock) {
4581 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4582 mWindowManager.disableNonVrUi(disableNonVrUi);
4583 if (disableNonVrUi) {
4584 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4585 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004586 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004587 }
4588 }
4589 });
4590 }
4591
Wale Ogunwale53783742018-09-16 10:21:51 -07004592 @Override
4593 public int getPackageScreenCompatMode(String packageName) {
4594 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4595 synchronized (mGlobalLock) {
4596 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4597 }
4598 }
4599
4600 @Override
4601 public void setPackageScreenCompatMode(String packageName, int mode) {
4602 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4603 "setPackageScreenCompatMode");
4604 synchronized (mGlobalLock) {
4605 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4606 }
4607 }
4608
4609 @Override
4610 public boolean getPackageAskScreenCompat(String packageName) {
4611 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4612 synchronized (mGlobalLock) {
4613 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4614 }
4615 }
4616
4617 @Override
4618 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4619 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4620 "setPackageAskScreenCompat");
4621 synchronized (mGlobalLock) {
4622 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4623 }
4624 }
4625
Wale Ogunwale64258362018-10-16 15:13:37 -07004626 public static String relaunchReasonToString(int relaunchReason) {
4627 switch (relaunchReason) {
4628 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4629 return "window_resize";
4630 case RELAUNCH_REASON_FREE_RESIZE:
4631 return "free_resize";
4632 default:
4633 return null;
4634 }
4635 }
4636
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004637 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004638 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004639 }
4640
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004641 /** Pokes the task persister. */
4642 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4643 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4644 }
4645
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004646 boolean isKeyguardLocked() {
4647 return mKeyguardController.isKeyguardLocked();
4648 }
4649
Garfield Tan01548632018-11-27 10:15:48 -08004650 /**
4651 * Clears launch params for the given package.
4652 * @param packageNames the names of the packages of which the launch params are to be cleared
4653 */
4654 @Override
4655 public void clearLaunchParamsForPackages(List<String> packageNames) {
4656 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4657 "clearLaunchParamsForPackages");
4658 synchronized (mGlobalLock) {
4659 for (int i = 0; i < packageNames.size(); ++i) {
4660 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4661 }
4662 }
4663 }
4664
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004665 /**
4666 * Makes the display with the given id a single task instance display. I.e the display can only
4667 * contain one task.
4668 */
4669 @Override
4670 public void setDisplayToSingleTaskInstance(int displayId) {
4671 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4672 "setDisplayToSingleTaskInstance");
4673 final long origId = Binder.clearCallingIdentity();
4674 try {
4675 final ActivityDisplay display =
4676 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4677 if (display != null) {
4678 display.setDisplayToSingleTaskInstance();
4679 }
4680 } finally {
4681 Binder.restoreCallingIdentity(origId);
4682 }
4683 }
4684
Wale Ogunwale31913b52018-10-13 08:29:31 -07004685 void dumpLastANRLocked(PrintWriter pw) {
4686 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4687 if (mLastANRState == null) {
4688 pw.println(" <no ANR has occurred since boot>");
4689 } else {
4690 pw.println(mLastANRState);
4691 }
4692 }
4693
4694 void dumpLastANRTracesLocked(PrintWriter pw) {
4695 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4696
4697 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4698 if (ArrayUtils.isEmpty(files)) {
4699 pw.println(" <no ANR has occurred since boot>");
4700 return;
4701 }
4702 // Find the latest file.
4703 File latest = null;
4704 for (File f : files) {
4705 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4706 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004707 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004708 }
4709 pw.print("File: ");
4710 pw.print(latest.getName());
4711 pw.println();
4712 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4713 String line;
4714 while ((line = in.readLine()) != null) {
4715 pw.println(line);
4716 }
4717 } catch (IOException e) {
4718 pw.print("Unable to read: ");
4719 pw.print(e);
4720 pw.println();
4721 }
4722 }
4723
4724 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4725 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4726 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4727 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4728 }
4729
4730 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4731 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4732 pw.println(header);
4733
Wale Ogunwaled32da472018-11-16 07:19:28 -08004734 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004735 dumpPackage);
4736 boolean needSep = printedAnything;
4737
4738 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004739 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004740 " ResumedActivity: ");
4741 if (printed) {
4742 printedAnything = true;
4743 needSep = false;
4744 }
4745
4746 if (dumpPackage == null) {
4747 if (needSep) {
4748 pw.println();
4749 }
4750 printedAnything = true;
4751 mStackSupervisor.dump(pw, " ");
4752 }
4753
4754 if (!printedAnything) {
4755 pw.println(" (nothing)");
4756 }
4757 }
4758
4759 void dumpActivityContainersLocked(PrintWriter pw) {
4760 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004761 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004762 pw.println(" ");
4763 }
4764
4765 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4766 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4767 getActivityStartController().dump(pw, "", dumpPackage);
4768 }
4769
4770 /**
4771 * There are three things that cmd can be:
4772 * - a flattened component name that matches an existing activity
4773 * - the cmd arg isn't the flattened component name of an existing activity:
4774 * dump all activity whose component contains the cmd as a substring
4775 * - A hex number of the ActivityRecord object instance.
4776 *
4777 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4778 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4779 */
4780 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4781 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4782 ArrayList<ActivityRecord> activities;
4783
4784 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004785 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004786 dumpFocusedStackOnly);
4787 }
4788
4789 if (activities.size() <= 0) {
4790 return false;
4791 }
4792
4793 String[] newArgs = new String[args.length - opti];
4794 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4795
4796 TaskRecord lastTask = null;
4797 boolean needSep = false;
4798 for (int i = activities.size() - 1; i >= 0; i--) {
4799 ActivityRecord r = activities.get(i);
4800 if (needSep) {
4801 pw.println();
4802 }
4803 needSep = true;
4804 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004805 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004806 if (lastTask != task) {
4807 lastTask = task;
4808 pw.print("TASK "); pw.print(lastTask.affinity);
4809 pw.print(" id="); pw.print(lastTask.taskId);
4810 pw.print(" userId="); pw.println(lastTask.userId);
4811 if (dumpAll) {
4812 lastTask.dump(pw, " ");
4813 }
4814 }
4815 }
4816 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4817 }
4818 return true;
4819 }
4820
4821 /**
4822 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4823 * there is a thread associated with the activity.
4824 */
4825 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4826 final ActivityRecord r, String[] args, boolean dumpAll) {
4827 String innerPrefix = prefix + " ";
4828 synchronized (mGlobalLock) {
4829 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4830 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4831 pw.print(" pid=");
4832 if (r.hasProcess()) pw.println(r.app.getPid());
4833 else pw.println("(not running)");
4834 if (dumpAll) {
4835 r.dump(pw, innerPrefix);
4836 }
4837 }
4838 if (r.attachedToProcess()) {
4839 // flush anything that is already in the PrintWriter since the thread is going
4840 // to write to the file descriptor directly
4841 pw.flush();
4842 try {
4843 TransferPipe tp = new TransferPipe();
4844 try {
4845 r.app.getThread().dumpActivity(tp.getWriteFd(),
4846 r.appToken, innerPrefix, args);
4847 tp.go(fd);
4848 } finally {
4849 tp.kill();
4850 }
4851 } catch (IOException e) {
4852 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4853 } catch (RemoteException e) {
4854 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4855 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004856 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004857 }
4858
sanryhuang498e77e2018-12-06 14:57:01 +08004859 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4860 boolean testPssMode) {
4861 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4862 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4863 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004864 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004865 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4866 st.toString());
4867 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004868 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4869 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4870 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004871 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4872 testPssMode);
4873 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004874 }
4875
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004876 int getCurrentUserId() {
4877 return mAmInternal.getCurrentUserId();
4878 }
4879
4880 private void enforceNotIsolatedCaller(String caller) {
4881 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4882 throw new SecurityException("Isolated process not allowed to call " + caller);
4883 }
4884 }
4885
Wale Ogunwalef6733932018-06-27 05:14:34 -07004886 public Configuration getConfiguration() {
4887 Configuration ci;
4888 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004889 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004890 ci.userSetLocale = false;
4891 }
4892 return ci;
4893 }
4894
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004895 /**
4896 * Current global configuration information. Contains general settings for the entire system,
4897 * also corresponds to the merged configuration of the default display.
4898 */
4899 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004900 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004901 }
4902
4903 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4904 boolean initLocale) {
4905 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4906 }
4907
4908 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4909 boolean initLocale, boolean deferResume) {
4910 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4911 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4912 UserHandle.USER_NULL, deferResume);
4913 }
4914
Wale Ogunwale59507092018-10-29 09:00:30 -07004915 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004916 final long origId = Binder.clearCallingIdentity();
4917 try {
4918 synchronized (mGlobalLock) {
4919 updateConfigurationLocked(values, null, false, true, userId,
4920 false /* deferResume */);
4921 }
4922 } finally {
4923 Binder.restoreCallingIdentity(origId);
4924 }
4925 }
4926
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004927 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4928 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4929 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4930 deferResume, null /* result */);
4931 }
4932
4933 /**
4934 * Do either or both things: (1) change the current configuration, and (2)
4935 * make sure the given activity is running with the (now) current
4936 * configuration. Returns true if the activity has been left running, or
4937 * false if <var>starting</var> is being destroyed to match the new
4938 * configuration.
4939 *
4940 * @param userId is only used when persistent parameter is set to true to persist configuration
4941 * for that particular user
4942 */
4943 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4944 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4945 ActivityTaskManagerService.UpdateConfigurationResult result) {
4946 int changes = 0;
4947 boolean kept = true;
4948
4949 if (mWindowManager != null) {
4950 mWindowManager.deferSurfaceLayout();
4951 }
4952 try {
4953 if (values != null) {
4954 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4955 deferResume);
4956 }
4957
4958 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4959 } finally {
4960 if (mWindowManager != null) {
4961 mWindowManager.continueSurfaceLayout();
4962 }
4963 }
4964
4965 if (result != null) {
4966 result.changes = changes;
4967 result.activityRelaunched = !kept;
4968 }
4969 return kept;
4970 }
4971
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004972 /** Update default (global) configuration and notify listeners about changes. */
4973 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4974 boolean persistent, int userId, boolean deferResume) {
4975 mTempConfig.setTo(getGlobalConfiguration());
4976 final int changes = mTempConfig.updateFrom(values);
4977 if (changes == 0) {
4978 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4979 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4980 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4981 // (even if there are no actual changes) to unfreeze the window.
4982 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4983 return 0;
4984 }
4985
4986 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4987 "Updating global configuration to: " + values);
4988
4989 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4990 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4991 values.colorMode,
4992 values.densityDpi,
4993 values.fontScale,
4994 values.hardKeyboardHidden,
4995 values.keyboard,
4996 values.keyboardHidden,
4997 values.mcc,
4998 values.mnc,
4999 values.navigation,
5000 values.navigationHidden,
5001 values.orientation,
5002 values.screenHeightDp,
5003 values.screenLayout,
5004 values.screenWidthDp,
5005 values.smallestScreenWidthDp,
5006 values.touchscreen,
5007 values.uiMode);
5008
5009
5010 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
5011 final LocaleList locales = values.getLocales();
5012 int bestLocaleIndex = 0;
5013 if (locales.size() > 1) {
5014 if (mSupportedSystemLocales == null) {
5015 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
5016 }
5017 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
5018 }
5019 SystemProperties.set("persist.sys.locale",
5020 locales.get(bestLocaleIndex).toLanguageTag());
5021 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005022
5023 final Message m = PooledLambda.obtainMessage(
5024 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
5025 locales.get(bestLocaleIndex));
5026 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005027 }
5028
Yunfan Chen75157d72018-07-27 14:47:21 +09005029 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005030
5031 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005032 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005033
5034 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
5035 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005036 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005037
5038 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07005039 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005040
5041 AttributeCache ac = AttributeCache.instance();
5042 if (ac != null) {
5043 ac.updateConfiguration(mTempConfig);
5044 }
5045
5046 // Make sure all resources in our process are updated right now, so that anyone who is going
5047 // to retrieve resource values after we return will be sure to get the new ones. This is
5048 // especially important during boot, where the first config change needs to guarantee all
5049 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005050 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005051
5052 // We need another copy of global config because we're scheduling some calls instead of
5053 // running them in place. We need to be sure that object we send will be handled unchanged.
5054 final Configuration configCopy = new Configuration(mTempConfig);
5055 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005056 final Message msg = PooledLambda.obtainMessage(
5057 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
5058 this, userId, configCopy);
5059 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005060 }
5061
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005062 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07005063 final int pid = mPidMap.keyAt(i);
5064 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005065 if (DEBUG_CONFIGURATION) {
5066 Slog.v(TAG_CONFIGURATION, "Update process config of "
5067 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005068 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07005069 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005070 }
5071
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07005072 final Message msg = PooledLambda.obtainMessage(
5073 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
5074 mAmInternal, changes, initLocale);
5075 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005076
5077 // Override configuration of the default display duplicates global config, so we need to
5078 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005079 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005080 DEFAULT_DISPLAY);
5081
5082 return changes;
5083 }
5084
5085 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5086 boolean deferResume, int displayId) {
5087 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5088 displayId, null /* result */);
5089 }
5090
5091 /**
5092 * Updates override configuration specific for the selected display. If no config is provided,
5093 * new one will be computed in WM based on current display info.
5094 */
5095 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5096 ActivityRecord starting, boolean deferResume, int displayId,
5097 ActivityTaskManagerService.UpdateConfigurationResult result) {
5098 int changes = 0;
5099 boolean kept = true;
5100
5101 if (mWindowManager != null) {
5102 mWindowManager.deferSurfaceLayout();
5103 }
5104 try {
5105 if (values != null) {
5106 if (displayId == DEFAULT_DISPLAY) {
5107 // Override configuration of the default display duplicates global config, so
5108 // we're calling global config update instead for default display. It will also
5109 // apply the correct override config.
5110 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5111 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5112 } else {
5113 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5114 }
5115 }
5116
5117 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5118 } finally {
5119 if (mWindowManager != null) {
5120 mWindowManager.continueSurfaceLayout();
5121 }
5122 }
5123
5124 if (result != null) {
5125 result.changes = changes;
5126 result.activityRelaunched = !kept;
5127 }
5128 return kept;
5129 }
5130
5131 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5132 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005133 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005134 final int changes = mTempConfig.updateFrom(values);
5135 if (changes != 0) {
5136 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5137 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005138 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005139
5140 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5141 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005142 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005143
Wale Ogunwale5c918702018-10-18 11:06:33 -07005144 // Post message to start process to avoid possible deadlock of calling into AMS with
5145 // the ATMS lock held.
5146 final Message msg = PooledLambda.obtainMessage(
5147 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5148 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5149 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005150 }
5151 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005152 return changes;
5153 }
5154
Wale Ogunwalef6733932018-06-27 05:14:34 -07005155 private void updateEventDispatchingLocked(boolean booted) {
5156 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5157 }
5158
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005159 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5160 final ContentResolver resolver = mContext.getContentResolver();
5161 Settings.System.putConfigurationForUser(resolver, config, userId);
5162 }
5163
5164 private void sendLocaleToMountDaemonMsg(Locale l) {
5165 try {
5166 IBinder service = ServiceManager.getService("mount");
5167 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5168 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5169 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5170 } catch (RemoteException e) {
5171 Log.e(TAG, "Error storing locale for decryption UI", e);
5172 }
5173 }
5174
Alison Cichowlas3e340502018-08-07 17:15:01 -04005175 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5176 mStartActivitySources.remove(permissionToken);
5177 mExpiredStartAsCallerTokens.add(permissionToken);
5178 }
5179
5180 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5181 mExpiredStartAsCallerTokens.remove(permissionToken);
5182 }
5183
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005184 boolean isActivityStartsLoggingEnabled() {
5185 return mAmInternal.isActivityStartsLoggingEnabled();
5186 }
5187
Michal Karpinski8596ded2018-11-14 14:43:48 +00005188 boolean isBackgroundActivityStartsEnabled() {
5189 return mAmInternal.isBackgroundActivityStartsEnabled();
5190 }
5191
Wale Ogunwalef6733932018-06-27 05:14:34 -07005192 void enableScreenAfterBoot(boolean booted) {
5193 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5194 SystemClock.uptimeMillis());
5195 mWindowManager.enableScreenAfterBoot();
5196
5197 synchronized (mGlobalLock) {
5198 updateEventDispatchingLocked(booted);
5199 }
5200 }
5201
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005202 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5203 if (r == null || !r.hasProcess()) {
5204 return KEY_DISPATCHING_TIMEOUT_MS;
5205 }
5206 return getInputDispatchingTimeoutLocked(r.app);
5207 }
5208
5209 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005210 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005211 }
5212
Wale Ogunwalef6733932018-06-27 05:14:34 -07005213 /**
5214 * Decide based on the configuration whether we should show the ANR,
5215 * crash, etc dialogs. The idea is that if there is no affordance to
5216 * press the on-screen buttons, or the user experience would be more
5217 * greatly impacted than the crash itself, we shouldn't show the dialog.
5218 *
5219 * A thought: SystemUI might also want to get told about this, the Power
5220 * dialog / global actions also might want different behaviors.
5221 */
5222 private void updateShouldShowDialogsLocked(Configuration config) {
5223 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5224 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5225 && config.navigation == Configuration.NAVIGATION_NONAV);
5226 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5227 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5228 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5229 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5230 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5231 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5232 HIDE_ERROR_DIALOGS, 0) != 0;
5233 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5234 }
5235
5236 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5237 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5238 FONT_SCALE, 1.0f, userId);
5239
5240 synchronized (this) {
5241 if (getGlobalConfiguration().fontScale == scaleFactor) {
5242 return;
5243 }
5244
5245 final Configuration configuration
5246 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5247 configuration.fontScale = scaleFactor;
5248 updatePersistentConfiguration(configuration, userId);
5249 }
5250 }
5251
5252 // Actually is sleeping or shutting down or whatever else in the future
5253 // is an inactive state.
5254 boolean isSleepingOrShuttingDownLocked() {
5255 return isSleepingLocked() || mShuttingDown;
5256 }
5257
5258 boolean isSleepingLocked() {
5259 return mSleeping;
5260 }
5261
Riddle Hsu16567132018-08-16 21:37:47 +08005262 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005263 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005264 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005265 if (task.isActivityTypeStandard()) {
5266 if (mCurAppTimeTracker != r.appTimeTracker) {
5267 // We are switching app tracking. Complete the current one.
5268 if (mCurAppTimeTracker != null) {
5269 mCurAppTimeTracker.stop();
5270 mH.obtainMessage(
5271 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005272 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005273 mCurAppTimeTracker = null;
5274 }
5275 if (r.appTimeTracker != null) {
5276 mCurAppTimeTracker = r.appTimeTracker;
5277 startTimeTrackingFocusedActivityLocked();
5278 }
5279 } else {
5280 startTimeTrackingFocusedActivityLocked();
5281 }
5282 } else {
5283 r.appTimeTracker = null;
5284 }
5285 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5286 // TODO: Probably not, because we don't want to resume voice on switching
5287 // back to this activity
5288 if (task.voiceInteractor != null) {
5289 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5290 } else {
5291 finishRunningVoiceLocked();
5292
5293 if (mLastResumedActivity != null) {
5294 final IVoiceInteractionSession session;
5295
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005296 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005297 if (lastResumedActivityTask != null
5298 && lastResumedActivityTask.voiceSession != null) {
5299 session = lastResumedActivityTask.voiceSession;
5300 } else {
5301 session = mLastResumedActivity.voiceSession;
5302 }
5303
5304 if (session != null) {
5305 // We had been in a voice interaction session, but now focused has
5306 // move to something different. Just finish the session, we can't
5307 // return to it and retain the proper state and synchronization with
5308 // the voice interaction service.
5309 finishVoiceTask(session);
5310 }
5311 }
5312 }
5313
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005314 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5315 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005316 }
5317 updateResumedAppTrace(r);
5318 mLastResumedActivity = r;
5319
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005320 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005321
5322 applyUpdateLockStateLocked(r);
5323 applyUpdateVrModeLocked(r);
5324
5325 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005326 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005327 r == null ? "NULL" : r.shortComponentName,
5328 reason);
5329 }
5330
5331 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5332 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005333 final ActivityTaskManagerInternal.SleepToken token =
5334 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005335 updateSleepIfNeededLocked();
5336 return token;
5337 }
5338 }
5339
5340 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005341 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005342 final boolean wasSleeping = mSleeping;
5343 boolean updateOomAdj = false;
5344
5345 if (!shouldSleep) {
5346 // If wasSleeping is true, we need to wake up activity manager state from when
5347 // we started sleeping. In either case, we need to apply the sleep tokens, which
5348 // will wake up stacks or put them to sleep as appropriate.
5349 if (wasSleeping) {
5350 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005351 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5352 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005353 startTimeTrackingFocusedActivityLocked();
5354 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5355 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5356 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005357 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005358 if (wasSleeping) {
5359 updateOomAdj = true;
5360 }
5361 } else if (!mSleeping && shouldSleep) {
5362 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005363 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5364 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005365 if (mCurAppTimeTracker != null) {
5366 mCurAppTimeTracker.stop();
5367 }
5368 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5369 mStackSupervisor.goingToSleepLocked();
5370 updateResumedAppTrace(null /* resumed */);
5371 updateOomAdj = true;
5372 }
5373 if (updateOomAdj) {
5374 mH.post(mAmInternal::updateOomAdj);
5375 }
5376 }
5377
5378 void updateOomAdj() {
5379 mH.post(mAmInternal::updateOomAdj);
5380 }
5381
Wale Ogunwale53783742018-09-16 10:21:51 -07005382 void updateCpuStats() {
5383 mH.post(mAmInternal::updateCpuStats);
5384 }
5385
Hui Yu03d12402018-12-06 18:00:37 -08005386 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5387 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005388 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5389 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005390 mH.sendMessage(m);
5391 }
5392
Hui Yu03d12402018-12-06 18:00:37 -08005393 void updateActivityUsageStats(ActivityRecord activity, int event) {
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005394 ComponentName taskRoot = null;
5395 final TaskRecord task = activity.getTaskRecord();
5396 if (task != null) {
5397 final ActivityRecord rootActivity = task.getRootActivity();
5398 if (rootActivity != null) {
5399 taskRoot = rootActivity.mActivityComponent;
5400 }
5401 }
5402
Hui Yu03d12402018-12-06 18:00:37 -08005403 final Message m = PooledLambda.obtainMessage(
5404 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
Michael Wachenschwanz0b4ab1f2019-01-07 13:59:10 -08005405 activity.mActivityComponent, activity.mUserId, event, activity.appToken, taskRoot);
Hui Yu03d12402018-12-06 18:00:37 -08005406 mH.sendMessage(m);
5407 }
5408
Wale Ogunwale53783742018-09-16 10:21:51 -07005409 void setBooting(boolean booting) {
5410 mAmInternal.setBooting(booting);
5411 }
5412
5413 boolean isBooting() {
5414 return mAmInternal.isBooting();
5415 }
5416
5417 void setBooted(boolean booted) {
5418 mAmInternal.setBooted(booted);
5419 }
5420
5421 boolean isBooted() {
5422 return mAmInternal.isBooted();
5423 }
5424
5425 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5426 mH.post(() -> {
5427 if (finishBooting) {
5428 mAmInternal.finishBooting();
5429 }
5430 if (enableScreen) {
5431 mInternal.enableScreenAfterBoot(isBooted());
5432 }
5433 });
5434 }
5435
5436 void setHeavyWeightProcess(ActivityRecord root) {
5437 mHeavyWeightProcess = root.app;
5438 final Message m = PooledLambda.obtainMessage(
5439 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005440 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005441 mH.sendMessage(m);
5442 }
5443
5444 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5445 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5446 return;
5447 }
5448
5449 mHeavyWeightProcess = null;
5450 final Message m = PooledLambda.obtainMessage(
5451 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5452 proc.mUserId);
5453 mH.sendMessage(m);
5454 }
5455
5456 private void cancelHeavyWeightProcessNotification(int userId) {
5457 final INotificationManager inm = NotificationManager.getService();
5458 if (inm == null) {
5459 return;
5460 }
5461 try {
5462 inm.cancelNotificationWithTag("android", null,
5463 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5464 } catch (RuntimeException e) {
5465 Slog.w(TAG, "Error canceling notification for service", e);
5466 } catch (RemoteException e) {
5467 }
5468
5469 }
5470
5471 private void postHeavyWeightProcessNotification(
5472 WindowProcessController proc, Intent intent, int userId) {
5473 if (proc == null) {
5474 return;
5475 }
5476
5477 final INotificationManager inm = NotificationManager.getService();
5478 if (inm == null) {
5479 return;
5480 }
5481
5482 try {
5483 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5484 String text = mContext.getString(R.string.heavy_weight_notification,
5485 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5486 Notification notification =
5487 new Notification.Builder(context,
5488 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5489 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5490 .setWhen(0)
5491 .setOngoing(true)
5492 .setTicker(text)
5493 .setColor(mContext.getColor(
5494 com.android.internal.R.color.system_notification_accent_color))
5495 .setContentTitle(text)
5496 .setContentText(
5497 mContext.getText(R.string.heavy_weight_notification_detail))
5498 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5499 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5500 new UserHandle(userId)))
5501 .build();
5502 try {
5503 inm.enqueueNotificationWithTag("android", "android", null,
5504 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5505 } catch (RuntimeException e) {
5506 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5507 } catch (RemoteException e) {
5508 }
5509 } catch (PackageManager.NameNotFoundException e) {
5510 Slog.w(TAG, "Unable to create context for heavy notification", e);
5511 }
5512
5513 }
5514
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005515 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5516 IBinder token, String resultWho, int requestCode, Intent[] intents,
5517 String[] resolvedTypes, int flags, Bundle bOptions) {
5518
5519 ActivityRecord activity = null;
5520 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5521 activity = ActivityRecord.isInStackLocked(token);
5522 if (activity == null) {
5523 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5524 return null;
5525 }
5526 if (activity.finishing) {
5527 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5528 return null;
5529 }
5530 }
5531
5532 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5533 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5534 bOptions);
5535 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5536 if (noCreate) {
5537 return rec;
5538 }
5539 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5540 if (activity.pendingResults == null) {
5541 activity.pendingResults = new HashSet<>();
5542 }
5543 activity.pendingResults.add(rec.ref);
5544 }
5545 return rec;
5546 }
5547
Andrii Kulian52d255c2018-07-13 11:32:19 -07005548 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005549 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005550 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005551 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5552 mCurAppTimeTracker.start(resumedActivity.packageName);
5553 }
5554 }
5555
5556 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5557 if (mTracedResumedActivity != null) {
5558 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5559 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5560 }
5561 if (resumed != null) {
5562 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5563 constructResumedTraceName(resumed.packageName), 0);
5564 }
5565 mTracedResumedActivity = resumed;
5566 }
5567
5568 private String constructResumedTraceName(String packageName) {
5569 return "focused app: " + packageName;
5570 }
5571
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005572 /** Applies latest configuration and/or visibility updates if needed. */
5573 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5574 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005575 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005576 // mainStack is null during startup.
5577 if (mainStack != null) {
5578 if (changes != 0 && starting == null) {
5579 // If the configuration changed, and the caller is not already
5580 // in the process of starting an activity, then find the top
5581 // activity to check if its configuration needs to change.
5582 starting = mainStack.topRunningActivityLocked();
5583 }
5584
5585 if (starting != null) {
5586 kept = starting.ensureActivityConfiguration(changes,
5587 false /* preserveWindow */);
5588 // And we need to make sure at this point that all other activities
5589 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005590 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005591 !PRESERVE_WINDOWS);
5592 }
5593 }
5594
5595 return kept;
5596 }
5597
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005598 void scheduleAppGcsLocked() {
5599 mH.post(() -> mAmInternal.scheduleAppGcs());
5600 }
5601
Wale Ogunwale53783742018-09-16 10:21:51 -07005602 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5603 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5604 }
5605
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005606 /**
5607 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5608 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5609 * on demand.
5610 */
5611 IPackageManager getPackageManager() {
5612 return AppGlobals.getPackageManager();
5613 }
5614
5615 PackageManagerInternal getPackageManagerInternalLocked() {
5616 if (mPmInternal == null) {
5617 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5618 }
5619 return mPmInternal;
5620 }
5621
Wale Ogunwale008163e2018-07-23 23:11:08 -07005622 AppWarnings getAppWarningsLocked() {
5623 return mAppWarnings;
5624 }
5625
Wale Ogunwale214f3482018-10-04 11:00:47 -07005626 Intent getHomeIntent() {
5627 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5628 intent.setComponent(mTopComponent);
5629 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5630 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5631 intent.addCategory(Intent.CATEGORY_HOME);
5632 }
5633 return intent;
5634 }
5635
Chilun2ef71f72018-11-16 17:57:15 +08005636 /**
5637 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5638 * activities.
5639 *
5640 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5641 * component defined in config_secondaryHomeComponent.
5642 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5643 */
5644 Intent getSecondaryHomeIntent(String preferredPackage) {
5645 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5646 if (preferredPackage == null) {
5647 // Using the component stored in config if no package name.
5648 final String secondaryHomeComponent = mContext.getResources().getString(
5649 com.android.internal.R.string.config_secondaryHomeComponent);
5650 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5651 } else {
5652 intent.setPackage(preferredPackage);
5653 }
5654 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5655 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5656 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5657 }
5658 return intent;
5659 }
5660
Wale Ogunwale214f3482018-10-04 11:00:47 -07005661 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5662 if (info == null) return null;
5663 ApplicationInfo newInfo = new ApplicationInfo(info);
5664 newInfo.initForUser(userId);
5665 return newInfo;
5666 }
5667
Wale Ogunwale9c103022018-10-18 07:44:54 -07005668 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005669 if (uid == SYSTEM_UID) {
5670 // The system gets to run in any process. If there are multiple processes with the same
5671 // uid, just pick the first (this should never happen).
5672 final SparseArray<WindowProcessController> procs =
5673 mProcessNames.getMap().get(processName);
5674 if (procs == null) return null;
5675 final int procCount = procs.size();
5676 for (int i = 0; i < procCount; i++) {
5677 final int procUid = procs.keyAt(i);
5678 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5679 // Don't use an app process or different user process for system component.
5680 continue;
5681 }
5682 return procs.valueAt(i);
5683 }
5684 }
5685
5686 return mProcessNames.get(processName, uid);
5687 }
5688
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005689 WindowProcessController getProcessController(IApplicationThread thread) {
5690 if (thread == null) {
5691 return null;
5692 }
5693
5694 final IBinder threadBinder = thread.asBinder();
5695 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5696 for (int i = pmap.size()-1; i >= 0; i--) {
5697 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5698 for (int j = procs.size() - 1; j >= 0; j--) {
5699 final WindowProcessController proc = procs.valueAt(j);
5700 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5701 return proc;
5702 }
5703 }
5704 }
5705
5706 return null;
5707 }
5708
Michal Karpinski9cbb20b2019-02-05 17:31:50 +00005709 WindowProcessController getProcessController(int pid, int uid) {
5710 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5711 for (int i = pmap.size()-1; i >= 0; i--) {
5712 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5713 for (int j = procs.size() - 1; j >= 0; j--) {
5714 final WindowProcessController proc = procs.valueAt(j);
5715 if (UserHandle.isApp(uid) && proc.getPid() == pid && proc.mUid == uid) {
5716 return proc;
5717 }
5718 }
5719 }
5720 return null;
5721 }
5722
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005723 int getUidStateLocked(int uid) {
5724 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5725 }
5726
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00005727 boolean isUidForeground(int uid) {
5728 return (getUidStateLocked(uid) == ActivityManager.PROCESS_STATE_TOP)
5729 || mWindowManager.mRoot.isAnyNonToastWindowVisibleForUid(uid);
5730 }
5731
Michal Karpinski4026cae2019-02-12 11:51:47 +00005732 boolean isDeviceOwner(String packageName) {
5733 if (packageName == null) {
5734 return false;
5735 }
5736 return packageName.equals(mDeviceOwnerPackageName);
5737 }
5738
5739 void setDeviceOwnerPackageName(String deviceOwnerPkg) {
5740 mDeviceOwnerPackageName = deviceOwnerPkg;
5741 }
5742
Wale Ogunwale9de19442018-10-18 19:05:03 -07005743 /**
5744 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5745 * the whitelist
5746 */
5747 String getPendingTempWhitelistTagForUidLocked(int uid) {
5748 return mPendingTempWhitelist.get(uid);
5749 }
5750
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005751 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5752 if (true || Build.IS_USER) {
5753 return;
5754 }
5755
5756 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5757 StrictMode.allowThreadDiskWrites();
5758 try {
5759 File tracesDir = new File("/data/anr");
5760 File tracesFile = null;
5761 try {
5762 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5763
5764 StringBuilder sb = new StringBuilder();
5765 Time tobj = new Time();
5766 tobj.set(System.currentTimeMillis());
5767 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5768 sb.append(": ");
5769 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5770 sb.append(" since ");
5771 sb.append(msg);
5772 FileOutputStream fos = new FileOutputStream(tracesFile);
5773 fos.write(sb.toString().getBytes());
5774 if (app == null) {
5775 fos.write("\n*** No application process!".getBytes());
5776 }
5777 fos.close();
5778 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5779 } catch (IOException e) {
5780 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5781 return;
5782 }
5783
5784 if (app != null && app.getPid() > 0) {
5785 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5786 firstPids.add(app.getPid());
5787 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5788 }
5789
5790 File lastTracesFile = null;
5791 File curTracesFile = null;
5792 for (int i=9; i>=0; i--) {
5793 String name = String.format(Locale.US, "slow%02d.txt", i);
5794 curTracesFile = new File(tracesDir, name);
5795 if (curTracesFile.exists()) {
5796 if (lastTracesFile != null) {
5797 curTracesFile.renameTo(lastTracesFile);
5798 } else {
5799 curTracesFile.delete();
5800 }
5801 }
5802 lastTracesFile = curTracesFile;
5803 }
5804 tracesFile.renameTo(curTracesFile);
5805 } finally {
5806 StrictMode.setThreadPolicy(oldPolicy);
5807 }
5808 }
5809
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005810 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005811 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005812
5813
Wale Ogunwale98875612018-10-12 07:53:02 -07005814 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5815 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005816
Riddle Hsud93a6c42018-11-29 21:50:06 +08005817 H(Looper looper) {
5818 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005819 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005820
5821 @Override
5822 public void handleMessage(Message msg) {
5823 switch (msg.what) {
5824 case REPORT_TIME_TRACKER_MSG: {
5825 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5826 tracker.deliverResult(mContext);
5827 } break;
5828 }
5829 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005830 }
5831
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005832 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005833 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005834
5835 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005836 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005837 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005838
5839 @Override
5840 public void handleMessage(Message msg) {
5841 switch (msg.what) {
5842 case DISMISS_DIALOG_UI_MSG: {
5843 final Dialog d = (Dialog) msg.obj;
5844 d.dismiss();
5845 break;
5846 }
5847 }
5848 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005849 }
5850
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005851 final class LocalService extends ActivityTaskManagerInternal {
5852 @Override
5853 public SleepToken acquireSleepToken(String tag, int displayId) {
5854 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005855 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005856 }
5857
5858 @Override
5859 public ComponentName getHomeActivityForUser(int userId) {
5860 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005861 final ActivityRecord homeActivity =
5862 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005863 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005864 }
5865 }
5866
5867 @Override
5868 public void onLocalVoiceInteractionStarted(IBinder activity,
5869 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5870 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005871 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005872 }
5873 }
5874
5875 @Override
5876 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5877 synchronized (mGlobalLock) {
5878 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5879 reasons, timestamp);
5880 }
5881 }
5882
5883 @Override
5884 public void notifyAppTransitionFinished() {
5885 synchronized (mGlobalLock) {
5886 mStackSupervisor.notifyAppTransitionDone();
5887 }
5888 }
5889
5890 @Override
5891 public void notifyAppTransitionCancelled() {
5892 synchronized (mGlobalLock) {
5893 mStackSupervisor.notifyAppTransitionDone();
5894 }
5895 }
5896
5897 @Override
5898 public List<IBinder> getTopVisibleActivities() {
5899 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005900 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005901 }
5902 }
5903
5904 @Override
5905 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5906 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005907 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005908 }
5909 }
5910
5911 @Override
5912 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5913 Bundle bOptions) {
5914 Preconditions.checkNotNull(intents, "intents");
5915 final String[] resolvedTypes = new String[intents.length];
5916
5917 // UID of the package on user userId.
5918 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5919 // packageUid may not be initialized.
5920 int packageUid = 0;
5921 final long ident = Binder.clearCallingIdentity();
5922
5923 try {
5924 for (int i = 0; i < intents.length; i++) {
5925 resolvedTypes[i] =
5926 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5927 }
5928
5929 packageUid = AppGlobals.getPackageManager().getPackageUid(
5930 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5931 } catch (RemoteException e) {
5932 // Shouldn't happen.
5933 } finally {
5934 Binder.restoreCallingIdentity(ident);
5935 }
5936
5937 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005938 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005939 packageUid, packageName,
5940 intents, resolvedTypes, null /* resultTo */,
5941 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005942 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5943 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005944 }
5945 }
5946
5947 @Override
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005948 public int startActivitiesInPackage(int uid, int realCallingPid, int realCallingUid,
5949 String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo,
5950 SafeActivityOptions options, int userId, boolean validateIncomingUser,
5951 PendingIntentRecord originatingPendingIntent,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005952 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005953 synchronized (mGlobalLock) {
Michal Karpinski84d9ebd2019-01-17 18:28:59 +00005954 return getActivityStartController().startActivitiesInPackage(uid, realCallingPid,
5955 realCallingUid, callingPackage, intents, resolvedTypes, resultTo, options,
5956 userId, validateIncomingUser, originatingPendingIntent,
5957 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005958 }
5959 }
5960
5961 @Override
5962 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5963 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5964 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5965 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005966 PendingIntentRecord originatingPendingIntent,
5967 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005968 synchronized (mGlobalLock) {
5969 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5970 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5971 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005972 validateIncomingUser, originatingPendingIntent,
5973 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005974 }
5975 }
5976
5977 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005978 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5979 Intent intent, Bundle options, int userId) {
5980 return ActivityTaskManagerService.this.startActivityAsUser(
5981 caller, callerPacakge, intent,
5982 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5983 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5984 false /*validateIncomingUser*/);
5985 }
5986
5987 @Override
lumark588a3e82018-07-20 18:53:54 +08005988 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005989 synchronized (mGlobalLock) {
5990
5991 // We might change the visibilities here, so prepare an empty app transition which
5992 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005993 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005994 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005995 if (activityDisplay == null) {
5996 return;
5997 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005998 final DisplayContent dc = activityDisplay.mDisplayContent;
5999 final boolean wasTransitionSet =
6000 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006001 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006002 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006003 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006004 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006005
6006 // If there was a transition set already we don't want to interfere with it as we
6007 // might be starting it too early.
6008 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08006009 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006010 }
6011 }
6012 if (callback != null) {
6013 callback.run();
6014 }
6015 }
6016
6017 @Override
6018 public void notifyKeyguardTrustedChanged() {
6019 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006020 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006021 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006022 }
6023 }
6024 }
6025
6026 /**
6027 * Called after virtual display Id is updated by
6028 * {@link com.android.server.vr.Vr2dDisplay} with a specific
6029 * {@param vrVr2dDisplayId}.
6030 */
6031 @Override
6032 public void setVr2dDisplayId(int vr2dDisplayId) {
6033 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
6034 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006035 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006036 }
6037 }
6038
6039 @Override
6040 public void setFocusedActivity(IBinder token) {
6041 synchronized (mGlobalLock) {
6042 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
6043 if (r == null) {
6044 throw new IllegalArgumentException(
6045 "setFocusedActivity: No activity record matching token=" + token);
6046 }
Louis Chang19443452018-10-09 12:10:21 +08006047 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006048 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006049 }
6050 }
6051 }
6052
6053 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006054 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006055 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006056 }
6057
6058 @Override
6059 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006060 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006061 }
6062
6063 @Override
6064 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07006065 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006066 }
6067
6068 @Override
6069 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
6070 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
6071 }
6072
6073 @Override
6074 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006075 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006076 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07006077
6078 @Override
6079 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
6080 synchronized (mGlobalLock) {
6081 mActiveVoiceInteractionServiceComponent = component;
6082 }
6083 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07006084
6085 @Override
6086 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
6087 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
6088 return;
6089 }
6090 synchronized (mGlobalLock) {
6091 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
6092 if (types == null) {
6093 if (uid < 0) {
6094 return;
6095 }
6096 types = new ArrayMap<>();
6097 mAllowAppSwitchUids.put(userId, types);
6098 }
6099 if (uid < 0) {
6100 types.remove(type);
6101 } else {
6102 types.put(type, uid);
6103 }
6104 }
6105 }
6106
6107 @Override
6108 public void onUserStopped(int userId) {
6109 synchronized (mGlobalLock) {
6110 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
6111 mAllowAppSwitchUids.remove(userId);
6112 }
6113 }
6114
6115 @Override
6116 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
6117 synchronized (mGlobalLock) {
6118 return ActivityTaskManagerService.this.isGetTasksAllowed(
6119 caller, callingPid, callingUid);
6120 }
6121 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006122
6123 @Override
6124 public void onProcessAdded(WindowProcessController proc) {
6125 synchronized (mGlobalLock) {
6126 mProcessNames.put(proc.mName, proc.mUid, proc);
6127 }
6128 }
6129
6130 @Override
6131 public void onProcessRemoved(String name, int uid) {
6132 synchronized (mGlobalLock) {
6133 mProcessNames.remove(name, uid);
6134 }
6135 }
6136
6137 @Override
6138 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6139 synchronized (mGlobalLock) {
6140 if (proc == mHomeProcess) {
6141 mHomeProcess = null;
6142 }
6143 if (proc == mPreviousProcess) {
6144 mPreviousProcess = null;
6145 }
6146 }
6147 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006148
6149 @Override
6150 public int getTopProcessState() {
6151 synchronized (mGlobalLock) {
6152 return mTopProcessState;
6153 }
6154 }
6155
6156 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006157 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6158 synchronized (mGlobalLock) {
6159 return proc == mHeavyWeightProcess;
6160 }
6161 }
6162
6163 @Override
6164 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6165 synchronized (mGlobalLock) {
6166 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6167 }
6168 }
6169
6170 @Override
6171 public void finishHeavyWeightApp() {
6172 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006173 if (mHeavyWeightProcess != null) {
6174 mHeavyWeightProcess.finishActivities();
6175 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006176 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6177 mHeavyWeightProcess);
6178 }
6179 }
6180
6181 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006182 public boolean isSleeping() {
6183 synchronized (mGlobalLock) {
6184 return isSleepingLocked();
6185 }
6186 }
6187
6188 @Override
6189 public boolean isShuttingDown() {
6190 synchronized (mGlobalLock) {
6191 return mShuttingDown;
6192 }
6193 }
6194
6195 @Override
6196 public boolean shuttingDown(boolean booted, int timeout) {
6197 synchronized (mGlobalLock) {
6198 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006199 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006200 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006201 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006202 return mStackSupervisor.shutdownLocked(timeout);
6203 }
6204 }
6205
6206 @Override
6207 public void enableScreenAfterBoot(boolean booted) {
6208 synchronized (mGlobalLock) {
6209 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6210 SystemClock.uptimeMillis());
6211 mWindowManager.enableScreenAfterBoot();
6212 updateEventDispatchingLocked(booted);
6213 }
6214 }
6215
6216 @Override
6217 public boolean showStrictModeViolationDialog() {
6218 synchronized (mGlobalLock) {
6219 return mShowDialogs && !mSleeping && !mShuttingDown;
6220 }
6221 }
6222
6223 @Override
6224 public void showSystemReadyErrorDialogsIfNeeded() {
6225 synchronized (mGlobalLock) {
6226 try {
6227 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6228 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6229 + " data partition or your device will be unstable.");
6230 mUiHandler.post(() -> {
6231 if (mShowDialogs) {
6232 AlertDialog d = new BaseErrorDialog(mUiContext);
6233 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6234 d.setCancelable(false);
6235 d.setTitle(mUiContext.getText(R.string.android_system_label));
6236 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6237 d.setButton(DialogInterface.BUTTON_POSITIVE,
6238 mUiContext.getText(R.string.ok),
6239 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6240 d.show();
6241 }
6242 });
6243 }
6244 } catch (RemoteException e) {
6245 }
6246
6247 if (!Build.isBuildConsistent()) {
6248 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6249 mUiHandler.post(() -> {
6250 if (mShowDialogs) {
6251 AlertDialog d = new BaseErrorDialog(mUiContext);
6252 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6253 d.setCancelable(false);
6254 d.setTitle(mUiContext.getText(R.string.android_system_label));
6255 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6256 d.setButton(DialogInterface.BUTTON_POSITIVE,
6257 mUiContext.getText(R.string.ok),
6258 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6259 d.show();
6260 }
6261 });
6262 }
6263 }
6264 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006265
6266 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006267 public void onProcessMapped(int pid, WindowProcessController proc) {
6268 synchronized (mGlobalLock) {
6269 mPidMap.put(pid, proc);
6270 }
6271 }
6272
6273 @Override
6274 public void onProcessUnMapped(int pid) {
6275 synchronized (mGlobalLock) {
6276 mPidMap.remove(pid);
6277 }
6278 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006279
6280 @Override
6281 public void onPackageDataCleared(String name) {
6282 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006283 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006284 mAppWarnings.onPackageDataCleared(name);
6285 }
6286 }
6287
6288 @Override
6289 public void onPackageUninstalled(String name) {
6290 synchronized (mGlobalLock) {
6291 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006292 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006293 }
6294 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006295
6296 @Override
6297 public void onPackageAdded(String name, boolean replacing) {
6298 synchronized (mGlobalLock) {
6299 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6300 }
6301 }
6302
6303 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006304 public void onPackageReplaced(ApplicationInfo aInfo) {
6305 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006306 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006307 }
6308 }
6309
6310 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006311 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6312 synchronized (mGlobalLock) {
6313 return compatibilityInfoForPackageLocked(ai);
6314 }
6315 }
6316
Yunfan Chen75157d72018-07-27 14:47:21 +09006317 /**
6318 * Set the corresponding display information for the process global configuration. To be
6319 * called when we need to show IME on a different display.
6320 *
6321 * @param pid The process id associated with the IME window.
6322 * @param displayId The ID of the display showing the IME.
6323 */
6324 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006325 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006326 if (pid == MY_PID || pid < 0) {
6327 if (DEBUG_CONFIGURATION) {
6328 Slog.w(TAG,
6329 "Trying to update display configuration for system/invalid process.");
6330 }
6331 return;
6332 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006333 synchronized (mGlobalLock) {
6334 final ActivityDisplay activityDisplay =
6335 mRootActivityContainer.getActivityDisplay(displayId);
6336 if (activityDisplay == null) {
6337 // Call might come when display is not yet added or has been removed.
6338 if (DEBUG_CONFIGURATION) {
6339 Slog.w(TAG, "Trying to update display configuration for non-existing "
6340 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006341 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006342 return;
Yunfan Chen75157d72018-07-27 14:47:21 +09006343 }
Yunfan Chencafc7062019-01-22 17:21:32 +09006344 final WindowProcessController process = mPidMap.get(pid);
6345 if (process == null) {
6346 if (DEBUG_CONFIGURATION) {
6347 Slog.w(TAG, "Trying to update display configuration for invalid "
6348 + "process, pid=" + pid);
6349 }
6350 return;
6351 }
6352 process.registerDisplayConfigurationListenerLocked(activityDisplay);
6353 }
Yunfan Chen75157d72018-07-27 14:47:21 +09006354 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006355
6356 @Override
6357 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6358 int requestCode, int resultCode, Intent data) {
6359 synchronized (mGlobalLock) {
6360 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006361 if (r != null && r.getActivityStack() != null) {
6362 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6363 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006364 }
6365 }
6366 }
6367
6368 @Override
6369 public void clearPendingResultForActivity(IBinder activityToken,
6370 WeakReference<PendingIntentRecord> pir) {
6371 synchronized (mGlobalLock) {
6372 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6373 if (r != null && r.pendingResults != null) {
6374 r.pendingResults.remove(pir);
6375 }
6376 }
6377 }
6378
6379 @Override
6380 public IIntentSender getIntentSender(int type, String packageName,
6381 int callingUid, int userId, IBinder token, String resultWho,
6382 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6383 Bundle bOptions) {
6384 synchronized (mGlobalLock) {
6385 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6386 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6387 }
6388 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006389
6390 @Override
6391 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6392 synchronized (mGlobalLock) {
6393 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6394 if (r == null) {
6395 return null;
6396 }
6397 if (r.mServiceConnectionsHolder == null) {
6398 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6399 ActivityTaskManagerService.this, r);
6400 }
6401
6402 return r.mServiceConnectionsHolder;
6403 }
6404 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006405
6406 @Override
6407 public Intent getHomeIntent() {
6408 synchronized (mGlobalLock) {
6409 return ActivityTaskManagerService.this.getHomeIntent();
6410 }
6411 }
6412
6413 @Override
6414 public boolean startHomeActivity(int userId, String reason) {
6415 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006416 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006417 }
6418 }
6419
6420 @Override
6421 public boolean startHomeOnAllDisplays(int userId, String reason) {
6422 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006423 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006424 }
6425 }
6426
6427 @Override
6428 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6429 synchronized (mGlobalLock) {
6430 if (mFactoryTest == FACTORY_TEST_OFF) {
6431 return false;
6432 }
6433 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6434 && wpc.mName.equals(mTopComponent.getPackageName())) {
6435 return true;
6436 }
6437 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6438 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6439 }
6440 }
6441
6442 @Override
6443 public void updateTopComponentForFactoryTest() {
6444 synchronized (mGlobalLock) {
6445 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6446 return;
6447 }
6448 final ResolveInfo ri = mContext.getPackageManager()
6449 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6450 final CharSequence errorMsg;
6451 if (ri != null) {
6452 final ActivityInfo ai = ri.activityInfo;
6453 final ApplicationInfo app = ai.applicationInfo;
6454 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6455 mTopAction = Intent.ACTION_FACTORY_TEST;
6456 mTopData = null;
6457 mTopComponent = new ComponentName(app.packageName, ai.name);
6458 errorMsg = null;
6459 } else {
6460 errorMsg = mContext.getResources().getText(
6461 com.android.internal.R.string.factorytest_not_system);
6462 }
6463 } else {
6464 errorMsg = mContext.getResources().getText(
6465 com.android.internal.R.string.factorytest_no_action);
6466 }
6467 if (errorMsg == null) {
6468 return;
6469 }
6470
6471 mTopAction = null;
6472 mTopData = null;
6473 mTopComponent = null;
6474 mUiHandler.post(() -> {
6475 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6476 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006477 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006478 });
6479 }
6480 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006481
6482 @Override
6483 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6484 Runnable finishInstrumentationCallback) {
6485 synchronized (mGlobalLock) {
6486 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006487 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006488
6489 wpc.clearRecentTasks();
6490 wpc.clearActivities();
6491
6492 if (wpc.isInstrumenting()) {
6493 finishInstrumentationCallback.run();
6494 }
6495
Jorim Jaggid0752812018-10-16 16:07:20 +02006496 if (!restarting && hasVisibleActivities) {
6497 mWindowManager.deferSurfaceLayout();
6498 try {
6499 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6500 // If there was nothing to resume, and we are not already restarting
6501 // this process, but there is a visible activity that is hosted by the
6502 // process...then make sure all visible activities are running, taking
6503 // care of restarting this process.
6504 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6505 !PRESERVE_WINDOWS);
6506 }
6507 } finally {
6508 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006509 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006510 }
6511 }
6512 }
6513
6514 @Override
6515 public void closeSystemDialogs(String reason) {
6516 enforceNotIsolatedCaller("closeSystemDialogs");
6517
6518 final int pid = Binder.getCallingPid();
6519 final int uid = Binder.getCallingUid();
6520 final long origId = Binder.clearCallingIdentity();
6521 try {
6522 synchronized (mGlobalLock) {
6523 // Only allow this from foreground processes, so that background
6524 // applications can't abuse it to prevent system UI from being shown.
6525 if (uid >= FIRST_APPLICATION_UID) {
6526 final WindowProcessController proc = mPidMap.get(pid);
6527 if (!proc.isPerceptible()) {
6528 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6529 + " from background process " + proc);
6530 return;
6531 }
6532 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006533 mWindowManager.closeSystemDialogs(reason);
6534
Wale Ogunwaled32da472018-11-16 07:19:28 -08006535 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006536 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006537 // Call into AM outside the synchronized block.
6538 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006539 } finally {
6540 Binder.restoreCallingIdentity(origId);
6541 }
6542 }
6543
6544 @Override
6545 public void cleanupDisabledPackageComponents(
6546 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6547 synchronized (mGlobalLock) {
6548 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006549 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006550 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006551 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006552 mStackSupervisor.scheduleIdleLocked();
6553 }
6554
6555 // Clean-up disabled tasks
6556 getRecentTasks().cleanupDisabledPackageTasksLocked(
6557 packageName, disabledClasses, userId);
6558 }
6559 }
6560
6561 @Override
6562 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6563 int userId) {
6564 synchronized (mGlobalLock) {
6565
6566 boolean didSomething =
6567 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006568 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006569 null, doit, evenPersistent, userId);
6570 return didSomething;
6571 }
6572 }
6573
6574 @Override
6575 public void resumeTopActivities(boolean scheduleIdle) {
6576 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006577 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006578 if (scheduleIdle) {
6579 mStackSupervisor.scheduleIdleLocked();
6580 }
6581 }
6582 }
6583
6584 @Override
6585 public void preBindApplication(WindowProcessController wpc) {
6586 synchronized (mGlobalLock) {
6587 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6588 }
6589 }
6590
6591 @Override
6592 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6593 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006594 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006595 }
6596 }
6597
6598 @Override
6599 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6600 try {
6601 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6602 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6603 }
6604 } catch (RemoteException ex) {
6605 throw new SecurityException("Fail to check is caller a privileged app", ex);
6606 }
6607
6608 synchronized (mGlobalLock) {
6609 final long ident = Binder.clearCallingIdentity();
6610 try {
6611 if (mAmInternal.shouldConfirmCredentials(userId)) {
6612 if (mKeyguardController.isKeyguardLocked()) {
6613 // Showing launcher to avoid user entering credential twice.
6614 startHomeActivity(currentUserId, "notifyLockedProfile");
6615 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006616 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006617 }
6618 } finally {
6619 Binder.restoreCallingIdentity(ident);
6620 }
6621 }
6622 }
6623
6624 @Override
6625 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6626 mAmInternal.enforceCallingPermission(
6627 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6628
6629 synchronized (mGlobalLock) {
6630 final long ident = Binder.clearCallingIdentity();
6631 try {
6632 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6633 FLAG_ACTIVITY_TASK_ON_HOME);
6634 ActivityOptions activityOptions = options != null
6635 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006636 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006637 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006638 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006639 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006640 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006641 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6642 UserHandle.CURRENT);
6643 } finally {
6644 Binder.restoreCallingIdentity(ident);
6645 }
6646 }
6647 }
6648
6649 @Override
6650 public void writeActivitiesToProto(ProtoOutputStream proto) {
6651 synchronized (mGlobalLock) {
6652 // The output proto of "activity --proto activities"
6653 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006654 mRootActivityContainer.writeToProto(proto,
Nataniel Borges023ecb52019-01-16 14:15:43 -08006655 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR,
6656 WindowTraceLogLevel.ALL);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006657 }
6658 }
6659
6660 @Override
6661 public void saveANRState(String reason) {
6662 synchronized (mGlobalLock) {
6663 final StringWriter sw = new StringWriter();
6664 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6665 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6666 if (reason != null) {
6667 pw.println(" Reason: " + reason);
6668 }
6669 pw.println();
6670 getActivityStartController().dump(pw, " ", null);
6671 pw.println();
6672 pw.println("-------------------------------------------------------------------------------");
6673 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6674 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6675 "" /* header */);
6676 pw.println();
6677 pw.close();
6678
6679 mLastANRState = sw.toString();
6680 }
6681 }
6682
6683 @Override
6684 public void clearSavedANRState() {
6685 synchronized (mGlobalLock) {
6686 mLastANRState = null;
6687 }
6688 }
6689
6690 @Override
6691 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6692 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6693 synchronized (mGlobalLock) {
6694 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6695 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6696 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6697 dumpLastANRLocked(pw);
6698 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6699 dumpLastANRTracesLocked(pw);
6700 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6701 dumpActivityStarterLocked(pw, dumpPackage);
6702 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6703 dumpActivityContainersLocked(pw);
6704 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6705 if (getRecentTasks() != null) {
6706 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6707 }
6708 }
6709 }
6710 }
6711
6712 @Override
6713 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6714 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6715 int wakefulness) {
6716 synchronized (mGlobalLock) {
6717 if (mHomeProcess != null && (dumpPackage == null
6718 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6719 if (needSep) {
6720 pw.println();
6721 needSep = false;
6722 }
6723 pw.println(" mHomeProcess: " + mHomeProcess);
6724 }
6725 if (mPreviousProcess != null && (dumpPackage == null
6726 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6727 if (needSep) {
6728 pw.println();
6729 needSep = false;
6730 }
6731 pw.println(" mPreviousProcess: " + mPreviousProcess);
6732 }
6733 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6734 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6735 StringBuilder sb = new StringBuilder(128);
6736 sb.append(" mPreviousProcessVisibleTime: ");
6737 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6738 pw.println(sb);
6739 }
6740 if (mHeavyWeightProcess != null && (dumpPackage == null
6741 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6742 if (needSep) {
6743 pw.println();
6744 needSep = false;
6745 }
6746 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6747 }
6748 if (dumpPackage == null) {
6749 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006750 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006751 }
6752 if (dumpAll) {
6753 if (dumpPackage == null) {
6754 pw.println(" mConfigWillChange: "
6755 + getTopDisplayFocusedStack().mConfigWillChange);
6756 }
6757 if (mCompatModePackages.getPackages().size() > 0) {
6758 boolean printed = false;
6759 for (Map.Entry<String, Integer> entry
6760 : mCompatModePackages.getPackages().entrySet()) {
6761 String pkg = entry.getKey();
6762 int mode = entry.getValue();
6763 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6764 continue;
6765 }
6766 if (!printed) {
6767 pw.println(" mScreenCompatPackages:");
6768 printed = true;
6769 }
6770 pw.println(" " + pkg + ": " + mode);
6771 }
6772 }
6773 }
6774
6775 if (dumpPackage == null) {
6776 pw.println(" mWakefulness="
6777 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006778 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006779 if (mRunningVoice != null) {
6780 pw.println(" mRunningVoice=" + mRunningVoice);
6781 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6782 }
6783 pw.println(" mSleeping=" + mSleeping);
6784 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6785 pw.println(" mVrController=" + mVrController);
6786 }
6787 if (mCurAppTimeTracker != null) {
6788 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6789 }
6790 if (mAllowAppSwitchUids.size() > 0) {
6791 boolean printed = false;
6792 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6793 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6794 for (int j = 0; j < types.size(); j++) {
6795 if (dumpPackage == null ||
6796 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6797 if (needSep) {
6798 pw.println();
6799 needSep = false;
6800 }
6801 if (!printed) {
6802 pw.println(" mAllowAppSwitchUids:");
6803 printed = true;
6804 }
6805 pw.print(" User ");
6806 pw.print(mAllowAppSwitchUids.keyAt(i));
6807 pw.print(": Type ");
6808 pw.print(types.keyAt(j));
6809 pw.print(" = ");
6810 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6811 pw.println();
6812 }
6813 }
6814 }
6815 }
6816 if (dumpPackage == null) {
6817 if (mController != null) {
6818 pw.println(" mController=" + mController
6819 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6820 }
6821 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6822 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6823 }
6824
6825 return needSep;
6826 }
6827 }
6828
6829 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006830 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6831 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006832 synchronized (mGlobalLock) {
6833 if (dumpPackage == null) {
6834 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6835 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006836 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6837 if (mRunningVoice != null) {
6838 final long vrToken = proto.start(
6839 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6840 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6841 mRunningVoice.toString());
6842 mVoiceWakeLock.writeToProto(
6843 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6844 proto.end(vrToken);
6845 }
6846 mVrController.writeToProto(proto,
6847 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006848 if (mController != null) {
6849 final long token = proto.start(CONTROLLER);
6850 proto.write(CONTROLLER, mController.toString());
6851 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6852 proto.end(token);
6853 }
6854 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6855 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6856 }
6857
6858 if (mHomeProcess != null && (dumpPackage == null
6859 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006860 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006861 }
6862
6863 if (mPreviousProcess != null && (dumpPackage == null
6864 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006865 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006866 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6867 }
6868
6869 if (mHeavyWeightProcess != null && (dumpPackage == null
6870 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006871 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006872 }
6873
6874 for (Map.Entry<String, Integer> entry
6875 : mCompatModePackages.getPackages().entrySet()) {
6876 String pkg = entry.getKey();
6877 int mode = entry.getValue();
6878 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6879 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6880 proto.write(PACKAGE, pkg);
6881 proto.write(MODE, mode);
6882 proto.end(compatToken);
6883 }
6884 }
6885
6886 if (mCurAppTimeTracker != null) {
6887 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6888 }
6889
6890 }
6891 }
6892
6893 @Override
6894 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6895 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6896 boolean dumpFocusedStackOnly) {
6897 synchronized (mGlobalLock) {
6898 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6899 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6900 }
6901 }
6902
6903 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006904 public void dumpForOom(PrintWriter pw) {
6905 synchronized (mGlobalLock) {
6906 pw.println(" mHomeProcess: " + mHomeProcess);
6907 pw.println(" mPreviousProcess: " + mPreviousProcess);
6908 if (mHeavyWeightProcess != null) {
6909 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6910 }
6911 }
6912 }
6913
6914 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006915 public boolean canGcNow() {
6916 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006917 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006918 }
6919 }
6920
6921 @Override
6922 public WindowProcessController getTopApp() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006923 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006924 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006925 return top != null ? top.app : null;
6926 }
6927 }
6928
6929 @Override
6930 public void rankTaskLayersIfNeeded() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006931 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006932 if (mRootActivityContainer != null) {
6933 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006934 }
6935 }
6936 }
6937
6938 @Override
6939 public void scheduleDestroyAllActivities(String reason) {
6940 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006941 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006942 }
6943 }
6944
6945 @Override
6946 public void removeUser(int userId) {
6947 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006948 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006949 }
6950 }
6951
6952 @Override
6953 public boolean switchUser(int userId, UserState userState) {
6954 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006955 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006956 }
6957 }
6958
6959 @Override
6960 public void onHandleAppCrash(WindowProcessController wpc) {
6961 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006962 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006963 }
6964 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006965
6966 @Override
6967 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6968 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006969 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006970 }
6971 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006972
6973 @Override
6974 public void onUidActive(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006975 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006976 mActiveUids.put(uid, procState);
6977 }
6978 }
6979
6980 @Override
6981 public void onUidInactive(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006982 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006983 mActiveUids.remove(uid);
6984 }
6985 }
6986
6987 @Override
6988 public void onActiveUidsCleared() {
Riddle Hsud7088f82019-01-30 13:04:50 +08006989 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006990 mActiveUids.clear();
6991 }
6992 }
6993
6994 @Override
6995 public void onUidProcStateChanged(int uid, int procState) {
Riddle Hsud7088f82019-01-30 13:04:50 +08006996 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006997 if (mActiveUids.get(uid) != null) {
6998 mActiveUids.put(uid, procState);
6999 }
7000 }
7001 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07007002
7003 @Override
7004 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007005 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007006 mPendingTempWhitelist.put(uid, tag);
7007 }
7008 }
7009
7010 @Override
7011 public void onUidRemovedFromPendingTempWhitelist(int uid) {
Riddle Hsud7088f82019-01-30 13:04:50 +08007012 synchronized (mGlobalLockWithoutBoost) {
Wale Ogunwale9de19442018-10-18 19:05:03 -07007013 mPendingTempWhitelist.remove(uid);
7014 }
7015 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07007016
7017 @Override
7018 public boolean handleAppCrashInActivityController(String processName, int pid,
7019 String shortMsg, String longMsg, long timeMillis, String stackTrace,
7020 Runnable killCrashingAppCallback) {
7021 synchronized (mGlobalLock) {
7022 if (mController == null) {
7023 return false;
7024 }
7025
7026 try {
7027 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
7028 stackTrace)) {
7029 killCrashingAppCallback.run();
7030 return true;
7031 }
7032 } catch (RemoteException e) {
7033 mController = null;
7034 Watchdog.getInstance().setActivityController(null);
7035 }
7036 return false;
7037 }
7038 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07007039
7040 @Override
7041 public void removeRecentTasksByPackageName(String packageName, int userId) {
7042 synchronized (mGlobalLock) {
7043 mRecentTasks.removeTasksByPackageName(packageName, userId);
7044 }
7045 }
7046
7047 @Override
7048 public void cleanupRecentTasksForUser(int userId) {
7049 synchronized (mGlobalLock) {
7050 mRecentTasks.cleanupLocked(userId);
7051 }
7052 }
7053
7054 @Override
7055 public void loadRecentTasksForUser(int userId) {
7056 synchronized (mGlobalLock) {
7057 mRecentTasks.loadUserRecentsLocked(userId);
7058 }
7059 }
7060
7061 @Override
7062 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
7063 synchronized (mGlobalLock) {
7064 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
7065 }
7066 }
7067
7068 @Override
7069 public void flushRecentTasks() {
7070 mRecentTasks.flush();
7071 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07007072
7073 @Override
7074 public WindowProcessController getHomeProcess() {
7075 synchronized (mGlobalLock) {
7076 return mHomeProcess;
7077 }
7078 }
7079
7080 @Override
7081 public WindowProcessController getPreviousProcess() {
7082 synchronized (mGlobalLock) {
7083 return mPreviousProcess;
7084 }
7085 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07007086
7087 @Override
7088 public void clearLockedTasks(String reason) {
7089 synchronized (mGlobalLock) {
7090 getLockTaskController().clearLockedTasks(reason);
7091 }
7092 }
7093
7094 @Override
7095 public void updateUserConfiguration() {
7096 synchronized (mGlobalLock) {
7097 final Configuration configuration = new Configuration(getGlobalConfiguration());
7098 final int currentUserId = mAmInternal.getCurrentUserId();
7099 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
7100 configuration, currentUserId, Settings.System.canWrite(mContext));
7101 updateConfigurationLocked(configuration, null /* starting */,
7102 false /* initLocale */, false /* persistent */, currentUserId,
7103 false /* deferResume */);
7104 }
7105 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07007106
7107 @Override
7108 public boolean canShowErrorDialogs() {
7109 synchronized (mGlobalLock) {
7110 return mShowDialogs && !mSleeping && !mShuttingDown
7111 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
7112 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
7113 mAmInternal.getCurrentUserId())
7114 && !(UserManager.isDeviceInDemoMode(mContext)
7115 && mAmInternal.getCurrentUser().isDemo());
7116 }
7117 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007118
7119 @Override
7120 public void setProfileApp(String profileApp) {
7121 synchronized (mGlobalLock) {
7122 mProfileApp = profileApp;
7123 }
7124 }
7125
7126 @Override
7127 public void setProfileProc(WindowProcessController wpc) {
7128 synchronized (mGlobalLock) {
7129 mProfileProc = wpc;
7130 }
7131 }
7132
7133 @Override
7134 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7135 synchronized (mGlobalLock) {
7136 mProfilerInfo = profilerInfo;
7137 }
7138 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007139
7140 @Override
7141 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7142 synchronized (mGlobalLock) {
7143 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7144 }
7145 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007146
7147 @Override
7148 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7149 synchronized (mGlobalLock) {
7150 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7151 }
7152 }
Michal Karpinskicc88d7e2019-01-24 15:32:12 +00007153
7154 @Override
7155 public boolean isUidForeground(int uid) {
7156 synchronized (mGlobalLock) {
7157 return ActivityTaskManagerService.this.isUidForeground(uid);
7158 }
7159 }
Michal Karpinski4026cae2019-02-12 11:51:47 +00007160
7161 @Override
7162 public void setDeviceOwnerPackageName(String deviceOwnerPkg) {
7163 synchronized (mGlobalLock) {
7164 ActivityTaskManagerService.this.setDeviceOwnerPackageName(deviceOwnerPkg);
7165 }
7166 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007167 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007168}