blob: ba8662ab769c016dec80a3f5ff6cfe54a10c5972 [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
17package com.android.server.am;
18
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.ALWAYS_FINISH_ACTIVITIES;
60import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
62import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070063import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
64import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070065import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
66import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070068import static android.view.WindowManager.TRANSIT_ACTIVITY_OPEN;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070069import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070070import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070071import static android.view.WindowManager.TRANSIT_TASK_OPEN;
72import static android.view.WindowManager.TRANSIT_TASK_TO_FRONT;
Evan Rosky4505b352018-09-06 11:20:40 -070073
Yunfan Chen79b96062018-10-17 12:45:23 -070074import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
75import static com.android.server.am.ActivityManagerService.MY_PID;
76import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
77import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070078import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
85import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
86import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
87import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen79b96062018-10-17 12:45:23 -070088import static com.android.server.am.ActivityManagerServiceDumpProcessesProto
89 .PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070090import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen79b96062018-10-17 12:45:23 -070091import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
92 .MODE;
93import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
94 .PACKAGE;
95import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
96import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
97import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
98import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
99import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
100import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
101import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
Wale Ogunwale98875612018-10-12 07:53:02 -0700102import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_ALL;
103import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
104import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
105import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
106import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
107import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STACK;
108import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
109import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
110import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
111import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
112import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
113import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
114import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
115import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
116import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
117import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
118import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
119import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700120import static com.android.server.am.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
121import static com.android.server.am.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700122import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700123import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700124import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -0700125import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
126import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
127import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
128import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700129import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
130import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700132import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700133import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700134import android.annotation.Nullable;
135import android.annotation.UserIdInt;
136import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700137import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700138import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700139import android.app.ActivityOptions;
140import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700141import android.app.ActivityThread;
142import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700143import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700144import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700145import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700146import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700147import android.app.IApplicationThread;
148import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700149import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700150import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700151import android.app.Notification;
152import android.app.NotificationManager;
153import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700154import android.app.PictureInPictureParams;
155import android.app.ProfilerInfo;
156import android.app.RemoteAction;
157import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700158import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700159import android.app.admin.DevicePolicyCache;
160import android.app.assist.AssistContent;
161import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700162import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700163import android.content.ActivityNotFoundException;
164import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700166import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.IIntentSender;
169import android.content.Intent;
170import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700171import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900172import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700173import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700174import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.content.pm.ParceledListSlice;
177import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700178import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700180import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700181import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700182import android.graphics.Bitmap;
183import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700184import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700185import android.metrics.LogMaker;
186import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700187import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700188import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700189import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700190import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700191import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700192import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700193import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700194import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700195import android.os.LocaleList;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700196import android.os.Looper;
197import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700198import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700199import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700200import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700201import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700202import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700203import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700204import android.os.SystemClock;
205import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700206import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700207import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700208import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700209import android.os.UserManager;
210import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700211import android.os.storage.IStorageManager;
212import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700213import android.provider.Settings;
214import android.service.voice.IVoiceInteractionSession;
215import android.service.voice.VoiceInteractionManagerInternal;
216import android.telecom.TelecomManager;
217import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700218import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700219import android.util.ArrayMap;
220import android.util.EventLog;
221import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700222import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700223import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700224import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700225import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700226import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700227import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700228import android.view.IRecentsAnimationRunner;
229import android.view.RemoteAnimationAdapter;
230import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700232
Evan Rosky4505b352018-09-06 11:20:40 -0700233import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700234import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700236import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700237import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700238import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700239import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700241import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
242import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700243import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700244import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700245import com.android.internal.policy.IKeyguardDismissCallback;
246import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700247import com.android.internal.util.ArrayUtils;
248import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700249import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700250import com.android.internal.util.function.pooled.PooledLambda;
Evan Rosky4505b352018-09-06 11:20:40 -0700251import com.android.server.AppOpsService;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700252import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700253import com.android.server.LocalServices;
254import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700255import com.android.server.SystemServiceManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700256import com.android.server.Watchdog;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700257import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700258import com.android.server.pm.UserManagerService;
259import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700260import com.android.server.vr.VrManagerInternal;
Evan Rosky4505b352018-09-06 11:20:40 -0700261import com.android.server.wm.ActivityTaskManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700262import com.android.server.wm.PinnedStackWindowController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700263import com.android.server.wm.WindowManagerService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700264
Wale Ogunwale31913b52018-10-13 08:29:31 -0700265import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700267import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700268import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700270import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700271import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700272import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700273import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700274import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700275import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700276import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700277import java.util.Date;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700278import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700279import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700280import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700281import java.util.Map;
282import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700283
284/**
285 * System service for managing activities and their containers (task, stacks, displays,... ).
286 *
287 * {@hide}
288 */
289public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700290 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700291 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700292 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
293 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
294 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
295 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
296 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700297 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700298
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700299 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700300 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700301 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700302 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700303
Wale Ogunwale98875612018-10-12 07:53:02 -0700304 /** Used to indicate that an app transition should be animated. */
305 static final boolean ANIMATE = true;
306
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700307 /** Hardware-reported OpenGLES version. */
308 final int GL_ES_VERSION;
309
Wale Ogunwale31913b52018-10-13 08:29:31 -0700310 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
311 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
312 public static final String DUMP_LASTANR_CMD = "lastanr" ;
313 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
314 public static final String DUMP_STARTER_CMD = "starter" ;
315 public static final String DUMP_CONTAINERS_CMD = "containers" ;
316 public static final String DUMP_RECENTS_CMD = "recents" ;
317 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
318
Wale Ogunwale64258362018-10-16 15:13:37 -0700319 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
320 public static final int RELAUNCH_REASON_NONE = 0;
321 /** This activity is being relaunched due to windowing mode change. */
322 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
323 /** This activity is being relaunched due to a free-resize operation. */
324 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
325
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700326 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700327
Wale Ogunwalef6733932018-06-27 05:14:34 -0700328 /**
329 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
330 * change at runtime. Use mContext for non-UI purposes.
331 */
332 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700333 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700334 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700335 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700336 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700337 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700338 private PackageManagerInternal mPmInternal;
Wale Ogunwale53783742018-09-16 10:21:51 -0700339 private ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700340 PowerManagerInternal mPowerManagerInternal;
341 private UsageStatsManagerInternal mUsageStatsInternal;
342
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700343 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 IntentFirewall mIntentFirewall;
345
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700346 /* Global service lock used by the package the owns this service. */
347 Object mGlobalLock;
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700348 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700349 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700350 private UserManagerService mUserManager;
351 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700352 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700353 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
354 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700355 /** All processes currently running that might have a window organized by name. */
356 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700357 /** All processes we currently have running mapped by pid */
358 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700359 /** This is the process holding what we currently consider to be the "home" activity. */
360 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700361 /** The currently running heavy-weight process, if any. */
362 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700363 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700364 /**
365 * This is the process holding the activity the user last visited that is in a different process
366 * from the one they are currently in.
367 */
368 WindowProcessController mPreviousProcess;
369 /** The time at which the previous process was last visible. */
370 long mPreviousProcessVisibleTime;
371
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700372 /** List of intents that were used to start the most recent tasks. */
373 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700374 /** State of external calls telling us if the device is awake or asleep. */
375 private boolean mKeyguardShown = false;
376
377 // Wrapper around VoiceInteractionServiceManager
378 private AssistUtils mAssistUtils;
379
380 // VoiceInteraction session ID that changes for each new request except when
381 // being called for multi-window assist in a single session.
382 private int mViSessionId = 1000;
383
384 // How long to wait in getAssistContextExtras for the activity and foreground services
385 // to respond with the result.
386 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
387
388 // How long top wait when going through the modern assist (which doesn't need to block
389 // on getting this result before starting to launch its UI).
390 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
391
392 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
393 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
394
395 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
396
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700397 // Keeps track of the active voice interaction service component, notified from
398 // VoiceInteractionManagerService
399 ComponentName mActiveVoiceInteractionServiceComponent;
400
Wale Ogunwalee2172292018-10-25 10:11:10 -0700401 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700402 KeyguardController mKeyguardController;
403 private final ClientLifecycleManager mLifecycleManager;
404 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700405 /** The controller for all operations related to locktask. */
406 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700407 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700408
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700409 boolean mSuppressResizeConfigChanges;
410
411 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
412 new UpdateConfigurationResult();
413
414 static final class UpdateConfigurationResult {
415 // Configuration changes that were updated.
416 int changes;
417 // If the activity was relaunched to match the new configuration.
418 boolean activityRelaunched;
419
420 void reset() {
421 changes = 0;
422 activityRelaunched = false;
423 }
424 }
425
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700426 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700427 private int mConfigurationSeq;
428 // To cache the list of supported system locales
429 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700430
431 /**
432 * Temp object used when global and/or display override configuration is updated. It is also
433 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
434 * anyone...
435 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700436 private Configuration mTempConfig = new Configuration();
437
Wale Ogunwalef6733932018-06-27 05:14:34 -0700438 /** Temporary to avoid allocations. */
439 final StringBuilder mStringBuilder = new StringBuilder(256);
440
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700441 // Amount of time after a call to stopAppSwitches() during which we will
442 // prevent further untrusted switches from happening.
443 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
444
445 /**
446 * The time at which we will allow normal application switches again,
447 * after a call to {@link #stopAppSwitches()}.
448 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700449 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700450 /**
451 * This is set to true after the first switch after mAppSwitchesAllowedTime
452 * is set; any switches after that will clear the time.
453 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700454 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700455
456 IActivityController mController = null;
457 boolean mControllerIsAMonkey = false;
458
Wale Ogunwale214f3482018-10-04 11:00:47 -0700459 final int mFactoryTest;
460
461 /** Used to control how we initialize the service. */
462 ComponentName mTopComponent;
463 String mTopAction = Intent.ACTION_MAIN;
464 String mTopData;
465
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700466 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700467 * Dump of the activity state at the time of the last ANR. Cleared after
468 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
469 */
470 String mLastANRState;
471
472 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700473 * Used to retain an update lock when the foreground activity is in
474 * immersive mode.
475 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700476 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700477
478 /**
479 * Packages that are being allowed to perform unrestricted app switches. Mapping is
480 * User -> Type -> uid.
481 */
482 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
483
484 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700485 private int mThumbnailWidth;
486 private int mThumbnailHeight;
487 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700488
489 /**
490 * Flag that indicates if multi-window is enabled.
491 *
492 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
493 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
494 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
495 * At least one of the forms of multi-window must be enabled in order for this flag to be
496 * initialized to 'true'.
497 *
498 * @see #mSupportsSplitScreenMultiWindow
499 * @see #mSupportsFreeformWindowManagement
500 * @see #mSupportsPictureInPicture
501 * @see #mSupportsMultiDisplay
502 */
503 boolean mSupportsMultiWindow;
504 boolean mSupportsSplitScreenMultiWindow;
505 boolean mSupportsFreeformWindowManagement;
506 boolean mSupportsPictureInPicture;
507 boolean mSupportsMultiDisplay;
508 boolean mForceResizableActivities;
509
510 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
511
512 // VR Vr2d Display Id.
513 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700514
Wale Ogunwalef6733932018-06-27 05:14:34 -0700515 /**
516 * Set while we are wanting to sleep, to prevent any
517 * activities from being started/resumed.
518 *
519 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
520 *
521 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
522 * while in the sleep state until there is a pending transition out of sleep, in which case
523 * mSleeping is set to false, and remains false while awake.
524 *
525 * Whether mSleeping can quickly toggled between true/false without the device actually
526 * display changing states is undefined.
527 */
528 private boolean mSleeping = false;
529
530 /**
531 * The process state used for processes that are running the top activities.
532 * This changes between TOP and TOP_SLEEPING to following mSleeping.
533 */
534 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
535
536 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
537 // automatically. Important for devices without direct input devices.
538 private boolean mShowDialogs = true;
539
540 /** Set if we are shutting down the system, similar to sleeping. */
541 boolean mShuttingDown = false;
542
543 /**
544 * We want to hold a wake lock while running a voice interaction session, since
545 * this may happen with the screen off and we need to keep the CPU running to
546 * be able to continue to interact with the user.
547 */
548 PowerManager.WakeLock mVoiceWakeLock;
549
550 /**
551 * Set while we are running a voice interaction. This overrides sleeping while it is active.
552 */
553 IVoiceInteractionSession mRunningVoice;
554
555 /**
556 * The last resumed activity. This is identical to the current resumed activity most
557 * of the time but could be different when we're pausing one activity before we resume
558 * another activity.
559 */
560 ActivityRecord mLastResumedActivity;
561
562 /**
563 * The activity that is currently being traced as the active resumed activity.
564 *
565 * @see #updateResumedAppTrace
566 */
567 private @Nullable ActivityRecord mTracedResumedActivity;
568
569 /** If non-null, we are tracking the time the user spends in the currently focused app. */
570 AppTimeTracker mCurAppTimeTracker;
571
Wale Ogunwale008163e2018-07-23 23:11:08 -0700572 private AppWarnings mAppWarnings;
573
Wale Ogunwale53783742018-09-16 10:21:51 -0700574 /**
575 * Packages that the user has asked to have run in screen size
576 * compatibility mode instead of filling the screen.
577 */
578 CompatModePackages mCompatModePackages;
579
Wale Ogunwalef6733932018-06-27 05:14:34 -0700580 private FontScaleSettingObserver mFontScaleSettingObserver;
581
582 private final class FontScaleSettingObserver extends ContentObserver {
583 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
584 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
585
586 public FontScaleSettingObserver() {
587 super(mH);
588 final ContentResolver resolver = mContext.getContentResolver();
589 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
590 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
591 UserHandle.USER_ALL);
592 }
593
594 @Override
595 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
596 if (mFontScaleUri.equals(uri)) {
597 updateFontScaleIfNeeded(userId);
598 } else if (mHideErrorDialogsUri.equals(uri)) {
599 synchronized (mGlobalLock) {
600 updateShouldShowDialogsLocked(getGlobalConfiguration());
601 }
602 }
603 }
604 }
605
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700606 ActivityTaskManagerService(Context context) {
607 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700608 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700609 mSystemThread = ActivityThread.currentActivityThread();
610 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700611 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700612 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700613 }
614
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700615 public void onSystemReady() {
616 synchronized (mGlobalLock) {
617 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
618 PackageManager.FEATURE_CANT_SAVE_STATE);
619 mAssistUtils = new AssistUtils(mContext);
620 mVrController.onSystemReady();
621 mRecentTasks.onSystemReadyLocked();
622 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700623 }
624
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700625 public void onInitPowerManagement() {
626 synchronized (mGlobalLock) {
627 mStackSupervisor.initPowerManagement();
628 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
629 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
630 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
631 mVoiceWakeLock.setReferenceCounted(false);
632 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700633 }
634
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700635 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700636 mFontScaleSettingObserver = new FontScaleSettingObserver();
637 }
638
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700639 void retrieveSettings(ContentResolver resolver) {
640 final boolean freeformWindowManagement =
641 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
642 || Settings.Global.getInt(
643 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
644
645 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
646 final boolean supportsPictureInPicture = supportsMultiWindow &&
647 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
648 final boolean supportsSplitScreenMultiWindow =
649 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
650 final boolean supportsMultiDisplay = mContext.getPackageManager()
651 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
652 final boolean alwaysFinishActivities =
653 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
654 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
655 final boolean forceResizable = Settings.Global.getInt(
656 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700657 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700658
659 // Transfer any global setting for forcing RTL layout, into a System Property
660 SystemProperties.set(DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
661
662 final Configuration configuration = new Configuration();
663 Settings.System.getConfiguration(resolver, configuration);
664 if (forceRtl) {
665 // This will take care of setting the correct layout direction flags
666 configuration.setLayoutDirection(configuration.locale);
667 }
668
669 synchronized (mGlobalLock) {
670 mForceResizableActivities = forceResizable;
671 final boolean multiWindowFormEnabled = freeformWindowManagement
672 || supportsSplitScreenMultiWindow
673 || supportsPictureInPicture
674 || supportsMultiDisplay;
675 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
676 mSupportsMultiWindow = true;
677 mSupportsFreeformWindowManagement = freeformWindowManagement;
678 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
679 mSupportsPictureInPicture = supportsPictureInPicture;
680 mSupportsMultiDisplay = supportsMultiDisplay;
681 } else {
682 mSupportsMultiWindow = false;
683 mSupportsFreeformWindowManagement = false;
684 mSupportsSplitScreenMultiWindow = false;
685 mSupportsPictureInPicture = false;
686 mSupportsMultiDisplay = false;
687 }
688 mWindowManager.setForceResizableTasks(mForceResizableActivities);
689 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700690 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
691 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700692 // This happens before any activities are started, so we can change global configuration
693 // in-place.
694 updateConfigurationLocked(configuration, null, true);
695 final Configuration globalConfig = getGlobalConfiguration();
696 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
697
698 // Load resources only after the current configuration has been set.
699 final Resources res = mContext.getResources();
700 mThumbnailWidth = res.getDimensionPixelSize(
701 com.android.internal.R.dimen.thumbnail_width);
702 mThumbnailHeight = res.getDimensionPixelSize(
703 com.android.internal.R.dimen.thumbnail_height);
704
705 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
706 mFullscreenThumbnailScale = (float) res
707 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
708 (float) globalConfig.screenWidthDp;
709 } else {
710 mFullscreenThumbnailScale = res.getFraction(
711 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
712 }
713 }
714 }
715
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700716 // TODO: Will be converted to WM lock once transition is complete.
Wale Ogunwale9de19442018-10-18 19:05:03 -0700717 void setActivityManagerService(Object globalLock, Looper looper,
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700718 IntentFirewall intentFirewall, PendingIntentController intentController) {
Wale Ogunwale9de19442018-10-18 19:05:03 -0700719 mGlobalLock = globalLock;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700720 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700721 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700722 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700723 final File systemDir = SystemServiceManager.ensureSystemDir();
724 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
725 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700726 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700727
728 mTempConfig.setToDefaults();
729 mTempConfig.setLocales(LocaleList.getDefault());
730 mConfigurationSeq = mTempConfig.seq = 1;
731 mStackSupervisor = createStackSupervisor();
732 mStackSupervisor.onConfigurationChanged(mTempConfig);
733
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700734 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700735 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700736 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700737 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700738 mRecentTasks = createRecentTasks();
739 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700740 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700741 mKeyguardController = mStackSupervisor.getKeyguardController();
742 }
743
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700744 public void onActivityManagerInternalAdded() {
745 synchronized (mGlobalLock) {
746 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
747 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
748 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700749 }
750
Yunfan Chen75157d72018-07-27 14:47:21 +0900751 int increaseConfigurationSeqLocked() {
752 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
753 return mConfigurationSeq;
754 }
755
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700756 protected ActivityStackSupervisor createStackSupervisor() {
757 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
758 supervisor.initialize();
759 return supervisor;
760 }
761
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700762 public void setWindowManager(WindowManagerService wm) {
763 synchronized (mGlobalLock) {
764 mWindowManager = wm;
765 mLockTaskController.setWindowManager(wm);
766 mStackSupervisor.setWindowManager(wm);
767 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700768 }
769
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700770 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
771 synchronized (mGlobalLock) {
772 mUsageStatsInternal = usageStatsManager;
773 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700774 }
775
Wale Ogunwalef6733932018-06-27 05:14:34 -0700776 UserManagerService getUserManager() {
777 if (mUserManager == null) {
778 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
779 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
780 }
781 return mUserManager;
782 }
783
784 AppOpsService getAppOpsService() {
785 if (mAppOpsService == null) {
786 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
787 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
788 }
789 return mAppOpsService;
790 }
791
792 boolean hasUserRestriction(String restriction, int userId) {
793 return getUserManager().hasUserRestriction(restriction, userId);
794 }
795
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700796 protected RecentTasks createRecentTasks() {
797 return new RecentTasks(this, mStackSupervisor);
798 }
799
800 RecentTasks getRecentTasks() {
801 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700802 }
803
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700804 ClientLifecycleManager getLifecycleManager() {
805 return mLifecycleManager;
806 }
807
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700808 ActivityStartController getActivityStartController() {
809 return mActivityStartController;
810 }
811
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700812 TaskChangeNotificationController getTaskChangeNotificationController() {
813 return mTaskChangeNotificationController;
814 }
815
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700816 LockTaskController getLockTaskController() {
817 return mLockTaskController;
818 }
819
Yunfan Chen75157d72018-07-27 14:47:21 +0900820 /**
821 * Return the global configuration used by the process corresponding to the input pid. This is
822 * usually the global configuration with some overrides specific to that process.
823 */
824 Configuration getGlobalConfigurationForCallingPid() {
825 final int pid = Binder.getCallingPid();
826 if (pid == MY_PID || pid < 0) {
827 return getGlobalConfiguration();
828 }
829 synchronized (mGlobalLock) {
830 final WindowProcessController app = mPidMap.get(pid);
831 return app != null ? app.getConfiguration() : getGlobalConfiguration();
832 }
833 }
834
835 /**
836 * Return the device configuration info used by the process corresponding to the input pid.
837 * The value is consistent with the global configuration for the process.
838 */
839 @Override
840 public ConfigurationInfo getDeviceConfigurationInfo() {
841 ConfigurationInfo config = new ConfigurationInfo();
842 synchronized (mGlobalLock) {
843 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
844 config.reqTouchScreen = globalConfig.touchscreen;
845 config.reqKeyboardType = globalConfig.keyboard;
846 config.reqNavigation = globalConfig.navigation;
847 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
848 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
849 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
850 }
851 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
852 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
853 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
854 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700855 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900856 }
857 return config;
858 }
859
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700860 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700861 mInternal = new LocalService();
862 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700863 }
864
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700865 public static final class Lifecycle extends SystemService {
866 private final ActivityTaskManagerService mService;
867
868 public Lifecycle(Context context) {
869 super(context);
870 mService = new ActivityTaskManagerService(context);
871 }
872
873 @Override
874 public void onStart() {
875 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700876 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700877 }
878
879 public ActivityTaskManagerService getService() {
880 return mService;
881 }
882 }
883
884 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700885 public final int startActivity(IApplicationThread caller, String callingPackage,
886 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
887 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
888 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
889 resultWho, requestCode, startFlags, profilerInfo, bOptions,
890 UserHandle.getCallingUserId());
891 }
892
893 @Override
894 public final int startActivities(IApplicationThread caller, String callingPackage,
895 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
896 int userId) {
897 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700898 enforceNotIsolatedCaller(reason);
899 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700900 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700901 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100902 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
903 null /* originatingPendingIntent */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700904 }
905
906 @Override
907 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
908 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
909 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
910 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
911 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
912 true /*validateIncomingUser*/);
913 }
914
915 int startActivityAsUser(IApplicationThread caller, String callingPackage,
916 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
917 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
918 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700919 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700920
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700921 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700922 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
923
924 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700925 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700926 .setCaller(caller)
927 .setCallingPackage(callingPackage)
928 .setResolvedType(resolvedType)
929 .setResultTo(resultTo)
930 .setResultWho(resultWho)
931 .setRequestCode(requestCode)
932 .setStartFlags(startFlags)
933 .setProfilerInfo(profilerInfo)
934 .setActivityOptions(bOptions)
935 .setMayWait(userId)
936 .execute();
937
938 }
939
940 @Override
941 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
942 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700943 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
944 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700945 // Refuse possible leaked file descriptors
946 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
947 throw new IllegalArgumentException("File descriptors passed in Intent");
948 }
949
950 if (!(target instanceof PendingIntentRecord)) {
951 throw new IllegalArgumentException("Bad PendingIntent object");
952 }
953
954 PendingIntentRecord pir = (PendingIntentRecord)target;
955
956 synchronized (mGlobalLock) {
957 // If this is coming from the currently resumed activity, it is
958 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -0700959 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700960 if (stack.mResumedActivity != null &&
961 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700962 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700963 }
964 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700965 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700966 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700967 }
968
969 @Override
970 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
971 Bundle bOptions) {
972 // Refuse possible leaked file descriptors
973 if (intent != null && intent.hasFileDescriptors()) {
974 throw new IllegalArgumentException("File descriptors passed in Intent");
975 }
976 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
977
978 synchronized (mGlobalLock) {
979 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
980 if (r == null) {
981 SafeActivityOptions.abort(options);
982 return false;
983 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700984 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700985 // The caller is not running... d'oh!
986 SafeActivityOptions.abort(options);
987 return false;
988 }
989 intent = new Intent(intent);
990 // The caller is not allowed to change the data.
991 intent.setDataAndType(r.intent.getData(), r.intent.getType());
992 // And we are resetting to find the next component...
993 intent.setComponent(null);
994
995 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
996
997 ActivityInfo aInfo = null;
998 try {
999 List<ResolveInfo> resolves =
1000 AppGlobals.getPackageManager().queryIntentActivities(
1001 intent, r.resolvedType,
1002 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1003 UserHandle.getCallingUserId()).getList();
1004
1005 // Look for the original activity in the list...
1006 final int N = resolves != null ? resolves.size() : 0;
1007 for (int i=0; i<N; i++) {
1008 ResolveInfo rInfo = resolves.get(i);
1009 if (rInfo.activityInfo.packageName.equals(r.packageName)
1010 && rInfo.activityInfo.name.equals(r.info.name)) {
1011 // We found the current one... the next matching is
1012 // after it.
1013 i++;
1014 if (i<N) {
1015 aInfo = resolves.get(i).activityInfo;
1016 }
1017 if (debug) {
1018 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1019 + "/" + r.info.name);
1020 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1021 ? "null" : aInfo.packageName + "/" + aInfo.name));
1022 }
1023 break;
1024 }
1025 }
1026 } catch (RemoteException e) {
1027 }
1028
1029 if (aInfo == null) {
1030 // Nobody who is next!
1031 SafeActivityOptions.abort(options);
1032 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1033 return false;
1034 }
1035
1036 intent.setComponent(new ComponentName(
1037 aInfo.applicationInfo.packageName, aInfo.name));
1038 intent.setFlags(intent.getFlags()&~(
1039 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1040 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1041 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1042 FLAG_ACTIVITY_NEW_TASK));
1043
1044 // Okay now we need to start the new activity, replacing the currently running activity.
1045 // This is a little tricky because we want to start the new one as if the current one is
1046 // finished, but not finish the current one first so that there is no flicker.
1047 // And thus...
1048 final boolean wasFinishing = r.finishing;
1049 r.finishing = true;
1050
1051 // Propagate reply information over to the new activity.
1052 final ActivityRecord resultTo = r.resultTo;
1053 final String resultWho = r.resultWho;
1054 final int requestCode = r.requestCode;
1055 r.resultTo = null;
1056 if (resultTo != null) {
1057 resultTo.removeResultsLocked(r, resultWho, requestCode);
1058 }
1059
1060 final long origId = Binder.clearCallingIdentity();
1061 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001062 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001063 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001064 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001065 .setResolvedType(r.resolvedType)
1066 .setActivityInfo(aInfo)
1067 .setResultTo(resultTo != null ? resultTo.appToken : null)
1068 .setResultWho(resultWho)
1069 .setRequestCode(requestCode)
1070 .setCallingPid(-1)
1071 .setCallingUid(r.launchedFromUid)
1072 .setCallingPackage(r.launchedFromPackage)
1073 .setRealCallingPid(-1)
1074 .setRealCallingUid(r.launchedFromUid)
1075 .setActivityOptions(options)
1076 .execute();
1077 Binder.restoreCallingIdentity(origId);
1078
1079 r.finishing = wasFinishing;
1080 if (res != ActivityManager.START_SUCCESS) {
1081 return false;
1082 }
1083 return true;
1084 }
1085 }
1086
1087 @Override
1088 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1089 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1090 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1091 final WaitResult res = new WaitResult();
1092 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001093 enforceNotIsolatedCaller("startActivityAndWait");
1094 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1095 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001096 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001097 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001098 .setCaller(caller)
1099 .setCallingPackage(callingPackage)
1100 .setResolvedType(resolvedType)
1101 .setResultTo(resultTo)
1102 .setResultWho(resultWho)
1103 .setRequestCode(requestCode)
1104 .setStartFlags(startFlags)
1105 .setActivityOptions(bOptions)
1106 .setMayWait(userId)
1107 .setProfilerInfo(profilerInfo)
1108 .setWaitResult(res)
1109 .execute();
1110 }
1111 return res;
1112 }
1113
1114 @Override
1115 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1116 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1117 int startFlags, Configuration config, Bundle bOptions, int userId) {
1118 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001119 enforceNotIsolatedCaller("startActivityWithConfig");
1120 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1121 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001122 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001123 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001124 .setCaller(caller)
1125 .setCallingPackage(callingPackage)
1126 .setResolvedType(resolvedType)
1127 .setResultTo(resultTo)
1128 .setResultWho(resultWho)
1129 .setRequestCode(requestCode)
1130 .setStartFlags(startFlags)
1131 .setGlobalConfiguration(config)
1132 .setActivityOptions(bOptions)
1133 .setMayWait(userId)
1134 .execute();
1135 }
1136 }
1137
1138 @Override
1139 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1140 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1141 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, boolean ignoreTargetSecurity,
1142 int userId) {
1143
1144 // This is very dangerous -- it allows you to perform a start activity (including
1145 // permission grants) as any app that may launch one of your own activities. So
1146 // we will only allow this to be done from activities that are part of the core framework,
1147 // and then only when they are running as the system.
1148 final ActivityRecord sourceRecord;
1149 final int targetUid;
1150 final String targetPackage;
1151 final boolean isResolver;
1152 synchronized (mGlobalLock) {
1153 if (resultTo == null) {
1154 throw new SecurityException("Must be called from an activity");
1155 }
1156 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo);
1157 if (sourceRecord == null) {
1158 throw new SecurityException("Called with bad activity token: " + resultTo);
1159 }
1160 if (!sourceRecord.info.packageName.equals("android")) {
1161 throw new SecurityException(
1162 "Must be called from an activity that is declared in the android package");
1163 }
1164 if (sourceRecord.app == null) {
1165 throw new SecurityException("Called without a process attached to activity");
1166 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001167 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001168 // This is still okay, as long as this activity is running under the
1169 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001170 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001171 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001172 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001173 + " must be system uid or original calling uid "
1174 + sourceRecord.launchedFromUid);
1175 }
1176 }
1177 if (ignoreTargetSecurity) {
1178 if (intent.getComponent() == null) {
1179 throw new SecurityException(
1180 "Component must be specified with ignoreTargetSecurity");
1181 }
1182 if (intent.getSelector() != null) {
1183 throw new SecurityException(
1184 "Selector not allowed with ignoreTargetSecurity");
1185 }
1186 }
1187 targetUid = sourceRecord.launchedFromUid;
1188 targetPackage = sourceRecord.launchedFromPackage;
1189 isResolver = sourceRecord.isResolverOrChildActivity();
1190 }
1191
1192 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001193 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001194 }
1195
1196 // TODO: Switch to user app stacks here.
1197 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001198 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001199 .setCallingUid(targetUid)
1200 .setCallingPackage(targetPackage)
1201 .setResolvedType(resolvedType)
1202 .setResultTo(resultTo)
1203 .setResultWho(resultWho)
1204 .setRequestCode(requestCode)
1205 .setStartFlags(startFlags)
1206 .setActivityOptions(bOptions)
1207 .setMayWait(userId)
1208 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1209 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1210 .execute();
1211 } catch (SecurityException e) {
1212 // XXX need to figure out how to propagate to original app.
1213 // A SecurityException here is generally actually a fault of the original
1214 // calling activity (such as a fairly granting permissions), so propagate it
1215 // back to them.
1216 /*
1217 StringBuilder msg = new StringBuilder();
1218 msg.append("While launching");
1219 msg.append(intent.toString());
1220 msg.append(": ");
1221 msg.append(e.getMessage());
1222 */
1223 throw e;
1224 }
1225 }
1226
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001227 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1228 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1229 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1230 }
1231
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001232 @Override
1233 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1234 Intent intent, String resolvedType, IVoiceInteractionSession session,
1235 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1236 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001237 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001238 if (session == null || interactor == null) {
1239 throw new NullPointerException("null session or interactor");
1240 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001241 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001242 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001243 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001244 .setCallingUid(callingUid)
1245 .setCallingPackage(callingPackage)
1246 .setResolvedType(resolvedType)
1247 .setVoiceSession(session)
1248 .setVoiceInteractor(interactor)
1249 .setStartFlags(startFlags)
1250 .setProfilerInfo(profilerInfo)
1251 .setActivityOptions(bOptions)
1252 .setMayWait(userId)
1253 .execute();
1254 }
1255
1256 @Override
1257 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1258 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001259 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1260 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001261
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001262 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001263 .setCallingUid(callingUid)
1264 .setCallingPackage(callingPackage)
1265 .setResolvedType(resolvedType)
1266 .setActivityOptions(bOptions)
1267 .setMayWait(userId)
1268 .execute();
1269 }
1270
1271 @Override
1272 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1273 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001274 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001275 final int callingPid = Binder.getCallingPid();
1276 final long origId = Binder.clearCallingIdentity();
1277 try {
1278 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001279 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1280 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001281
1282 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001283 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1284 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001285 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1286 recentsUid, assistDataReceiver);
1287 }
1288 } finally {
1289 Binder.restoreCallingIdentity(origId);
1290 }
1291 }
1292
1293 @Override
1294 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001295 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001296 "startActivityFromRecents()");
1297
1298 final int callingPid = Binder.getCallingPid();
1299 final int callingUid = Binder.getCallingUid();
1300 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1301 final long origId = Binder.clearCallingIdentity();
1302 try {
1303 synchronized (mGlobalLock) {
1304 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1305 safeOptions);
1306 }
1307 } finally {
1308 Binder.restoreCallingIdentity(origId);
1309 }
1310 }
1311
1312 /**
1313 * This is the internal entry point for handling Activity.finish().
1314 *
1315 * @param token The Binder token referencing the Activity we want to finish.
1316 * @param resultCode Result code, if any, from this Activity.
1317 * @param resultData Result data (Intent), if any, from this Activity.
1318 * @param finishTask Whether to finish the task associated with this Activity.
1319 *
1320 * @return Returns true if the activity successfully finished, or false if it is still running.
1321 */
1322 @Override
1323 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1324 int finishTask) {
1325 // Refuse possible leaked file descriptors
1326 if (resultData != null && resultData.hasFileDescriptors()) {
1327 throw new IllegalArgumentException("File descriptors passed in Intent");
1328 }
1329
1330 synchronized (mGlobalLock) {
1331 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1332 if (r == null) {
1333 return true;
1334 }
1335 // Keep track of the root activity of the task before we finish it
1336 TaskRecord tr = r.getTask();
1337 ActivityRecord rootR = tr.getRootActivity();
1338 if (rootR == null) {
1339 Slog.w(TAG, "Finishing task with all activities already finished");
1340 }
1341 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1342 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001343 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001344 return false;
1345 }
1346
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001347 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1348 // We should consolidate.
1349 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001350 // Find the first activity that is not finishing.
1351 ActivityRecord next = r.getStack().topRunningActivityLocked(token, 0);
1352 if (next != null) {
1353 // ask watcher if this is allowed
1354 boolean resumeOK = true;
1355 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001356 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001358 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 Watchdog.getInstance().setActivityController(null);
1360 }
1361
1362 if (!resumeOK) {
1363 Slog.i(TAG, "Not finishing activity because controller resumed");
1364 return false;
1365 }
1366 }
1367 }
1368 final long origId = Binder.clearCallingIdentity();
1369 try {
1370 boolean res;
1371 final boolean finishWithRootActivity =
1372 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1373 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1374 || (finishWithRootActivity && r == rootR)) {
1375 // If requested, remove the task that is associated to this activity only if it
1376 // was the root activity in the task. The result code and data is ignored
1377 // because we don't support returning them across task boundaries. Also, to
1378 // keep backwards compatibility we remove the task from recents when finishing
1379 // task with root activity.
1380 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1381 finishWithRootActivity, "finish-activity");
1382 if (!res) {
1383 Slog.i(TAG, "Removing task failed to finish activity");
1384 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001385 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001386 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001387 } else {
1388 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1389 resultData, "app-request", true);
1390 if (!res) {
1391 Slog.i(TAG, "Failed to finish by app-request");
1392 }
1393 }
1394 return res;
1395 } finally {
1396 Binder.restoreCallingIdentity(origId);
1397 }
1398 }
1399 }
1400
1401 @Override
1402 public boolean finishActivityAffinity(IBinder token) {
1403 synchronized (mGlobalLock) {
1404 final long origId = Binder.clearCallingIdentity();
1405 try {
1406 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1407 if (r == null) {
1408 return false;
1409 }
1410
1411 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1412 // can finish.
1413 final TaskRecord task = r.getTask();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001414 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001415 return false;
1416 }
1417 return task.getStack().finishActivityAffinityLocked(r);
1418 } finally {
1419 Binder.restoreCallingIdentity(origId);
1420 }
1421 }
1422 }
1423
1424 @Override
1425 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1426 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001427 try {
1428 WindowProcessController proc = null;
1429 synchronized (mGlobalLock) {
1430 ActivityStack stack = ActivityRecord.getStackLocked(token);
1431 if (stack == null) {
1432 return;
1433 }
1434 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1435 false /* fromTimeout */, false /* processPausingActivities */, config);
1436 if (r != null) {
1437 proc = r.app;
1438 }
1439 if (stopProfiling && proc != null) {
1440 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001441 }
1442 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001443 } finally {
1444 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001445 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001446 }
1447
1448 @Override
1449 public final void activityResumed(IBinder token) {
1450 final long origId = Binder.clearCallingIdentity();
1451 synchronized (mGlobalLock) {
1452 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001453 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001454 }
1455 Binder.restoreCallingIdentity(origId);
1456 }
1457
1458 @Override
1459 public final void activityPaused(IBinder token) {
1460 final long origId = Binder.clearCallingIdentity();
1461 synchronized (mGlobalLock) {
1462 ActivityStack stack = ActivityRecord.getStackLocked(token);
1463 if (stack != null) {
1464 stack.activityPausedLocked(token, false);
1465 }
1466 }
1467 Binder.restoreCallingIdentity(origId);
1468 }
1469
1470 @Override
1471 public final void activityStopped(IBinder token, Bundle icicle,
1472 PersistableBundle persistentState, CharSequence description) {
1473 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1474
1475 // Refuse possible leaked file descriptors
1476 if (icicle != null && icicle.hasFileDescriptors()) {
1477 throw new IllegalArgumentException("File descriptors passed in Bundle");
1478 }
1479
1480 final long origId = Binder.clearCallingIdentity();
1481
1482 synchronized (mGlobalLock) {
1483 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1484 if (r != null) {
1485 r.activityStoppedLocked(icicle, persistentState, description);
1486 }
1487 }
1488
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001489 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001490
1491 Binder.restoreCallingIdentity(origId);
1492 }
1493
1494 @Override
1495 public final void activityDestroyed(IBinder token) {
1496 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1497 synchronized (mGlobalLock) {
1498 ActivityStack stack = ActivityRecord.getStackLocked(token);
1499 if (stack != null) {
1500 stack.activityDestroyedLocked(token, "activityDestroyed");
1501 }
1502 }
1503 }
1504
1505 @Override
1506 public final void activityRelaunched(IBinder token) {
1507 final long origId = Binder.clearCallingIdentity();
1508 synchronized (mGlobalLock) {
1509 mStackSupervisor.activityRelaunchedLocked(token);
1510 }
1511 Binder.restoreCallingIdentity(origId);
1512 }
1513
1514 public final void activitySlept(IBinder token) {
1515 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1516
1517 final long origId = Binder.clearCallingIdentity();
1518
1519 synchronized (mGlobalLock) {
1520 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1521 if (r != null) {
1522 mStackSupervisor.activitySleptLocked(r);
1523 }
1524 }
1525
1526 Binder.restoreCallingIdentity(origId);
1527 }
1528
1529 @Override
1530 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1531 synchronized (mGlobalLock) {
1532 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1533 if (r == null) {
1534 return;
1535 }
1536 final long origId = Binder.clearCallingIdentity();
1537 try {
1538 r.setRequestedOrientation(requestedOrientation);
1539 } finally {
1540 Binder.restoreCallingIdentity(origId);
1541 }
1542 }
1543 }
1544
1545 @Override
1546 public int getRequestedOrientation(IBinder token) {
1547 synchronized (mGlobalLock) {
1548 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1549 if (r == null) {
1550 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1551 }
1552 return r.getRequestedOrientation();
1553 }
1554 }
1555
1556 @Override
1557 public void setImmersive(IBinder token, boolean immersive) {
1558 synchronized (mGlobalLock) {
1559 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1560 if (r == null) {
1561 throw new IllegalArgumentException();
1562 }
1563 r.immersive = immersive;
1564
1565 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001566 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001567 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001568 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001569 }
1570 }
1571 }
1572
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001573 void applyUpdateLockStateLocked(ActivityRecord r) {
1574 // Modifications to the UpdateLock state are done on our handler, outside
1575 // the activity manager's locks. The new state is determined based on the
1576 // state *now* of the relevant activity record. The object is passed to
1577 // the handler solely for logging detail, not to be consulted/modified.
1578 final boolean nextState = r != null && r.immersive;
1579 mH.post(() -> {
1580 if (mUpdateLock.isHeld() != nextState) {
1581 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1582 "Applying new update lock state '" + nextState + "' for " + r);
1583 if (nextState) {
1584 mUpdateLock.acquire();
1585 } else {
1586 mUpdateLock.release();
1587 }
1588 }
1589 });
1590 }
1591
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 @Override
1593 public boolean isImmersive(IBinder token) {
1594 synchronized (mGlobalLock) {
1595 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1596 if (r == null) {
1597 throw new IllegalArgumentException();
1598 }
1599 return r.immersive;
1600 }
1601 }
1602
1603 @Override
1604 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001605 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001606 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001607 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001608 return (r != null) ? r.immersive : false;
1609 }
1610 }
1611
1612 @Override
1613 public void overridePendingTransition(IBinder token, String packageName,
1614 int enterAnim, int exitAnim) {
1615 synchronized (mGlobalLock) {
1616 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1617 if (self == null) {
1618 return;
1619 }
1620
1621 final long origId = Binder.clearCallingIdentity();
1622
1623 if (self.isState(
1624 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001625 mWindowManager.overridePendingAppTransition(packageName,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001626 enterAnim, exitAnim, null);
1627 }
1628
1629 Binder.restoreCallingIdentity(origId);
1630 }
1631 }
1632
1633 @Override
1634 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001635 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001636 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001637 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001638 if (r == null) {
1639 return ActivityManager.COMPAT_MODE_UNKNOWN;
1640 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001641 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001642 }
1643 }
1644
1645 @Override
1646 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001647 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001648 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001649 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001650 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001651 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001652 if (r == null) {
1653 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1654 return;
1655 }
1656 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001657 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001658 }
1659 }
1660
1661 @Override
1662 public int getLaunchedFromUid(IBinder activityToken) {
1663 ActivityRecord srec;
1664 synchronized (mGlobalLock) {
1665 srec = ActivityRecord.forTokenLocked(activityToken);
1666 }
1667 if (srec == null) {
1668 return -1;
1669 }
1670 return srec.launchedFromUid;
1671 }
1672
1673 @Override
1674 public String getLaunchedFromPackage(IBinder activityToken) {
1675 ActivityRecord srec;
1676 synchronized (mGlobalLock) {
1677 srec = ActivityRecord.forTokenLocked(activityToken);
1678 }
1679 if (srec == null) {
1680 return null;
1681 }
1682 return srec.launchedFromPackage;
1683 }
1684
1685 @Override
1686 public boolean convertFromTranslucent(IBinder token) {
1687 final long origId = Binder.clearCallingIdentity();
1688 try {
1689 synchronized (mGlobalLock) {
1690 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1691 if (r == null) {
1692 return false;
1693 }
1694 final boolean translucentChanged = r.changeWindowTranslucency(true);
1695 if (translucentChanged) {
1696 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
1697 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001698 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001699 return translucentChanged;
1700 }
1701 } finally {
1702 Binder.restoreCallingIdentity(origId);
1703 }
1704 }
1705
1706 @Override
1707 public boolean convertToTranslucent(IBinder token, Bundle options) {
1708 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1709 final long origId = Binder.clearCallingIdentity();
1710 try {
1711 synchronized (mGlobalLock) {
1712 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1713 if (r == null) {
1714 return false;
1715 }
1716 final TaskRecord task = r.getTask();
1717 int index = task.mActivities.lastIndexOf(r);
1718 if (index > 0) {
1719 ActivityRecord under = task.mActivities.get(index - 1);
1720 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1721 }
1722 final boolean translucentChanged = r.changeWindowTranslucency(false);
1723 if (translucentChanged) {
1724 r.getStack().convertActivityToTranslucent(r);
1725 }
1726 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001727 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001728 return translucentChanged;
1729 }
1730 } finally {
1731 Binder.restoreCallingIdentity(origId);
1732 }
1733 }
1734
1735 @Override
1736 public void notifyActivityDrawn(IBinder token) {
1737 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1738 synchronized (mGlobalLock) {
1739 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token);
1740 if (r != null) {
1741 r.getStack().notifyActivityDrawnLocked(r);
1742 }
1743 }
1744 }
1745
1746 @Override
1747 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1748 synchronized (mGlobalLock) {
1749 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1750 if (r == null) {
1751 return;
1752 }
1753 r.reportFullyDrawnLocked(restoredFromBundle);
1754 }
1755 }
1756
1757 @Override
1758 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1759 synchronized (mGlobalLock) {
1760 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1761 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1762 return stack.mDisplayId;
1763 }
1764 return DEFAULT_DISPLAY;
1765 }
1766 }
1767
1768 @Override
1769 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001770 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001771 long ident = Binder.clearCallingIdentity();
1772 try {
1773 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001774 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001775 if (focusedStack != null) {
1776 return mStackSupervisor.getStackInfo(focusedStack.mStackId);
1777 }
1778 return null;
1779 }
1780 } finally {
1781 Binder.restoreCallingIdentity(ident);
1782 }
1783 }
1784
1785 @Override
1786 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001787 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001788 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1789 final long callingId = Binder.clearCallingIdentity();
1790 try {
1791 synchronized (mGlobalLock) {
1792 final ActivityStack stack = mStackSupervisor.getStack(stackId);
1793 if (stack == null) {
1794 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1795 return;
1796 }
1797 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001798 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001799 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001800 }
1801 }
1802 } finally {
1803 Binder.restoreCallingIdentity(callingId);
1804 }
1805 }
1806
1807 @Override
1808 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001809 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001810 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1811 final long callingId = Binder.clearCallingIdentity();
1812 try {
1813 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001814 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1815 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001816 if (task == null) {
1817 return;
1818 }
1819 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001820 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08001821 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001822 }
1823 }
1824 } finally {
1825 Binder.restoreCallingIdentity(callingId);
1826 }
1827 }
1828
1829 @Override
1830 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001831 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001832 synchronized (mGlobalLock) {
1833 final long ident = Binder.clearCallingIdentity();
1834 try {
1835 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1836 "remove-task");
1837 } finally {
1838 Binder.restoreCallingIdentity(ident);
1839 }
1840 }
1841 }
1842
1843 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001844 public void removeAllVisibleRecentTasks() {
1845 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1846 synchronized (mGlobalLock) {
1847 final long ident = Binder.clearCallingIdentity();
1848 try {
1849 getRecentTasks().removeAllVisibleTasks();
1850 } finally {
1851 Binder.restoreCallingIdentity(ident);
1852 }
1853 }
1854 }
1855
1856 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001857 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
1858 synchronized (mGlobalLock) {
1859 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
1860 if (srec != null) {
1861 return srec.getStack().shouldUpRecreateTaskLocked(srec, destAffinity);
1862 }
1863 }
1864 return false;
1865 }
1866
1867 @Override
1868 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
1869 Intent resultData) {
1870
1871 synchronized (mGlobalLock) {
1872 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1873 if (r != null) {
1874 return r.getStack().navigateUpToLocked(r, destIntent, resultCode, resultData);
1875 }
1876 return false;
1877 }
1878 }
1879
1880 /**
1881 * Attempts to move a task backwards in z-order (the order of activities within the task is
1882 * unchanged).
1883 *
1884 * There are several possible results of this call:
1885 * - if the task is locked, then we will show the lock toast
1886 * - if there is a task behind the provided task, then that task is made visible and resumed as
1887 * this task is moved to the back
1888 * - otherwise, if there are no other tasks in the stack:
1889 * - if this task is in the pinned stack, then we remove the stack completely, which will
1890 * have the effect of moving the task to the top or bottom of the fullscreen stack
1891 * (depending on whether it is visible)
1892 * - otherwise, we simply return home and hide this task
1893 *
1894 * @param token A reference to the activity we wish to move
1895 * @param nonRoot If false then this only works if the activity is the root
1896 * of a task; if true it will work for any activity in a task.
1897 * @return Returns true if the move completed, false if not.
1898 */
1899 @Override
1900 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001901 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001902 synchronized (mGlobalLock) {
1903 final long origId = Binder.clearCallingIdentity();
1904 try {
1905 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
1906 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
1907 if (task != null) {
1908 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
1909 }
1910 } finally {
1911 Binder.restoreCallingIdentity(origId);
1912 }
1913 }
1914 return false;
1915 }
1916
1917 @Override
1918 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001919 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001920 long ident = Binder.clearCallingIdentity();
1921 Rect rect = new Rect();
1922 try {
1923 synchronized (mGlobalLock) {
1924 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1925 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1926 if (task == null) {
1927 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
1928 return rect;
1929 }
1930 if (task.getStack() != null) {
1931 // Return the bounds from window manager since it will be adjusted for various
1932 // things like the presense of a docked stack for tasks that aren't resizeable.
1933 task.getWindowContainerBounds(rect);
1934 } else {
1935 // Task isn't in window manager yet since it isn't associated with a stack.
1936 // Return the persist value from activity manager
1937 if (!task.matchParentBounds()) {
1938 rect.set(task.getBounds());
1939 } else if (task.mLastNonFullscreenBounds != null) {
1940 rect.set(task.mLastNonFullscreenBounds);
1941 }
1942 }
1943 }
1944 } finally {
1945 Binder.restoreCallingIdentity(ident);
1946 }
1947 return rect;
1948 }
1949
1950 @Override
1951 public ActivityManager.TaskDescription getTaskDescription(int id) {
1952 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001953 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001954 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
1955 final TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id,
1956 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
1957 if (tr != null) {
1958 return tr.lastTaskDescription;
1959 }
1960 }
1961 return null;
1962 }
1963
1964 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001965 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
1966 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
1967 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
1968 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
1969 return;
1970 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001971 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001972 synchronized (mGlobalLock) {
1973 final long ident = Binder.clearCallingIdentity();
1974 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001975 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
1976 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001977 if (task == null) {
1978 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
1979 return;
1980 }
1981
1982 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
1983 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
1984
1985 if (!task.isActivityTypeStandardOrUndefined()) {
1986 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
1987 + " non-standard task " + taskId + " to windowing mode="
1988 + windowingMode);
1989 }
1990
1991 final ActivityStack stack = task.getStack();
1992 if (toTop) {
1993 stack.moveToFront("setTaskWindowingMode", task);
1994 }
1995 stack.setWindowingMode(windowingMode);
1996 } finally {
1997 Binder.restoreCallingIdentity(ident);
1998 }
1999 }
2000 }
2001
2002 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002003 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002004 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002005 ActivityRecord r = getCallingRecordLocked(token);
2006 return r != null ? r.info.packageName : null;
2007 }
2008 }
2009
2010 @Override
2011 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002012 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 ActivityRecord r = getCallingRecordLocked(token);
2014 return r != null ? r.intent.getComponent() : null;
2015 }
2016 }
2017
2018 private ActivityRecord getCallingRecordLocked(IBinder token) {
2019 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2020 if (r == null) {
2021 return null;
2022 }
2023 return r.resultTo;
2024 }
2025
2026 @Override
2027 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002028 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002029
2030 synchronized (mGlobalLock) {
2031 final long origId = Binder.clearCallingIdentity();
2032 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002033 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002034 } finally {
2035 Binder.restoreCallingIdentity(origId);
2036 }
2037 }
2038 }
2039
2040 /**
2041 * TODO: Add mController hook
2042 */
2043 @Override
2044 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002045 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002046
2047 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2048 synchronized (mGlobalLock) {
2049 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2050 false /* fromRecents */);
2051 }
2052 }
2053
2054 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2055 boolean fromRecents) {
2056
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002057 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002058 Binder.getCallingUid(), -1, -1, "Task to front")) {
2059 SafeActivityOptions.abort(options);
2060 return;
2061 }
2062 final long origId = Binder.clearCallingIdentity();
2063 try {
2064 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2065 if (task == null) {
2066 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002067 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002068 return;
2069 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002070 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002071 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002072 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002073 return;
2074 }
2075 ActivityOptions realOptions = options != null
2076 ? options.getOptions(mStackSupervisor)
2077 : null;
2078 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2079 false /* forceNonResizable */);
2080
2081 final ActivityRecord topActivity = task.getTopActivity();
2082 if (topActivity != null) {
2083
2084 // We are reshowing a task, use a starting window to hide the initial draw delay
2085 // so the transition can start earlier.
2086 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2087 true /* taskSwitch */, fromRecents);
2088 }
2089 } finally {
2090 Binder.restoreCallingIdentity(origId);
2091 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002092 }
2093
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002094 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2095 int callingPid, int callingUid, String name) {
2096 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2097 return true;
2098 }
2099
2100 if (getRecentTasks().isCallerRecents(sourceUid)) {
2101 return true;
2102 }
2103
2104 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2105 if (perm == PackageManager.PERMISSION_GRANTED) {
2106 return true;
2107 }
2108 if (checkAllowAppSwitchUid(sourceUid)) {
2109 return true;
2110 }
2111
2112 // If the actual IPC caller is different from the logical source, then
2113 // also see if they are allowed to control app switches.
2114 if (callingUid != -1 && callingUid != sourceUid) {
2115 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2116 if (perm == PackageManager.PERMISSION_GRANTED) {
2117 return true;
2118 }
2119 if (checkAllowAppSwitchUid(callingUid)) {
2120 return true;
2121 }
2122 }
2123
2124 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2125 return false;
2126 }
2127
2128 private boolean checkAllowAppSwitchUid(int uid) {
2129 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2130 if (types != null) {
2131 for (int i = types.size() - 1; i >= 0; i--) {
2132 if (types.valueAt(i).intValue() == uid) {
2133 return true;
2134 }
2135 }
2136 }
2137 return false;
2138 }
2139
2140 @Override
2141 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2142 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2143 "setActivityController()");
2144 synchronized (mGlobalLock) {
2145 mController = controller;
2146 mControllerIsAMonkey = imAMonkey;
2147 Watchdog.getInstance().setActivityController(controller);
2148 }
2149 }
2150
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002151 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002152 synchronized (mGlobalLock) {
2153 return mController != null && mControllerIsAMonkey;
2154 }
2155 }
2156
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002157 @Override
2158 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2159 synchronized (mGlobalLock) {
2160 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2161 }
2162 }
2163
2164 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002165 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2166 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2167 }
2168
2169 @Override
2170 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2171 @WindowConfiguration.ActivityType int ignoreActivityType,
2172 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2173 final int callingUid = Binder.getCallingUid();
2174 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2175
2176 synchronized (mGlobalLock) {
2177 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2178
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002179 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002180 callingUid);
2181 mStackSupervisor.getRunningTasks(maxNum, list, ignoreActivityType,
2182 ignoreWindowingMode, callingUid, allowed);
2183 }
2184
2185 return list;
2186 }
2187
2188 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002189 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2190 synchronized (mGlobalLock) {
2191 final long origId = Binder.clearCallingIdentity();
2192 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2193 if (r != null) {
2194 r.getStack().finishSubActivityLocked(r, resultWho, requestCode);
2195 }
2196 Binder.restoreCallingIdentity(origId);
2197 }
2198 }
2199
2200 @Override
2201 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002202 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002203 ActivityStack stack = ActivityRecord.getStackLocked(token);
2204 if (stack != null) {
2205 return stack.willActivityBeVisibleLocked(token);
2206 }
2207 return false;
2208 }
2209 }
2210
2211 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002212 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002213 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002214 synchronized (mGlobalLock) {
2215 final long ident = Binder.clearCallingIdentity();
2216 try {
2217 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
2218 if (task == null) {
2219 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2220 return;
2221 }
2222
2223 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2224 + " to stackId=" + stackId + " toTop=" + toTop);
2225
2226 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2227 if (stack == null) {
2228 throw new IllegalStateException(
2229 "moveTaskToStack: No stack for stackId=" + stackId);
2230 }
2231 if (!stack.isActivityTypeStandardOrUndefined()) {
2232 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2233 + taskId + " to stack " + stackId);
2234 }
2235 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002236 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002237 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2238 }
2239 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2240 "moveTaskToStack");
2241 } finally {
2242 Binder.restoreCallingIdentity(ident);
2243 }
2244 }
2245 }
2246
2247 @Override
2248 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2249 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002250 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002251
2252 final long ident = Binder.clearCallingIdentity();
2253 try {
2254 synchronized (mGlobalLock) {
2255 if (animate) {
2256 final PinnedActivityStack stack = mStackSupervisor.getStack(stackId);
2257 if (stack == null) {
2258 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2259 return;
2260 }
2261 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2262 throw new IllegalArgumentException("Stack: " + stackId
2263 + " doesn't support animated resize.");
2264 }
2265 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2266 animationDuration, false /* fromFullscreen */);
2267 } else {
2268 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2269 if (stack == null) {
2270 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2271 return;
2272 }
2273 mStackSupervisor.resizeStackLocked(stack, destBounds,
2274 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2275 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2276 }
2277 }
2278 } finally {
2279 Binder.restoreCallingIdentity(ident);
2280 }
2281 }
2282
2283 /**
2284 * Moves the specified task to the primary-split-screen stack.
2285 *
2286 * @param taskId Id of task to move.
2287 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2288 * exist already. See
2289 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2290 * and
2291 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2292 * @param toTop If the task and stack should be moved to the top.
2293 * @param animate Whether we should play an animation for the moving the task.
2294 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2295 * stack. Pass {@code null} to use default bounds.
2296 * @param showRecents If the recents activity should be shown on the other side of the task
2297 * going into split-screen mode.
2298 */
2299 @Override
2300 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2301 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002302 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002303 "setTaskWindowingModeSplitScreenPrimary()");
2304 synchronized (mGlobalLock) {
2305 final long ident = Binder.clearCallingIdentity();
2306 try {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002307 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2308 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002309 if (task == null) {
2310 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2311 return false;
2312 }
2313 if (DEBUG_STACK) Slog.d(TAG_STACK,
2314 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2315 + " to createMode=" + createMode + " toTop=" + toTop);
2316 if (!task.isActivityTypeStandardOrUndefined()) {
2317 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2318 + " non-standard task " + taskId + " to split-screen windowing mode");
2319 }
2320
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002321 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002322 final int windowingMode = task.getWindowingMode();
2323 final ActivityStack stack = task.getStack();
2324 if (toTop) {
2325 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2326 }
2327 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
2328 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */);
2329 return windowingMode != task.getWindowingMode();
2330 } finally {
2331 Binder.restoreCallingIdentity(ident);
2332 }
2333 }
2334 }
2335
2336 /**
2337 * Removes stacks in the input windowing modes from the system if they are of activity type
2338 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2339 */
2340 @Override
2341 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002342 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002343 "removeStacksInWindowingModes()");
2344
2345 synchronized (mGlobalLock) {
2346 final long ident = Binder.clearCallingIdentity();
2347 try {
2348 mStackSupervisor.removeStacksInWindowingModes(windowingModes);
2349 } finally {
2350 Binder.restoreCallingIdentity(ident);
2351 }
2352 }
2353 }
2354
2355 @Override
2356 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002357 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002358 "removeStacksWithActivityTypes()");
2359
2360 synchronized (mGlobalLock) {
2361 final long ident = Binder.clearCallingIdentity();
2362 try {
2363 mStackSupervisor.removeStacksWithActivityTypes(activityTypes);
2364 } finally {
2365 Binder.restoreCallingIdentity(ident);
2366 }
2367 }
2368 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002369
2370 @Override
2371 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2372 int userId) {
2373 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002374 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2375 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002376 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002377 final boolean detailed = checkGetTasksPermission(
2378 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2379 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002380 == PackageManager.PERMISSION_GRANTED;
2381
2382 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002383 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002384 callingUid);
2385 }
2386 }
2387
2388 @Override
2389 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002390 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002391 long ident = Binder.clearCallingIdentity();
2392 try {
2393 synchronized (mGlobalLock) {
2394 return mStackSupervisor.getAllStackInfosLocked();
2395 }
2396 } finally {
2397 Binder.restoreCallingIdentity(ident);
2398 }
2399 }
2400
2401 @Override
2402 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002403 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002404 long ident = Binder.clearCallingIdentity();
2405 try {
2406 synchronized (mGlobalLock) {
2407 return mStackSupervisor.getStackInfo(windowingMode, activityType);
2408 }
2409 } finally {
2410 Binder.restoreCallingIdentity(ident);
2411 }
2412 }
2413
2414 @Override
2415 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002416 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002417 final long callingUid = Binder.getCallingUid();
2418 final long origId = Binder.clearCallingIdentity();
2419 try {
2420 synchronized (mGlobalLock) {
2421 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002422 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002423 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2424 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2425 }
2426 } finally {
2427 Binder.restoreCallingIdentity(origId);
2428 }
2429 }
2430
2431 @Override
2432 public void startLockTaskModeByToken(IBinder token) {
2433 synchronized (mGlobalLock) {
2434 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2435 if (r == null) {
2436 return;
2437 }
2438 startLockTaskModeLocked(r.getTask(), false /* isSystemCaller */);
2439 }
2440 }
2441
2442 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002443 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002444 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002445 // This makes inner call to look as if it was initiated by system.
2446 long ident = Binder.clearCallingIdentity();
2447 try {
2448 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002449 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2450 MATCH_TASK_IN_STACKS_ONLY);
2451 if (task == null) {
2452 return;
2453 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002454
2455 // When starting lock task mode the stack must be in front and focused
2456 task.getStack().moveToFront("startSystemLockTaskMode");
2457 startLockTaskModeLocked(task, true /* isSystemCaller */);
2458 }
2459 } finally {
2460 Binder.restoreCallingIdentity(ident);
2461 }
2462 }
2463
2464 @Override
2465 public void stopLockTaskModeByToken(IBinder token) {
2466 synchronized (mGlobalLock) {
2467 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2468 if (r == null) {
2469 return;
2470 }
2471 stopLockTaskModeInternal(r.getTask(), false /* isSystemCaller */);
2472 }
2473 }
2474
2475 /**
2476 * This API should be called by SystemUI only when user perform certain action to dismiss
2477 * lock task mode. We should only dismiss pinned lock task mode in this case.
2478 */
2479 @Override
2480 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002481 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002482 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2483 }
2484
2485 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2486 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2487 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2488 return;
2489 }
2490
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002491 final ActivityStack stack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002492 if (stack == null || task != stack.topTask()) {
2493 throw new IllegalArgumentException("Invalid task, not in foreground");
2494 }
2495
2496 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2497 // system or a specific app.
2498 // * System-initiated requests will only start the pinned mode (screen pinning)
2499 // * App-initiated requests
2500 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2501 // - will start the pinned mode, otherwise
2502 final int callingUid = Binder.getCallingUid();
2503 long ident = Binder.clearCallingIdentity();
2504 try {
2505 // When a task is locked, dismiss the pinned stack if it exists
2506 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
2507
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002508 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002509 } finally {
2510 Binder.restoreCallingIdentity(ident);
2511 }
2512 }
2513
2514 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2515 final int callingUid = Binder.getCallingUid();
2516 long ident = Binder.clearCallingIdentity();
2517 try {
2518 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002519 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002520 }
2521 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2522 // task and jumping straight into a call in the case of emergency call back.
2523 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2524 if (tm != null) {
2525 tm.showInCallScreen(false);
2526 }
2527 } finally {
2528 Binder.restoreCallingIdentity(ident);
2529 }
2530 }
2531
2532 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002533 public void updateLockTaskPackages(int userId, String[] packages) {
2534 final int callingUid = Binder.getCallingUid();
2535 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2536 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2537 "updateLockTaskPackages()");
2538 }
2539 synchronized (this) {
2540 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2541 + Arrays.toString(packages));
2542 getLockTaskController().updateLockTaskPackages(userId, packages);
2543 }
2544 }
2545
2546 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002547 public boolean isInLockTaskMode() {
2548 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2549 }
2550
2551 @Override
2552 public int getLockTaskModeState() {
2553 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002554 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002555 }
2556 }
2557
2558 @Override
2559 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2560 synchronized (mGlobalLock) {
2561 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2562 if (r != null) {
2563 r.setTaskDescription(td);
2564 final TaskRecord task = r.getTask();
2565 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002566 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002567 }
2568 }
2569 }
2570
2571 @Override
2572 public Bundle getActivityOptions(IBinder token) {
2573 final long origId = Binder.clearCallingIdentity();
2574 try {
2575 synchronized (mGlobalLock) {
2576 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2577 if (r != null) {
2578 final ActivityOptions activityOptions = r.takeOptionsLocked();
2579 return activityOptions == null ? null : activityOptions.toBundle();
2580 }
2581 return null;
2582 }
2583 } finally {
2584 Binder.restoreCallingIdentity(origId);
2585 }
2586 }
2587
2588 @Override
2589 public List<IBinder> getAppTasks(String callingPackage) {
2590 int callingUid = Binder.getCallingUid();
2591 long ident = Binder.clearCallingIdentity();
2592 try {
2593 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002594 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002595 }
2596 } finally {
2597 Binder.restoreCallingIdentity(ident);
2598 }
2599 }
2600
2601 @Override
2602 public void finishVoiceTask(IVoiceInteractionSession session) {
2603 synchronized (mGlobalLock) {
2604 final long origId = Binder.clearCallingIdentity();
2605 try {
2606 // TODO: VI Consider treating local voice interactions and voice tasks
2607 // differently here
2608 mStackSupervisor.finishVoiceTask(session);
2609 } finally {
2610 Binder.restoreCallingIdentity(origId);
2611 }
2612 }
2613
2614 }
2615
2616 @Override
2617 public boolean isTopOfTask(IBinder token) {
2618 synchronized (mGlobalLock) {
2619 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Riddle Hsu66b74a82018-07-26 00:20:12 +08002620 return r != null && r.getTask().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002621 }
2622 }
2623
2624 @Override
2625 public void notifyLaunchTaskBehindComplete(IBinder token) {
2626 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2627 }
2628
2629 @Override
2630 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002631 mH.post(() -> {
2632 synchronized (mGlobalLock) {
2633 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002634 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002635 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002636 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002637 } catch (RemoteException e) {
2638 }
2639 }
2640 }
2641
2642 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002643 }
2644
2645 /** Called from an app when assist data is ready. */
2646 @Override
2647 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2648 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002649 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002650 synchronized (pae) {
2651 pae.result = extras;
2652 pae.structure = structure;
2653 pae.content = content;
2654 if (referrer != null) {
2655 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2656 }
2657 if (structure != null) {
2658 structure.setHomeActivity(pae.isHome);
2659 }
2660 pae.haveResult = true;
2661 pae.notifyAll();
2662 if (pae.intent == null && pae.receiver == null) {
2663 // Caller is just waiting for the result.
2664 return;
2665 }
2666 }
2667 // We are now ready to launch the assist activity.
2668 IAssistDataReceiver sendReceiver = null;
2669 Bundle sendBundle = null;
2670 synchronized (mGlobalLock) {
2671 buildAssistBundleLocked(pae, extras);
2672 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002673 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002674 if (!exists) {
2675 // Timed out.
2676 return;
2677 }
2678
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002679 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002680 // Caller wants result sent back to them.
2681 sendBundle = new Bundle();
2682 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2683 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2684 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2685 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2686 }
2687 }
2688 if (sendReceiver != null) {
2689 try {
2690 sendReceiver.onHandleAssistData(sendBundle);
2691 } catch (RemoteException e) {
2692 }
2693 return;
2694 }
2695
2696 final long ident = Binder.clearCallingIdentity();
2697 try {
2698 if (TextUtils.equals(pae.intent.getAction(),
2699 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2700 pae.intent.putExtras(pae.extras);
2701 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2702 } else {
2703 pae.intent.replaceExtras(pae.extras);
2704 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2705 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2706 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002707 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002708
2709 try {
2710 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2711 } catch (ActivityNotFoundException e) {
2712 Slog.w(TAG, "No activity to handle assist action.", e);
2713 }
2714 }
2715 } finally {
2716 Binder.restoreCallingIdentity(ident);
2717 }
2718 }
2719
2720 @Override
2721 public int addAppTask(IBinder activityToken, Intent intent,
2722 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2723 final int callingUid = Binder.getCallingUid();
2724 final long callingIdent = Binder.clearCallingIdentity();
2725
2726 try {
2727 synchronized (mGlobalLock) {
2728 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2729 if (r == null) {
2730 throw new IllegalArgumentException("Activity does not exist; token="
2731 + activityToken);
2732 }
2733 ComponentName comp = intent.getComponent();
2734 if (comp == null) {
2735 throw new IllegalArgumentException("Intent " + intent
2736 + " must specify explicit component");
2737 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002738 if (thumbnail.getWidth() != mThumbnailWidth
2739 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002740 throw new IllegalArgumentException("Bad thumbnail size: got "
2741 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002742 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002743 }
2744 if (intent.getSelector() != null) {
2745 intent.setSelector(null);
2746 }
2747 if (intent.getSourceBounds() != null) {
2748 intent.setSourceBounds(null);
2749 }
2750 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2751 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2752 // The caller has added this as an auto-remove task... that makes no
2753 // sense, so turn off auto-remove.
2754 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2755 }
2756 }
2757 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2758 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2759 if (ainfo.applicationInfo.uid != callingUid) {
2760 throw new SecurityException(
2761 "Can't add task for another application: target uid="
2762 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2763 }
2764
2765 final ActivityStack stack = r.getStack();
2766 final TaskRecord task = stack.createTaskRecord(
2767 mStackSupervisor.getNextTaskIdForUserLocked(r.userId), ainfo, intent,
2768 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002769 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002770 // The app has too many tasks already and we can't add any more
2771 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2772 return INVALID_TASK_ID;
2773 }
2774 task.lastTaskDescription.copyFrom(description);
2775
2776 // TODO: Send the thumbnail to WM to store it.
2777
2778 return task.taskId;
2779 }
2780 } finally {
2781 Binder.restoreCallingIdentity(callingIdent);
2782 }
2783 }
2784
2785 @Override
2786 public Point getAppTaskThumbnailSize() {
2787 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002788 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002789 }
2790 }
2791
2792 @Override
2793 public void setTaskResizeable(int taskId, int resizeableMode) {
2794 synchronized (mGlobalLock) {
2795 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(
2796 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2797 if (task == null) {
2798 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2799 return;
2800 }
2801 task.setResizeMode(resizeableMode);
2802 }
2803 }
2804
2805 @Override
2806 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002807 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002808 long ident = Binder.clearCallingIdentity();
2809 try {
2810 synchronized (mGlobalLock) {
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002811 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
2812 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002813 if (task == null) {
2814 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2815 return;
2816 }
2817 // Place the task in the right stack if it isn't there already based on
2818 // the requested bounds.
2819 // The stack transition logic is:
2820 // - a null bounds on a freeform task moves that task to fullscreen
2821 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2822 // that task to freeform
2823 // - otherwise the task is not moved
2824 ActivityStack stack = task.getStack();
2825 if (!task.getWindowConfiguration().canResizeTask()) {
2826 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2827 }
2828 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2829 stack = stack.getDisplay().getOrCreateStack(
2830 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2831 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2832 stack = stack.getDisplay().getOrCreateStack(
2833 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2834 }
2835
2836 // Reparent the task to the right stack if necessary
2837 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2838 if (stack != task.getStack()) {
2839 // Defer resume until the task is resized below
2840 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2841 DEFER_RESUME, "resizeTask");
2842 preserveWindow = false;
2843 }
2844
2845 // After reparenting (which only resizes the task to the stack bounds), resize the
2846 // task to the actual bounds provided
2847 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
2848 }
2849 } finally {
2850 Binder.restoreCallingIdentity(ident);
2851 }
2852 }
2853
2854 @Override
2855 public boolean releaseActivityInstance(IBinder token) {
2856 synchronized (mGlobalLock) {
2857 final long origId = Binder.clearCallingIdentity();
2858 try {
2859 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2860 if (r == null) {
2861 return false;
2862 }
2863 return r.getStack().safelyDestroyActivityLocked(r, "app-req");
2864 } finally {
2865 Binder.restoreCallingIdentity(origId);
2866 }
2867 }
2868 }
2869
2870 @Override
2871 public void releaseSomeActivities(IApplicationThread appInt) {
2872 synchronized (mGlobalLock) {
2873 final long origId = Binder.clearCallingIdentity();
2874 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002875 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002876 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem");
2877 } finally {
2878 Binder.restoreCallingIdentity(origId);
2879 }
2880 }
2881 }
2882
2883 @Override
2884 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
2885 int secondaryDisplayShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002886 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002887 != PackageManager.PERMISSION_GRANTED) {
2888 throw new SecurityException("Requires permission "
2889 + android.Manifest.permission.DEVICE_POWER);
2890 }
2891
2892 synchronized (mGlobalLock) {
2893 long ident = Binder.clearCallingIdentity();
2894 if (mKeyguardShown != keyguardShowing) {
2895 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07002896 final Message msg = PooledLambda.obtainMessage(
2897 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
2898 keyguardShowing);
2899 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002900 }
2901 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002902 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002903 secondaryDisplayShowing);
2904 } finally {
2905 Binder.restoreCallingIdentity(ident);
2906 }
2907 }
2908
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002909 mH.post(() -> {
2910 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2911 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
2912 }
2913 });
2914 }
2915
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002916 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002917 mH.post(() -> {
2918 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
2919 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
2920 }
2921 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 }
2923
2924 @Override
2925 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002926 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
2927 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002928
2929 final File passedIconFile = new File(filePath);
2930 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
2931 passedIconFile.getName());
2932 if (!legitIconFile.getPath().equals(filePath)
2933 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
2934 throw new IllegalArgumentException("Bad file path: " + filePath
2935 + " passed for userId " + userId);
2936 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002937 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002938 }
2939
2940 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002941 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002942 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
2943 final ActivityOptions activityOptions = safeOptions != null
2944 ? safeOptions.getOptions(mStackSupervisor)
2945 : null;
2946 if (activityOptions == null
2947 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
2948 || activityOptions.getCustomInPlaceResId() == 0) {
2949 throw new IllegalArgumentException("Expected in-place ActivityOption " +
2950 "with valid animation");
2951 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002952 mWindowManager.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
2953 mWindowManager.overridePendingAppTransitionInPlace(activityOptions.getPackageName(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002954 activityOptions.getCustomInPlaceResId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002955 mWindowManager.executeAppTransition();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002956 }
2957
2958 @Override
2959 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002960 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002961 synchronized (mGlobalLock) {
2962 final long ident = Binder.clearCallingIdentity();
2963 try {
2964 final ActivityStack stack = mStackSupervisor.getStack(stackId);
2965 if (stack == null) {
2966 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
2967 return;
2968 }
2969 if (!stack.isActivityTypeStandardOrUndefined()) {
2970 throw new IllegalArgumentException(
2971 "Removing non-standard stack is not allowed.");
2972 }
2973 mStackSupervisor.removeStack(stack);
2974 } finally {
2975 Binder.restoreCallingIdentity(ident);
2976 }
2977 }
2978 }
2979
2980 @Override
2981 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002982 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002983
2984 synchronized (mGlobalLock) {
2985 final long ident = Binder.clearCallingIdentity();
2986 try {
2987 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
2988 + " to displayId=" + displayId);
2989 mStackSupervisor.moveStackToDisplayLocked(stackId, displayId, ON_TOP);
2990 } finally {
2991 Binder.restoreCallingIdentity(ident);
2992 }
2993 }
2994 }
2995
2996 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002997 public void exitFreeformMode(IBinder token) {
2998 synchronized (mGlobalLock) {
2999 long ident = Binder.clearCallingIdentity();
3000 try {
3001 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3002 if (r == null) {
3003 throw new IllegalArgumentException(
3004 "exitFreeformMode: No activity record matching token=" + token);
3005 }
3006
3007 final ActivityStack stack = r.getStack();
3008 if (stack == null || !stack.inFreeformWindowingMode()) {
3009 throw new IllegalStateException(
3010 "exitFreeformMode: You can only go fullscreen from freeform.");
3011 }
3012
3013 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3014 } finally {
3015 Binder.restoreCallingIdentity(ident);
3016 }
3017 }
3018 }
3019
3020 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3021 @Override
3022 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003023 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003024 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003025 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003026 }
3027
3028 /** Unregister a task stack listener so that it stops receiving callbacks. */
3029 @Override
3030 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003031 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003032 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003033 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003034 }
3035
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003036 @Override
3037 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3038 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3039 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3040 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3041 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3042 }
3043
3044 @Override
3045 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3046 IBinder activityToken, int flags) {
3047 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3048 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3049 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3050 }
3051
3052 @Override
3053 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3054 Bundle args) {
3055 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3056 true /* focused */, true /* newSessionId */, userHandle, args,
3057 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3058 }
3059
3060 @Override
3061 public Bundle getAssistContextExtras(int requestType) {
3062 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3063 null, null, true /* focused */, true /* newSessionId */,
3064 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3065 if (pae == null) {
3066 return null;
3067 }
3068 synchronized (pae) {
3069 while (!pae.haveResult) {
3070 try {
3071 pae.wait();
3072 } catch (InterruptedException e) {
3073 }
3074 }
3075 }
3076 synchronized (mGlobalLock) {
3077 buildAssistBundleLocked(pae, pae.result);
3078 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003079 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003080 }
3081 return pae.extras;
3082 }
3083
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003084 /**
3085 * Binder IPC calls go through the public entry point.
3086 * This can be called with or without the global lock held.
3087 */
3088 private static int checkCallingPermission(String permission) {
3089 return checkPermission(
3090 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3091 }
3092
3093 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003094 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003095 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3096 mAmInternal.enforceCallingPermission(permission, func);
3097 }
3098 }
3099
3100 @VisibleForTesting
3101 int checkGetTasksPermission(String permission, int pid, int uid) {
3102 return checkPermission(permission, pid, uid);
3103 }
3104
3105 static int checkPermission(String permission, int pid, int uid) {
3106 if (permission == null) {
3107 return PackageManager.PERMISSION_DENIED;
3108 }
3109 return checkComponentPermission(permission, pid, uid, -1, true);
3110 }
3111
Wale Ogunwale214f3482018-10-04 11:00:47 -07003112 public static int checkComponentPermission(String permission, int pid, int uid,
3113 int owningUid, boolean exported) {
3114 return ActivityManagerService.checkComponentPermission(
3115 permission, pid, uid, owningUid, exported);
3116 }
3117
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003118 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3119 if (getRecentTasks().isCallerRecents(callingUid)) {
3120 // Always allow the recents component to get tasks
3121 return true;
3122 }
3123
3124 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3125 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3126 if (!allowed) {
3127 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3128 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3129 // Temporary compatibility: some existing apps on the system image may
3130 // still be requesting the old permission and not switched to the new
3131 // one; if so, we'll still allow them full access. This means we need
3132 // to see if they are holding the old permission and are a system app.
3133 try {
3134 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3135 allowed = true;
3136 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3137 + " is using old GET_TASKS but privileged; allowing");
3138 }
3139 } catch (RemoteException e) {
3140 }
3141 }
3142 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3143 + " does not hold REAL_GET_TASKS; limiting output");
3144 }
3145 return allowed;
3146 }
3147
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003148 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3149 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3150 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3151 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003152 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003153 "enqueueAssistContext()");
3154
3155 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003156 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003157 if (activity == null) {
3158 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3159 return null;
3160 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003161 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003162 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3163 return null;
3164 }
3165 if (focused) {
3166 if (activityToken != null) {
3167 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3168 if (activity != caller) {
3169 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3170 + " is not current top " + activity);
3171 return null;
3172 }
3173 }
3174 } else {
3175 activity = ActivityRecord.forTokenLocked(activityToken);
3176 if (activity == null) {
3177 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3178 + " couldn't be found");
3179 return null;
3180 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003181 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003182 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3183 return null;
3184 }
3185 }
3186
3187 PendingAssistExtras pae;
3188 Bundle extras = new Bundle();
3189 if (args != null) {
3190 extras.putAll(args);
3191 }
3192 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003193 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003194
3195 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3196 userHandle);
3197 pae.isHome = activity.isActivityTypeHome();
3198
3199 // Increment the sessionId if necessary
3200 if (newSessionId) {
3201 mViSessionId++;
3202 }
3203 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003204 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3205 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003206 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003207 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003208 } catch (RemoteException e) {
3209 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3210 return null;
3211 }
3212 return pae;
3213 }
3214 }
3215
3216 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3217 if (result != null) {
3218 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3219 }
3220 if (pae.hint != null) {
3221 pae.extras.putBoolean(pae.hint, true);
3222 }
3223 }
3224
3225 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3226 IAssistDataReceiver receiver;
3227 synchronized (mGlobalLock) {
3228 mPendingAssistExtras.remove(pae);
3229 receiver = pae.receiver;
3230 }
3231 if (receiver != null) {
3232 // Caller wants result sent back to them.
3233 Bundle sendBundle = new Bundle();
3234 // At least return the receiver extras
3235 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3236 try {
3237 pae.receiver.onHandleAssistData(sendBundle);
3238 } catch (RemoteException e) {
3239 }
3240 }
3241 }
3242
3243 public class PendingAssistExtras extends Binder implements Runnable {
3244 public final ActivityRecord activity;
3245 public boolean isHome;
3246 public final Bundle extras;
3247 public final Intent intent;
3248 public final String hint;
3249 public final IAssistDataReceiver receiver;
3250 public final int userHandle;
3251 public boolean haveResult = false;
3252 public Bundle result = null;
3253 public AssistStructure structure = null;
3254 public AssistContent content = null;
3255 public Bundle receiverExtras;
3256
3257 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3258 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3259 int _userHandle) {
3260 activity = _activity;
3261 extras = _extras;
3262 intent = _intent;
3263 hint = _hint;
3264 receiver = _receiver;
3265 receiverExtras = _receiverExtras;
3266 userHandle = _userHandle;
3267 }
3268
3269 @Override
3270 public void run() {
3271 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3272 synchronized (this) {
3273 haveResult = true;
3274 notifyAll();
3275 }
3276 pendingAssistExtrasTimedOut(this);
3277 }
3278 }
3279
3280 @Override
3281 public boolean isAssistDataAllowedOnCurrentActivity() {
3282 int userId;
3283 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003284 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003285 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3286 return false;
3287 }
3288
3289 final ActivityRecord activity = focusedStack.getTopActivity();
3290 if (activity == null) {
3291 return false;
3292 }
3293 userId = activity.userId;
3294 }
3295 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3296 }
3297
3298 @Override
3299 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3300 long ident = Binder.clearCallingIdentity();
3301 try {
3302 synchronized (mGlobalLock) {
3303 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003304 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003305 if (top != caller) {
3306 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3307 + " is not current top " + top);
3308 return false;
3309 }
3310 if (!top.nowVisible) {
3311 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3312 + " is not visible");
3313 return false;
3314 }
3315 }
3316 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3317 token);
3318 } finally {
3319 Binder.restoreCallingIdentity(ident);
3320 }
3321 }
3322
3323 @Override
3324 public boolean isRootVoiceInteraction(IBinder token) {
3325 synchronized (mGlobalLock) {
3326 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3327 if (r == null) {
3328 return false;
3329 }
3330 return r.rootVoiceInteraction;
3331 }
3332 }
3333
Wale Ogunwalef6733932018-06-27 05:14:34 -07003334 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3335 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3336 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3337 if (activityToCallback == null) return;
3338 activityToCallback.setVoiceSessionLocked(voiceSession);
3339
3340 // Inform the activity
3341 try {
3342 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3343 voiceInteractor);
3344 long token = Binder.clearCallingIdentity();
3345 try {
3346 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3347 } finally {
3348 Binder.restoreCallingIdentity(token);
3349 }
3350 // TODO: VI Should we cache the activity so that it's easier to find later
3351 // rather than scan through all the stacks and activities?
3352 } catch (RemoteException re) {
3353 activityToCallback.clearVoiceSessionLocked();
3354 // TODO: VI Should this terminate the voice session?
3355 }
3356 }
3357
3358 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3359 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3360 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3361 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3362 boolean wasRunningVoice = mRunningVoice != null;
3363 mRunningVoice = session;
3364 if (!wasRunningVoice) {
3365 mVoiceWakeLock.acquire();
3366 updateSleepIfNeededLocked();
3367 }
3368 }
3369 }
3370
3371 void finishRunningVoiceLocked() {
3372 if (mRunningVoice != null) {
3373 mRunningVoice = null;
3374 mVoiceWakeLock.release();
3375 updateSleepIfNeededLocked();
3376 }
3377 }
3378
3379 @Override
3380 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3381 synchronized (mGlobalLock) {
3382 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3383 if (keepAwake) {
3384 mVoiceWakeLock.acquire();
3385 } else {
3386 mVoiceWakeLock.release();
3387 }
3388 }
3389 }
3390 }
3391
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003392 @Override
3393 public ComponentName getActivityClassForToken(IBinder token) {
3394 synchronized (mGlobalLock) {
3395 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3396 if (r == null) {
3397 return null;
3398 }
3399 return r.intent.getComponent();
3400 }
3401 }
3402
3403 @Override
3404 public String getPackageForToken(IBinder token) {
3405 synchronized (mGlobalLock) {
3406 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3407 if (r == null) {
3408 return null;
3409 }
3410 return r.packageName;
3411 }
3412 }
3413
3414 @Override
3415 public void showLockTaskEscapeMessage(IBinder token) {
3416 synchronized (mGlobalLock) {
3417 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3418 if (r == null) {
3419 return;
3420 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003421 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003422 }
3423 }
3424
3425 @Override
3426 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003427 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003428 final long token = Binder.clearCallingIdentity();
3429 try {
3430 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003431 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003432 }
3433 } finally {
3434 Binder.restoreCallingIdentity(token);
3435 }
3436 }
3437
3438 /**
3439 * Try to place task to provided position. The final position might be different depending on
3440 * current user and stacks state. The task will be moved to target stack if it's currently in
3441 * different stack.
3442 */
3443 @Override
3444 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003445 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 synchronized (mGlobalLock) {
3447 long ident = Binder.clearCallingIdentity();
3448 try {
3449 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3450 + taskId + " in stackId=" + stackId + " at position=" + position);
3451 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
3452 if (task == null) {
3453 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3454 + taskId);
3455 }
3456
3457 final ActivityStack stack = mStackSupervisor.getStack(stackId);
3458
3459 if (stack == null) {
3460 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3461 + stackId);
3462 }
3463 if (!stack.isActivityTypeStandardOrUndefined()) {
3464 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3465 + " the position of task " + taskId + " in/to non-standard stack");
3466 }
3467
3468 // TODO: Have the callers of this API call a separate reparent method if that is
3469 // what they intended to do vs. having this method also do reparenting.
3470 if (task.getStack() == stack) {
3471 // Change position in current stack.
3472 stack.positionChildAt(task, position);
3473 } else {
3474 // Reparent to new stack.
3475 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3476 !DEFER_RESUME, "positionTaskInStack");
3477 }
3478 } finally {
3479 Binder.restoreCallingIdentity(ident);
3480 }
3481 }
3482 }
3483
3484 @Override
3485 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3486 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3487 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3488 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3489 synchronized (mGlobalLock) {
3490 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3491 if (record == null) {
3492 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3493 + "found for: " + token);
3494 }
3495 record.setSizeConfigurations(horizontalSizeConfiguration,
3496 verticalSizeConfigurations, smallestSizeConfigurations);
3497 }
3498 }
3499
3500 /**
3501 * Dismisses split-screen multi-window mode.
3502 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3503 */
3504 @Override
3505 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003506 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003507 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3508 final long ident = Binder.clearCallingIdentity();
3509 try {
3510 synchronized (mGlobalLock) {
3511 final ActivityStack stack =
3512 mStackSupervisor.getDefaultDisplay().getSplitScreenPrimaryStack();
3513 if (stack == null) {
3514 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3515 return;
3516 }
3517
3518 if (toTop) {
3519 // Caller wants the current split-screen primary stack to be the top stack after
3520 // it goes fullscreen, so move it to the front.
3521 stack.moveToFront("dismissSplitScreenMode");
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003522 } else if (mStackSupervisor.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003523 // In this case the current split-screen primary stack shouldn't be the top
3524 // stack after it goes fullscreen, but it current has focus, so we move the
3525 // focus to the top-most split-screen secondary stack next to it.
3526 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3527 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3528 if (otherStack != null) {
3529 otherStack.moveToFront("dismissSplitScreenMode_other");
3530 }
3531 }
3532
Evan Rosky10475742018-09-05 19:02:48 -07003533 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003534 }
3535 } finally {
3536 Binder.restoreCallingIdentity(ident);
3537 }
3538 }
3539
3540 /**
3541 * Dismisses Pip
3542 * @param animate True if the dismissal should be animated.
3543 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3544 * default animation duration should be used.
3545 */
3546 @Override
3547 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003548 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003549 final long ident = Binder.clearCallingIdentity();
3550 try {
3551 synchronized (mGlobalLock) {
3552 final PinnedActivityStack stack =
3553 mStackSupervisor.getDefaultDisplay().getPinnedStack();
3554 if (stack == null) {
3555 Slog.w(TAG, "dismissPip: pinned stack not found.");
3556 return;
3557 }
3558 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3559 throw new IllegalArgumentException("Stack: " + stack
3560 + " doesn't support animated resize.");
3561 }
3562 if (animate) {
3563 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3564 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3565 } else {
3566 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3567 }
3568 }
3569 } finally {
3570 Binder.restoreCallingIdentity(ident);
3571 }
3572 }
3573
3574 @Override
3575 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003576 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003577 synchronized (mGlobalLock) {
3578 mSuppressResizeConfigChanges = suppress;
3579 }
3580 }
3581
3582 /**
3583 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3584 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3585 * activity and clearing the task at the same time.
3586 */
3587 @Override
3588 // TODO: API should just be about changing windowing modes...
3589 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003590 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003591 "moveTasksToFullscreenStack()");
3592 synchronized (mGlobalLock) {
3593 final long origId = Binder.clearCallingIdentity();
3594 try {
3595 final ActivityStack stack = mStackSupervisor.getStack(fromStackId);
3596 if (stack != null){
3597 if (!stack.isActivityTypeStandardOrUndefined()) {
3598 throw new IllegalArgumentException(
3599 "You can't move tasks from non-standard stacks.");
3600 }
3601 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3602 }
3603 } finally {
3604 Binder.restoreCallingIdentity(origId);
3605 }
3606 }
3607 }
3608
3609 /**
3610 * Moves the top activity in the input stackId to the pinned stack.
3611 *
3612 * @param stackId Id of stack to move the top activity to pinned stack.
3613 * @param bounds Bounds to use for pinned stack.
3614 *
3615 * @return True if the top activity of the input stack was successfully moved to the pinned
3616 * stack.
3617 */
3618 @Override
3619 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003620 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003621 "moveTopActivityToPinnedStack()");
3622 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003623 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003624 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3625 + "Device doesn't support picture-in-picture mode");
3626 }
3627
3628 long ident = Binder.clearCallingIdentity();
3629 try {
3630 return mStackSupervisor.moveTopStackActivityToPinnedStackLocked(stackId, bounds);
3631 } finally {
3632 Binder.restoreCallingIdentity(ident);
3633 }
3634 }
3635 }
3636
3637 @Override
3638 public boolean isInMultiWindowMode(IBinder token) {
3639 final long origId = Binder.clearCallingIdentity();
3640 try {
3641 synchronized (mGlobalLock) {
3642 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3643 if (r == null) {
3644 return false;
3645 }
3646 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3647 return r.inMultiWindowMode();
3648 }
3649 } finally {
3650 Binder.restoreCallingIdentity(origId);
3651 }
3652 }
3653
3654 @Override
3655 public boolean isInPictureInPictureMode(IBinder token) {
3656 final long origId = Binder.clearCallingIdentity();
3657 try {
3658 synchronized (mGlobalLock) {
3659 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3660 }
3661 } finally {
3662 Binder.restoreCallingIdentity(origId);
3663 }
3664 }
3665
3666 private boolean isInPictureInPictureMode(ActivityRecord r) {
3667 if (r == null || r.getStack() == null || !r.inPinnedWindowingMode()
3668 || r.getStack().isInStackLocked(r) == null) {
3669 return false;
3670 }
3671
3672 // If we are animating to fullscreen then we have already dispatched the PIP mode
3673 // changed, so we should reflect that check here as well.
3674 final PinnedActivityStack stack = r.getStack();
3675 final PinnedStackWindowController windowController = stack.getWindowContainerController();
3676 return !windowController.isAnimatingBoundsToFullscreen();
3677 }
3678
3679 @Override
3680 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3681 final long origId = Binder.clearCallingIdentity();
3682 try {
3683 synchronized (mGlobalLock) {
3684 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3685 "enterPictureInPictureMode", token, params);
3686
3687 // If the activity is already in picture in picture mode, then just return early
3688 if (isInPictureInPictureMode(r)) {
3689 return true;
3690 }
3691
3692 // Activity supports picture-in-picture, now check that we can enter PiP at this
3693 // point, if it is
3694 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3695 false /* beforeStopping */)) {
3696 return false;
3697 }
3698
3699 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003700 synchronized (mGlobalLock) {
3701 // Only update the saved args from the args that are set
3702 r.pictureInPictureArgs.copyOnlySet(params);
3703 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3704 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3705 // Adjust the source bounds by the insets for the transition down
3706 final Rect sourceBounds = new Rect(
3707 r.pictureInPictureArgs.getSourceRectHint());
3708 mStackSupervisor.moveActivityToPinnedStackLocked(
3709 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
3710 final PinnedActivityStack stack = r.getStack();
3711 stack.setPictureInPictureAspectRatio(aspectRatio);
3712 stack.setPictureInPictureActions(actions);
3713 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3714 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3715 logPictureInPictureArgs(params);
3716 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003717 };
3718
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003719 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003720 // If the keyguard is showing or occluded, then try and dismiss it before
3721 // entering picture-in-picture (this will prompt the user to authenticate if the
3722 // device is currently locked).
3723 dismissKeyguard(token, new KeyguardDismissCallback() {
3724 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003725 public void onDismissSucceeded() {
3726 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003727 }
3728 }, null /* message */);
3729 } else {
3730 // Enter picture in picture immediately otherwise
3731 enterPipRunnable.run();
3732 }
3733 return true;
3734 }
3735 } finally {
3736 Binder.restoreCallingIdentity(origId);
3737 }
3738 }
3739
3740 @Override
3741 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3742 final long origId = Binder.clearCallingIdentity();
3743 try {
3744 synchronized (mGlobalLock) {
3745 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3746 "setPictureInPictureParams", token, params);
3747
3748 // Only update the saved args from the args that are set
3749 r.pictureInPictureArgs.copyOnlySet(params);
3750 if (r.inPinnedWindowingMode()) {
3751 // If the activity is already in picture-in-picture, update the pinned stack now
3752 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3753 // be used the next time the activity enters PiP
3754 final PinnedActivityStack stack = r.getStack();
3755 if (!stack.isAnimatingBoundsToFullscreen()) {
3756 stack.setPictureInPictureAspectRatio(
3757 r.pictureInPictureArgs.getAspectRatio());
3758 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3759 }
3760 }
3761 logPictureInPictureArgs(params);
3762 }
3763 } finally {
3764 Binder.restoreCallingIdentity(origId);
3765 }
3766 }
3767
3768 @Override
3769 public int getMaxNumPictureInPictureActions(IBinder token) {
3770 // Currently, this is a static constant, but later, we may change this to be dependent on
3771 // the context of the activity
3772 return 3;
3773 }
3774
3775 private void logPictureInPictureArgs(PictureInPictureParams params) {
3776 if (params.hasSetActions()) {
3777 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3778 params.getActions().size());
3779 }
3780 if (params.hasSetAspectRatio()) {
3781 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3782 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3783 MetricsLogger.action(lm);
3784 }
3785 }
3786
3787 /**
3788 * Checks the state of the system and the activity associated with the given {@param token} to
3789 * verify that picture-in-picture is supported for that activity.
3790 *
3791 * @return the activity record for the given {@param token} if all the checks pass.
3792 */
3793 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3794 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003795 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003796 throw new IllegalStateException(caller
3797 + ": Device doesn't support picture-in-picture mode.");
3798 }
3799
3800 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3801 if (r == null) {
3802 throw new IllegalStateException(caller
3803 + ": Can't find activity for token=" + token);
3804 }
3805
3806 if (!r.supportsPictureInPicture()) {
3807 throw new IllegalStateException(caller
3808 + ": Current activity does not support picture-in-picture.");
3809 }
3810
3811 if (params.hasSetAspectRatio()
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003812 && !mWindowManager.isValidPictureInPictureAspectRatio(r.getStack().mDisplayId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003813 params.getAspectRatio())) {
3814 final float minAspectRatio = mContext.getResources().getFloat(
3815 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3816 final float maxAspectRatio = mContext.getResources().getFloat(
3817 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3818 throw new IllegalArgumentException(String.format(caller
3819 + ": Aspect ratio is too extreme (must be between %f and %f).",
3820 minAspectRatio, maxAspectRatio));
3821 }
3822
3823 // Truncate the number of actions if necessary
3824 params.truncateActions(getMaxNumPictureInPictureActions(token));
3825
3826 return r;
3827 }
3828
3829 @Override
3830 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003831 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003832 synchronized (mGlobalLock) {
3833 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3834 if (r == null) {
3835 throw new IllegalArgumentException("Activity does not exist; token="
3836 + activityToken);
3837 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003838 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003839 }
3840 }
3841
3842 @Override
3843 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
3844 Rect tempDockedTaskInsetBounds,
3845 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003846 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003847 long ident = Binder.clearCallingIdentity();
3848 try {
3849 synchronized (mGlobalLock) {
3850 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
3851 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
3852 PRESERVE_WINDOWS);
3853 }
3854 } finally {
3855 Binder.restoreCallingIdentity(ident);
3856 }
3857 }
3858
3859 @Override
3860 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003861 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003862 final long ident = Binder.clearCallingIdentity();
3863 try {
3864 synchronized (mGlobalLock) {
3865 mStackSupervisor.setSplitScreenResizing(resizing);
3866 }
3867 } finally {
3868 Binder.restoreCallingIdentity(ident);
3869 }
3870 }
3871
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003872 /**
3873 * Check that we have the features required for VR-related API calls, and throw an exception if
3874 * not.
3875 */
3876 void enforceSystemHasVrFeature() {
3877 if (!mContext.getPackageManager().hasSystemFeature(
3878 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
3879 throw new UnsupportedOperationException("VR mode not supported on this device!");
3880 }
3881 }
3882
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003883 @Override
3884 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003885 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003886
3887 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
3888
3889 ActivityRecord r;
3890 synchronized (mGlobalLock) {
3891 r = ActivityRecord.isInStackLocked(token);
3892 }
3893
3894 if (r == null) {
3895 throw new IllegalArgumentException();
3896 }
3897
3898 int err;
3899 if ((err = vrService.hasVrPackage(packageName, r.userId)) !=
3900 VrManagerInternal.NO_ERROR) {
3901 return err;
3902 }
3903
3904 // Clear the binder calling uid since this path may call moveToTask().
3905 final long callingId = Binder.clearCallingIdentity();
3906 try {
3907 synchronized (mGlobalLock) {
3908 r.requestedVrComponent = (enabled) ? packageName : null;
3909
3910 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07003911 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003912 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003913 }
3914 return 0;
3915 }
3916 } finally {
3917 Binder.restoreCallingIdentity(callingId);
3918 }
3919 }
3920
3921 @Override
3922 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
3923 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
3924 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003925 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003926 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
3927 throw new SecurityException("Only focused activity can call startVoiceInteraction");
3928 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07003929 if (mRunningVoice != null || activity.getTask().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003930 || activity.voiceSession != null) {
3931 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
3932 return;
3933 }
3934 if (activity.pendingVoiceInteractionStart) {
3935 Slog.w(TAG, "Pending start of voice interaction already.");
3936 return;
3937 }
3938 activity.pendingVoiceInteractionStart = true;
3939 }
3940 LocalServices.getService(VoiceInteractionManagerInternal.class)
3941 .startLocalVoiceInteraction(callingActivity, options);
3942 }
3943
3944 @Override
3945 public void stopLocalVoiceInteraction(IBinder callingActivity) {
3946 LocalServices.getService(VoiceInteractionManagerInternal.class)
3947 .stopLocalVoiceInteraction(callingActivity);
3948 }
3949
3950 @Override
3951 public boolean supportsLocalVoiceInteraction() {
3952 return LocalServices.getService(VoiceInteractionManagerInternal.class)
3953 .supportsLocalVoiceInteraction();
3954 }
3955
3956 /** Notifies all listeners when the pinned stack animation starts. */
3957 @Override
3958 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003959 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003960 }
3961
3962 /** Notifies all listeners when the pinned stack animation ends. */
3963 @Override
3964 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003965 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003966 }
3967
3968 @Override
3969 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003970 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003971 final long ident = Binder.clearCallingIdentity();
3972 try {
3973 synchronized (mGlobalLock) {
3974 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
3975 }
3976 } finally {
3977 Binder.restoreCallingIdentity(ident);
3978 }
3979 }
3980
3981 @Override
3982 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003983 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003984
3985 synchronized (mGlobalLock) {
3986 // Check if display is initialized in AM.
3987 if (!mStackSupervisor.isDisplayAdded(displayId)) {
3988 // Call might come when display is not yet added or has already been removed.
3989 if (DEBUG_CONFIGURATION) {
3990 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
3991 + displayId);
3992 }
3993 return false;
3994 }
3995
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003996 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003997 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003998 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003999 }
4000
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004001 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004002 final Message msg = PooledLambda.obtainMessage(
4003 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4004 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004005 }
4006
4007 final long origId = Binder.clearCallingIdentity();
4008 try {
4009 if (values != null) {
4010 Settings.System.clearConfiguration(values);
4011 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004012 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004013 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4014 return mTmpUpdateConfigurationResult.changes != 0;
4015 } finally {
4016 Binder.restoreCallingIdentity(origId);
4017 }
4018 }
4019 }
4020
4021 @Override
4022 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004023 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004024
4025 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004026 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004027 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004028 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004029 }
4030
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004031 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004032 final Message msg = PooledLambda.obtainMessage(
4033 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4034 DEFAULT_DISPLAY);
4035 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004036 }
4037
4038 final long origId = Binder.clearCallingIdentity();
4039 try {
4040 if (values != null) {
4041 Settings.System.clearConfiguration(values);
4042 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004043 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004044 UserHandle.USER_NULL, false /* deferResume */,
4045 mTmpUpdateConfigurationResult);
4046 return mTmpUpdateConfigurationResult.changes != 0;
4047 } finally {
4048 Binder.restoreCallingIdentity(origId);
4049 }
4050 }
4051 }
4052
4053 @Override
4054 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4055 CharSequence message) {
4056 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004057 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004058 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4059 }
4060 final long callingId = Binder.clearCallingIdentity();
4061 try {
4062 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004063 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004064 }
4065 } finally {
4066 Binder.restoreCallingIdentity(callingId);
4067 }
4068 }
4069
4070 @Override
4071 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004072 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 "cancelTaskWindowTransition()");
4074 final long ident = Binder.clearCallingIdentity();
4075 try {
4076 synchronized (mGlobalLock) {
4077 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId,
4078 MATCH_TASK_IN_STACKS_ONLY);
4079 if (task == null) {
4080 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4081 return;
4082 }
4083 task.cancelWindowTransition();
4084 }
4085 } finally {
4086 Binder.restoreCallingIdentity(ident);
4087 }
4088 }
4089
4090 @Override
4091 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004092 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004093 final long ident = Binder.clearCallingIdentity();
4094 try {
4095 final TaskRecord task;
4096 synchronized (mGlobalLock) {
4097 task = mStackSupervisor.anyTaskForIdLocked(taskId,
4098 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4099 if (task == null) {
4100 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4101 return null;
4102 }
4103 }
4104 // Don't call this while holding the lock as this operation might hit the disk.
4105 return task.getSnapshot(reducedResolution);
4106 } finally {
4107 Binder.restoreCallingIdentity(ident);
4108 }
4109 }
4110
4111 @Override
4112 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4113 synchronized (mGlobalLock) {
4114 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4115 if (r == null) {
4116 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4117 + token);
4118 return;
4119 }
4120 final long origId = Binder.clearCallingIdentity();
4121 try {
4122 r.setDisablePreviewScreenshots(disable);
4123 } finally {
4124 Binder.restoreCallingIdentity(origId);
4125 }
4126 }
4127 }
4128
4129 /** Return the user id of the last resumed activity. */
4130 @Override
4131 public @UserIdInt
4132 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004133 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004134 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4135 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004136 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004137 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004138 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004139 return mLastResumedActivity.userId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004140 }
4141 }
4142
4143 @Override
4144 public void updateLockTaskFeatures(int userId, int flags) {
4145 final int callingUid = Binder.getCallingUid();
4146 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004147 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 "updateLockTaskFeatures()");
4149 }
4150 synchronized (mGlobalLock) {
4151 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4152 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004153 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004154 }
4155 }
4156
4157 @Override
4158 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4159 synchronized (mGlobalLock) {
4160 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4161 if (r == null) {
4162 return;
4163 }
4164 final long origId = Binder.clearCallingIdentity();
4165 try {
4166 r.setShowWhenLocked(showWhenLocked);
4167 } finally {
4168 Binder.restoreCallingIdentity(origId);
4169 }
4170 }
4171 }
4172
4173 @Override
4174 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4175 synchronized (mGlobalLock) {
4176 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4177 if (r == null) {
4178 return;
4179 }
4180 final long origId = Binder.clearCallingIdentity();
4181 try {
4182 r.setTurnScreenOn(turnScreenOn);
4183 } finally {
4184 Binder.restoreCallingIdentity(origId);
4185 }
4186 }
4187 }
4188
4189 @Override
4190 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004192 "registerRemoteAnimations");
4193 definition.setCallingPid(Binder.getCallingPid());
4194 synchronized (mGlobalLock) {
4195 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4196 if (r == null) {
4197 return;
4198 }
4199 final long origId = Binder.clearCallingIdentity();
4200 try {
4201 r.registerRemoteAnimations(definition);
4202 } finally {
4203 Binder.restoreCallingIdentity(origId);
4204 }
4205 }
4206 }
4207
4208 @Override
4209 public void registerRemoteAnimationForNextActivityStart(String packageName,
4210 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004211 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004212 "registerRemoteAnimationForNextActivityStart");
4213 adapter.setCallingPid(Binder.getCallingPid());
4214 synchronized (mGlobalLock) {
4215 final long origId = Binder.clearCallingIdentity();
4216 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004217 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 packageName, adapter);
4219 } finally {
4220 Binder.restoreCallingIdentity(origId);
4221 }
4222 }
4223 }
4224
4225 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4226 @Override
4227 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4228 synchronized (mGlobalLock) {
4229 final long origId = Binder.clearCallingIdentity();
4230 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004231 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004232 } finally {
4233 Binder.restoreCallingIdentity(origId);
4234 }
4235 }
4236 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004237
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004238 @Override
4239 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004240 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004241 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004242 final int pid = Binder.getCallingPid();
4243 final WindowProcessController wpc = mPidMap.get(pid);
4244 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004245 }
4246 }
4247
4248 @Override
4249 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004250 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004251 != PERMISSION_GRANTED) {
4252 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4253 + Binder.getCallingPid()
4254 + ", uid=" + Binder.getCallingUid()
4255 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4256 Slog.w(TAG, msg);
4257 throw new SecurityException(msg);
4258 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004259 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004260 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004261 final int pid = Binder.getCallingPid();
4262 final WindowProcessController proc = mPidMap.get(pid);
4263 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004264 }
4265 }
4266
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004267 @Override
4268 public void stopAppSwitches() {
4269 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4270 synchronized (mGlobalLock) {
4271 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4272 mDidAppSwitch = false;
4273 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4274 }
4275 }
4276
4277 @Override
4278 public void resumeAppSwitches() {
4279 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4280 synchronized (mGlobalLock) {
4281 // Note that we don't execute any pending app switches... we will
4282 // let those wait until either the timeout, or the next start
4283 // activity request.
4284 mAppSwitchesAllowedTime = 0;
4285 }
4286 }
4287
4288 void onStartActivitySetDidAppSwitch() {
4289 if (mDidAppSwitch) {
4290 // This is the second allowed switch since we stopped switches, so now just generally
4291 // allow switches. Use case:
4292 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4293 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4294 // anyone to switch again).
4295 mAppSwitchesAllowedTime = 0;
4296 } else {
4297 mDidAppSwitch = true;
4298 }
4299 }
4300
4301 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004302 boolean shouldDisableNonVrUiLocked() {
4303 return mVrController.shouldDisableNonVrUiLocked();
4304 }
4305
Wale Ogunwale53783742018-09-16 10:21:51 -07004306 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004307 // VR apps are expected to run in a main display. If an app is turning on VR for
4308 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4309 // fullscreen stack before enabling VR Mode.
4310 // TODO: The goal of this code is to keep the VR app on the main display. When the
4311 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4312 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4313 // option would be a better choice here.
4314 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4315 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4316 + " to main stack for VR");
4317 final ActivityStack stack = mStackSupervisor.getDefaultDisplay().getOrCreateStack(
4318 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
4319 moveTaskToStack(r.getTask().taskId, stack.mStackId, true /* toTop */);
4320 }
4321 mH.post(() -> {
4322 if (!mVrController.onVrModeChanged(r)) {
4323 return;
4324 }
4325 synchronized (mGlobalLock) {
4326 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4327 mWindowManager.disableNonVrUi(disableNonVrUi);
4328 if (disableNonVrUi) {
4329 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4330 // then remove the pinned stack.
4331 mStackSupervisor.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
4332 }
4333 }
4334 });
4335 }
4336
Wale Ogunwale53783742018-09-16 10:21:51 -07004337 @Override
4338 public int getPackageScreenCompatMode(String packageName) {
4339 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4340 synchronized (mGlobalLock) {
4341 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4342 }
4343 }
4344
4345 @Override
4346 public void setPackageScreenCompatMode(String packageName, int mode) {
4347 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4348 "setPackageScreenCompatMode");
4349 synchronized (mGlobalLock) {
4350 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4351 }
4352 }
4353
4354 @Override
4355 public boolean getPackageAskScreenCompat(String packageName) {
4356 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4357 synchronized (mGlobalLock) {
4358 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4359 }
4360 }
4361
4362 @Override
4363 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4364 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4365 "setPackageAskScreenCompat");
4366 synchronized (mGlobalLock) {
4367 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4368 }
4369 }
4370
Wale Ogunwale64258362018-10-16 15:13:37 -07004371 public static String relaunchReasonToString(int relaunchReason) {
4372 switch (relaunchReason) {
4373 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4374 return "window_resize";
4375 case RELAUNCH_REASON_FREE_RESIZE:
4376 return "free_resize";
4377 default:
4378 return null;
4379 }
4380 }
4381
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004382 ActivityStack getTopDisplayFocusedStack() {
4383 return mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004384 }
4385
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004386 /** Pokes the task persister. */
4387 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4388 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4389 }
4390
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004391 boolean isKeyguardLocked() {
4392 return mKeyguardController.isKeyguardLocked();
4393 }
4394
4395 boolean isNextTransitionForward() {
4396 int transit = mWindowManager.getPendingAppTransition();
4397 return transit == TRANSIT_ACTIVITY_OPEN
4398 || transit == TRANSIT_TASK_OPEN
4399 || transit == TRANSIT_TASK_TO_FRONT;
4400 }
4401
Wale Ogunwale31913b52018-10-13 08:29:31 -07004402 void dumpLastANRLocked(PrintWriter pw) {
4403 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4404 if (mLastANRState == null) {
4405 pw.println(" <no ANR has occurred since boot>");
4406 } else {
4407 pw.println(mLastANRState);
4408 }
4409 }
4410
4411 void dumpLastANRTracesLocked(PrintWriter pw) {
4412 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4413
4414 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4415 if (ArrayUtils.isEmpty(files)) {
4416 pw.println(" <no ANR has occurred since boot>");
4417 return;
4418 }
4419 // Find the latest file.
4420 File latest = null;
4421 for (File f : files) {
4422 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4423 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004424 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004425 }
4426 pw.print("File: ");
4427 pw.print(latest.getName());
4428 pw.println();
4429 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4430 String line;
4431 while ((line = in.readLine()) != null) {
4432 pw.println(line);
4433 }
4434 } catch (IOException e) {
4435 pw.print("Unable to read: ");
4436 pw.print(e);
4437 pw.println();
4438 }
4439 }
4440
4441 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4442 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4443 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4444 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4445 }
4446
4447 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4448 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4449 pw.println(header);
4450
4451 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
4452 dumpPackage);
4453 boolean needSep = printedAnything;
4454
4455 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
4456 mStackSupervisor.getTopResumedActivity(), dumpPackage, needSep,
4457 " ResumedActivity: ");
4458 if (printed) {
4459 printedAnything = true;
4460 needSep = false;
4461 }
4462
4463 if (dumpPackage == null) {
4464 if (needSep) {
4465 pw.println();
4466 }
4467 printedAnything = true;
4468 mStackSupervisor.dump(pw, " ");
4469 }
4470
4471 if (!printedAnything) {
4472 pw.println(" (nothing)");
4473 }
4474 }
4475
4476 void dumpActivityContainersLocked(PrintWriter pw) {
4477 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
4478 mStackSupervisor.dumpChildrenNames(pw, " ");
4479 pw.println(" ");
4480 }
4481
4482 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4483 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4484 getActivityStartController().dump(pw, "", dumpPackage);
4485 }
4486
4487 /**
4488 * There are three things that cmd can be:
4489 * - a flattened component name that matches an existing activity
4490 * - the cmd arg isn't the flattened component name of an existing activity:
4491 * dump all activity whose component contains the cmd as a substring
4492 * - A hex number of the ActivityRecord object instance.
4493 *
4494 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4495 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4496 */
4497 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4498 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4499 ArrayList<ActivityRecord> activities;
4500
4501 synchronized (mGlobalLock) {
4502 activities = mStackSupervisor.getDumpActivitiesLocked(name, dumpVisibleStacksOnly,
4503 dumpFocusedStackOnly);
4504 }
4505
4506 if (activities.size() <= 0) {
4507 return false;
4508 }
4509
4510 String[] newArgs = new String[args.length - opti];
4511 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4512
4513 TaskRecord lastTask = null;
4514 boolean needSep = false;
4515 for (int i = activities.size() - 1; i >= 0; i--) {
4516 ActivityRecord r = activities.get(i);
4517 if (needSep) {
4518 pw.println();
4519 }
4520 needSep = true;
4521 synchronized (mGlobalLock) {
4522 final TaskRecord task = r.getTask();
4523 if (lastTask != task) {
4524 lastTask = task;
4525 pw.print("TASK "); pw.print(lastTask.affinity);
4526 pw.print(" id="); pw.print(lastTask.taskId);
4527 pw.print(" userId="); pw.println(lastTask.userId);
4528 if (dumpAll) {
4529 lastTask.dump(pw, " ");
4530 }
4531 }
4532 }
4533 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4534 }
4535 return true;
4536 }
4537
4538 /**
4539 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4540 * there is a thread associated with the activity.
4541 */
4542 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4543 final ActivityRecord r, String[] args, boolean dumpAll) {
4544 String innerPrefix = prefix + " ";
4545 synchronized (mGlobalLock) {
4546 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4547 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4548 pw.print(" pid=");
4549 if (r.hasProcess()) pw.println(r.app.getPid());
4550 else pw.println("(not running)");
4551 if (dumpAll) {
4552 r.dump(pw, innerPrefix);
4553 }
4554 }
4555 if (r.attachedToProcess()) {
4556 // flush anything that is already in the PrintWriter since the thread is going
4557 // to write to the file descriptor directly
4558 pw.flush();
4559 try {
4560 TransferPipe tp = new TransferPipe();
4561 try {
4562 r.app.getThread().dumpActivity(tp.getWriteFd(),
4563 r.appToken, innerPrefix, args);
4564 tp.go(fd);
4565 } finally {
4566 tp.kill();
4567 }
4568 } catch (IOException e) {
4569 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4570 } catch (RemoteException e) {
4571 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4572 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004573 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004574 }
4575
Wale Ogunwalef6733932018-06-27 05:14:34 -07004576 void writeSleepStateToProto(ProtoOutputStream proto) {
4577 for (ActivityTaskManagerInternal.SleepToken st : mStackSupervisor.mSleepTokens) {
4578 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4579 st.toString());
4580 }
4581
4582 if (mRunningVoice != null) {
4583 final long vrToken = proto.start(
4584 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
4585 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
4586 mRunningVoice.toString());
4587 mVoiceWakeLock.writeToProto(
4588 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
4589 proto.end(vrToken);
4590 }
4591
4592 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4593 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4594 mShuttingDown);
4595 mVrController.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004596 }
4597
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004598 int getCurrentUserId() {
4599 return mAmInternal.getCurrentUserId();
4600 }
4601
4602 private void enforceNotIsolatedCaller(String caller) {
4603 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4604 throw new SecurityException("Isolated process not allowed to call " + caller);
4605 }
4606 }
4607
Wale Ogunwalef6733932018-06-27 05:14:34 -07004608 public Configuration getConfiguration() {
4609 Configuration ci;
4610 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004611 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004612 ci.userSetLocale = false;
4613 }
4614 return ci;
4615 }
4616
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004617 /**
4618 * Current global configuration information. Contains general settings for the entire system,
4619 * also corresponds to the merged configuration of the default display.
4620 */
4621 Configuration getGlobalConfiguration() {
4622 return mStackSupervisor.getConfiguration();
4623 }
4624
4625 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4626 boolean initLocale) {
4627 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4628 }
4629
4630 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4631 boolean initLocale, boolean deferResume) {
4632 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4633 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4634 UserHandle.USER_NULL, deferResume);
4635 }
4636
4637 void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
4638 final long origId = Binder.clearCallingIdentity();
4639 try {
4640 synchronized (mGlobalLock) {
4641 updateConfigurationLocked(values, null, false, true, userId,
4642 false /* deferResume */);
4643 }
4644 } finally {
4645 Binder.restoreCallingIdentity(origId);
4646 }
4647 }
4648
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004649 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4650 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4651 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4652 deferResume, null /* result */);
4653 }
4654
4655 /**
4656 * Do either or both things: (1) change the current configuration, and (2)
4657 * make sure the given activity is running with the (now) current
4658 * configuration. Returns true if the activity has been left running, or
4659 * false if <var>starting</var> is being destroyed to match the new
4660 * configuration.
4661 *
4662 * @param userId is only used when persistent parameter is set to true to persist configuration
4663 * for that particular user
4664 */
4665 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4666 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4667 ActivityTaskManagerService.UpdateConfigurationResult result) {
4668 int changes = 0;
4669 boolean kept = true;
4670
4671 if (mWindowManager != null) {
4672 mWindowManager.deferSurfaceLayout();
4673 }
4674 try {
4675 if (values != null) {
4676 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4677 deferResume);
4678 }
4679
4680 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4681 } finally {
4682 if (mWindowManager != null) {
4683 mWindowManager.continueSurfaceLayout();
4684 }
4685 }
4686
4687 if (result != null) {
4688 result.changes = changes;
4689 result.activityRelaunched = !kept;
4690 }
4691 return kept;
4692 }
4693
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004694 /** Update default (global) configuration and notify listeners about changes. */
4695 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4696 boolean persistent, int userId, boolean deferResume) {
4697 mTempConfig.setTo(getGlobalConfiguration());
4698 final int changes = mTempConfig.updateFrom(values);
4699 if (changes == 0) {
4700 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4701 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4702 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4703 // (even if there are no actual changes) to unfreeze the window.
4704 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4705 return 0;
4706 }
4707
4708 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4709 "Updating global configuration to: " + values);
4710
4711 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4712 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4713 values.colorMode,
4714 values.densityDpi,
4715 values.fontScale,
4716 values.hardKeyboardHidden,
4717 values.keyboard,
4718 values.keyboardHidden,
4719 values.mcc,
4720 values.mnc,
4721 values.navigation,
4722 values.navigationHidden,
4723 values.orientation,
4724 values.screenHeightDp,
4725 values.screenLayout,
4726 values.screenWidthDp,
4727 values.smallestScreenWidthDp,
4728 values.touchscreen,
4729 values.uiMode);
4730
4731
4732 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4733 final LocaleList locales = values.getLocales();
4734 int bestLocaleIndex = 0;
4735 if (locales.size() > 1) {
4736 if (mSupportedSystemLocales == null) {
4737 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4738 }
4739 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4740 }
4741 SystemProperties.set("persist.sys.locale",
4742 locales.get(bestLocaleIndex).toLanguageTag());
4743 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004744
4745 final Message m = PooledLambda.obtainMessage(
4746 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4747 locales.get(bestLocaleIndex));
4748 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004749 }
4750
Yunfan Chen75157d72018-07-27 14:47:21 +09004751 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004752
4753 // Update stored global config and notify everyone about the change.
4754 mStackSupervisor.onConfigurationChanged(mTempConfig);
4755
4756 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4757 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004758 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004759
4760 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004761 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004762
4763 AttributeCache ac = AttributeCache.instance();
4764 if (ac != null) {
4765 ac.updateConfiguration(mTempConfig);
4766 }
4767
4768 // Make sure all resources in our process are updated right now, so that anyone who is going
4769 // to retrieve resource values after we return will be sure to get the new ones. This is
4770 // especially important during boot, where the first config change needs to guarantee all
4771 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004772 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004773
4774 // We need another copy of global config because we're scheduling some calls instead of
4775 // running them in place. We need to be sure that object we send will be handled unchanged.
4776 final Configuration configCopy = new Configuration(mTempConfig);
4777 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004778 final Message msg = PooledLambda.obtainMessage(
4779 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4780 this, userId, configCopy);
4781 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004782 }
4783
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004784 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004785 final int pid = mPidMap.keyAt(i);
4786 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004787 if (DEBUG_CONFIGURATION) {
4788 Slog.v(TAG_CONFIGURATION, "Update process config of "
4789 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004790 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004791 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004792 }
4793
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004794 final Message msg = PooledLambda.obtainMessage(
4795 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4796 mAmInternal, changes, initLocale);
4797 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004798
4799 // Override configuration of the default display duplicates global config, so we need to
4800 // update it also. This will also notify WindowManager about changes.
4801 performDisplayOverrideConfigUpdate(mStackSupervisor.getConfiguration(), deferResume,
4802 DEFAULT_DISPLAY);
4803
4804 return changes;
4805 }
4806
4807 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
4808 boolean deferResume, int displayId) {
4809 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
4810 displayId, null /* result */);
4811 }
4812
4813 /**
4814 * Updates override configuration specific for the selected display. If no config is provided,
4815 * new one will be computed in WM based on current display info.
4816 */
4817 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
4818 ActivityRecord starting, boolean deferResume, int displayId,
4819 ActivityTaskManagerService.UpdateConfigurationResult result) {
4820 int changes = 0;
4821 boolean kept = true;
4822
4823 if (mWindowManager != null) {
4824 mWindowManager.deferSurfaceLayout();
4825 }
4826 try {
4827 if (values != null) {
4828 if (displayId == DEFAULT_DISPLAY) {
4829 // Override configuration of the default display duplicates global config, so
4830 // we're calling global config update instead for default display. It will also
4831 // apply the correct override config.
4832 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
4833 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
4834 } else {
4835 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
4836 }
4837 }
4838
4839 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4840 } finally {
4841 if (mWindowManager != null) {
4842 mWindowManager.continueSurfaceLayout();
4843 }
4844 }
4845
4846 if (result != null) {
4847 result.changes = changes;
4848 result.activityRelaunched = !kept;
4849 }
4850 return kept;
4851 }
4852
4853 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
4854 int displayId) {
4855 mTempConfig.setTo(mStackSupervisor.getDisplayOverrideConfiguration(displayId));
4856 final int changes = mTempConfig.updateFrom(values);
4857 if (changes != 0) {
4858 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
4859 + mTempConfig + " for displayId=" + displayId);
4860 mStackSupervisor.setDisplayOverrideConfiguration(mTempConfig, displayId);
4861
4862 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
4863 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004864 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004865
Wale Ogunwale5c918702018-10-18 11:06:33 -07004866 // Post message to start process to avoid possible deadlock of calling into AMS with
4867 // the ATMS lock held.
4868 final Message msg = PooledLambda.obtainMessage(
4869 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
4870 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
4871 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004872 }
4873 }
4874
4875 // Update the configuration with WM first and check if any of the stacks need to be resized
4876 // due to the configuration change. If so, resize the stacks now and do any relaunches if
4877 // necessary. This way we don't need to relaunch again afterwards in
4878 // ensureActivityConfiguration().
4879 if (mWindowManager != null) {
4880 final int[] resizedStacks =
4881 mWindowManager.setNewDisplayOverrideConfiguration(mTempConfig, displayId);
4882 if (resizedStacks != null) {
4883 for (int stackId : resizedStacks) {
4884 resizeStackWithBoundsFromWindowManager(stackId, deferResume);
4885 }
4886 }
4887 }
4888
4889 return changes;
4890 }
4891
Wale Ogunwalef6733932018-06-27 05:14:34 -07004892 private void updateEventDispatchingLocked(boolean booted) {
4893 mWindowManager.setEventDispatching(booted && !mShuttingDown);
4894 }
4895
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004896 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
4897 final ContentResolver resolver = mContext.getContentResolver();
4898 Settings.System.putConfigurationForUser(resolver, config, userId);
4899 }
4900
4901 private void sendLocaleToMountDaemonMsg(Locale l) {
4902 try {
4903 IBinder service = ServiceManager.getService("mount");
4904 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
4905 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
4906 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
4907 } catch (RemoteException e) {
4908 Log.e(TAG, "Error storing locale for decryption UI", e);
4909 }
4910 }
4911
4912 boolean isActivityStartsLoggingEnabled() {
4913 return mAmInternal.isActivityStartsLoggingEnabled();
4914 }
4915
Wale Ogunwalef6733932018-06-27 05:14:34 -07004916 void enableScreenAfterBoot(boolean booted) {
4917 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
4918 SystemClock.uptimeMillis());
4919 mWindowManager.enableScreenAfterBoot();
4920
4921 synchronized (mGlobalLock) {
4922 updateEventDispatchingLocked(booted);
4923 }
4924 }
4925
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004926 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
4927 if (r == null || !r.hasProcess()) {
4928 return KEY_DISPATCHING_TIMEOUT_MS;
4929 }
4930 return getInputDispatchingTimeoutLocked(r.app);
4931 }
4932
4933 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07004934 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07004935 }
4936
Wale Ogunwalef6733932018-06-27 05:14:34 -07004937 /**
4938 * Decide based on the configuration whether we should show the ANR,
4939 * crash, etc dialogs. The idea is that if there is no affordance to
4940 * press the on-screen buttons, or the user experience would be more
4941 * greatly impacted than the crash itself, we shouldn't show the dialog.
4942 *
4943 * A thought: SystemUI might also want to get told about this, the Power
4944 * dialog / global actions also might want different behaviors.
4945 */
4946 private void updateShouldShowDialogsLocked(Configuration config) {
4947 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
4948 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
4949 && config.navigation == Configuration.NAVIGATION_NONAV);
4950 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
4951 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
4952 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
4953 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
4954 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
4955 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
4956 HIDE_ERROR_DIALOGS, 0) != 0;
4957 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
4958 }
4959
4960 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
4961 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
4962 FONT_SCALE, 1.0f, userId);
4963
4964 synchronized (this) {
4965 if (getGlobalConfiguration().fontScale == scaleFactor) {
4966 return;
4967 }
4968
4969 final Configuration configuration
4970 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
4971 configuration.fontScale = scaleFactor;
4972 updatePersistentConfiguration(configuration, userId);
4973 }
4974 }
4975
4976 // Actually is sleeping or shutting down or whatever else in the future
4977 // is an inactive state.
4978 boolean isSleepingOrShuttingDownLocked() {
4979 return isSleepingLocked() || mShuttingDown;
4980 }
4981
4982 boolean isSleepingLocked() {
4983 return mSleeping;
4984 }
4985
Riddle Hsu16567132018-08-16 21:37:47 +08004986 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07004987 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
4988 final TaskRecord task = r.getTask();
4989 if (task.isActivityTypeStandard()) {
4990 if (mCurAppTimeTracker != r.appTimeTracker) {
4991 // We are switching app tracking. Complete the current one.
4992 if (mCurAppTimeTracker != null) {
4993 mCurAppTimeTracker.stop();
4994 mH.obtainMessage(
4995 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
4996 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker);
4997 mCurAppTimeTracker = null;
4998 }
4999 if (r.appTimeTracker != null) {
5000 mCurAppTimeTracker = r.appTimeTracker;
5001 startTimeTrackingFocusedActivityLocked();
5002 }
5003 } else {
5004 startTimeTrackingFocusedActivityLocked();
5005 }
5006 } else {
5007 r.appTimeTracker = null;
5008 }
5009 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5010 // TODO: Probably not, because we don't want to resume voice on switching
5011 // back to this activity
5012 if (task.voiceInteractor != null) {
5013 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5014 } else {
5015 finishRunningVoiceLocked();
5016
5017 if (mLastResumedActivity != null) {
5018 final IVoiceInteractionSession session;
5019
5020 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTask();
5021 if (lastResumedActivityTask != null
5022 && lastResumedActivityTask.voiceSession != null) {
5023 session = lastResumedActivityTask.voiceSession;
5024 } else {
5025 session = mLastResumedActivity.voiceSession;
5026 }
5027
5028 if (session != null) {
5029 // We had been in a voice interaction session, but now focused has
5030 // move to something different. Just finish the session, we can't
5031 // return to it and retain the proper state and synchronization with
5032 // the voice interaction service.
5033 finishVoiceTask(session);
5034 }
5035 }
5036 }
5037
5038 if (mLastResumedActivity != null && r.userId != mLastResumedActivity.userId) {
5039 mAmInternal.sendForegroundProfileChanged(r.userId);
5040 }
5041 updateResumedAppTrace(r);
5042 mLastResumedActivity = r;
5043
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005044 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005045
5046 applyUpdateLockStateLocked(r);
5047 applyUpdateVrModeLocked(r);
5048
5049 EventLogTags.writeAmSetResumedActivity(
5050 r == null ? -1 : r.userId,
5051 r == null ? "NULL" : r.shortComponentName,
5052 reason);
5053 }
5054
5055 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5056 synchronized (mGlobalLock) {
5057 final ActivityTaskManagerInternal.SleepToken token = mStackSupervisor.createSleepTokenLocked(tag, displayId);
5058 updateSleepIfNeededLocked();
5059 return token;
5060 }
5061 }
5062
5063 void updateSleepIfNeededLocked() {
5064 final boolean shouldSleep = !mStackSupervisor.hasAwakeDisplay();
5065 final boolean wasSleeping = mSleeping;
5066 boolean updateOomAdj = false;
5067
5068 if (!shouldSleep) {
5069 // If wasSleeping is true, we need to wake up activity manager state from when
5070 // we started sleeping. In either case, we need to apply the sleep tokens, which
5071 // will wake up stacks or put them to sleep as appropriate.
5072 if (wasSleeping) {
5073 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005074 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5075 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005076 startTimeTrackingFocusedActivityLocked();
5077 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5078 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5079 }
5080 mStackSupervisor.applySleepTokensLocked(true /* applyToStacks */);
5081 if (wasSleeping) {
5082 updateOomAdj = true;
5083 }
5084 } else if (!mSleeping && shouldSleep) {
5085 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005086 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5087 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005088 if (mCurAppTimeTracker != null) {
5089 mCurAppTimeTracker.stop();
5090 }
5091 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5092 mStackSupervisor.goingToSleepLocked();
5093 updateResumedAppTrace(null /* resumed */);
5094 updateOomAdj = true;
5095 }
5096 if (updateOomAdj) {
5097 mH.post(mAmInternal::updateOomAdj);
5098 }
5099 }
5100
5101 void updateOomAdj() {
5102 mH.post(mAmInternal::updateOomAdj);
5103 }
5104
Wale Ogunwale53783742018-09-16 10:21:51 -07005105 void updateCpuStats() {
5106 mH.post(mAmInternal::updateCpuStats);
5107 }
5108
5109 void updateUsageStats(ActivityRecord component, boolean resumed) {
5110 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateUsageStats,
5111 mAmInternal, component.realActivity, component.app.mUid, component.userId, resumed);
5112 mH.sendMessage(m);
5113 }
5114
5115 void setBooting(boolean booting) {
5116 mAmInternal.setBooting(booting);
5117 }
5118
5119 boolean isBooting() {
5120 return mAmInternal.isBooting();
5121 }
5122
5123 void setBooted(boolean booted) {
5124 mAmInternal.setBooted(booted);
5125 }
5126
5127 boolean isBooted() {
5128 return mAmInternal.isBooted();
5129 }
5130
5131 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5132 mH.post(() -> {
5133 if (finishBooting) {
5134 mAmInternal.finishBooting();
5135 }
5136 if (enableScreen) {
5137 mInternal.enableScreenAfterBoot(isBooted());
5138 }
5139 });
5140 }
5141
5142 void setHeavyWeightProcess(ActivityRecord root) {
5143 mHeavyWeightProcess = root.app;
5144 final Message m = PooledLambda.obtainMessage(
5145 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
5146 root.app, root.intent, root.userId);
5147 mH.sendMessage(m);
5148 }
5149
5150 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5151 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5152 return;
5153 }
5154
5155 mHeavyWeightProcess = null;
5156 final Message m = PooledLambda.obtainMessage(
5157 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5158 proc.mUserId);
5159 mH.sendMessage(m);
5160 }
5161
5162 private void cancelHeavyWeightProcessNotification(int userId) {
5163 final INotificationManager inm = NotificationManager.getService();
5164 if (inm == null) {
5165 return;
5166 }
5167 try {
5168 inm.cancelNotificationWithTag("android", null,
5169 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5170 } catch (RuntimeException e) {
5171 Slog.w(TAG, "Error canceling notification for service", e);
5172 } catch (RemoteException e) {
5173 }
5174
5175 }
5176
5177 private void postHeavyWeightProcessNotification(
5178 WindowProcessController proc, Intent intent, int userId) {
5179 if (proc == null) {
5180 return;
5181 }
5182
5183 final INotificationManager inm = NotificationManager.getService();
5184 if (inm == null) {
5185 return;
5186 }
5187
5188 try {
5189 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5190 String text = mContext.getString(R.string.heavy_weight_notification,
5191 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5192 Notification notification =
5193 new Notification.Builder(context,
5194 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5195 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5196 .setWhen(0)
5197 .setOngoing(true)
5198 .setTicker(text)
5199 .setColor(mContext.getColor(
5200 com.android.internal.R.color.system_notification_accent_color))
5201 .setContentTitle(text)
5202 .setContentText(
5203 mContext.getText(R.string.heavy_weight_notification_detail))
5204 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5205 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5206 new UserHandle(userId)))
5207 .build();
5208 try {
5209 inm.enqueueNotificationWithTag("android", "android", null,
5210 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5211 } catch (RuntimeException e) {
5212 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5213 } catch (RemoteException e) {
5214 }
5215 } catch (PackageManager.NameNotFoundException e) {
5216 Slog.w(TAG, "Unable to create context for heavy notification", e);
5217 }
5218
5219 }
5220
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005221 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5222 IBinder token, String resultWho, int requestCode, Intent[] intents,
5223 String[] resolvedTypes, int flags, Bundle bOptions) {
5224
5225 ActivityRecord activity = null;
5226 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5227 activity = ActivityRecord.isInStackLocked(token);
5228 if (activity == null) {
5229 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5230 return null;
5231 }
5232 if (activity.finishing) {
5233 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5234 return null;
5235 }
5236 }
5237
5238 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5239 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5240 bOptions);
5241 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5242 if (noCreate) {
5243 return rec;
5244 }
5245 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5246 if (activity.pendingResults == null) {
5247 activity.pendingResults = new HashSet<>();
5248 }
5249 activity.pendingResults.add(rec.ref);
5250 }
5251 return rec;
5252 }
5253
Andrii Kulian52d255c2018-07-13 11:32:19 -07005254 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005255 private void startTimeTrackingFocusedActivityLocked() {
Andrii Kulian52d255c2018-07-13 11:32:19 -07005256 final ActivityRecord resumedActivity = mStackSupervisor.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005257 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5258 mCurAppTimeTracker.start(resumedActivity.packageName);
5259 }
5260 }
5261
5262 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5263 if (mTracedResumedActivity != null) {
5264 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5265 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5266 }
5267 if (resumed != null) {
5268 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5269 constructResumedTraceName(resumed.packageName), 0);
5270 }
5271 mTracedResumedActivity = resumed;
5272 }
5273
5274 private String constructResumedTraceName(String packageName) {
5275 return "focused app: " + packageName;
5276 }
5277
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005278 /** Helper method that requests bounds from WM and applies them to stack. */
5279 private void resizeStackWithBoundsFromWindowManager(int stackId, boolean deferResume) {
5280 final Rect newStackBounds = new Rect();
5281 final ActivityStack stack = mStackSupervisor.getStack(stackId);
5282
5283 // TODO(b/71548119): Revert CL introducing below once cause of mismatch is found.
5284 if (stack == null) {
5285 final StringWriter writer = new StringWriter();
5286 final PrintWriter printWriter = new PrintWriter(writer);
5287 mStackSupervisor.dumpDisplays(printWriter);
5288 printWriter.flush();
5289
5290 Log.wtf(TAG, "stack not found:" + stackId + " displays:" + writer);
5291 }
5292
5293 stack.getBoundsForNewConfiguration(newStackBounds);
5294 mStackSupervisor.resizeStackLocked(
5295 stack, !newStackBounds.isEmpty() ? newStackBounds : null /* bounds */,
5296 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
5297 false /* preserveWindows */, false /* allowResizeInDockedMode */, deferResume);
5298 }
5299
5300 /** Applies latest configuration and/or visibility updates if needed. */
5301 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5302 boolean kept = true;
Andrii Kulian5f750bc2018-07-17 08:57:23 -07005303 final ActivityStack mainStack = mStackSupervisor.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005304 // mainStack is null during startup.
5305 if (mainStack != null) {
5306 if (changes != 0 && starting == null) {
5307 // If the configuration changed, and the caller is not already
5308 // in the process of starting an activity, then find the top
5309 // activity to check if its configuration needs to change.
5310 starting = mainStack.topRunningActivityLocked();
5311 }
5312
5313 if (starting != null) {
5314 kept = starting.ensureActivityConfiguration(changes,
5315 false /* preserveWindow */);
5316 // And we need to make sure at this point that all other activities
5317 // are made visible with the correct configuration.
5318 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes,
5319 !PRESERVE_WINDOWS);
5320 }
5321 }
5322
5323 return kept;
5324 }
5325
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005326 void scheduleAppGcsLocked() {
5327 mH.post(() -> mAmInternal.scheduleAppGcs());
5328 }
5329
Wale Ogunwale53783742018-09-16 10:21:51 -07005330 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5331 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5332 }
5333
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005334 /**
5335 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5336 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5337 * on demand.
5338 */
5339 IPackageManager getPackageManager() {
5340 return AppGlobals.getPackageManager();
5341 }
5342
5343 PackageManagerInternal getPackageManagerInternalLocked() {
5344 if (mPmInternal == null) {
5345 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5346 }
5347 return mPmInternal;
5348 }
5349
Wale Ogunwale008163e2018-07-23 23:11:08 -07005350 AppWarnings getAppWarningsLocked() {
5351 return mAppWarnings;
5352 }
5353
Wale Ogunwale214f3482018-10-04 11:00:47 -07005354 Intent getHomeIntent() {
5355 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5356 intent.setComponent(mTopComponent);
5357 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5358 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5359 intent.addCategory(Intent.CATEGORY_HOME);
5360 }
5361 return intent;
5362 }
5363
5364 /**
5365 * This starts home activity on displays that can have system decorations and only if the
5366 * home activity can have multiple instances.
5367 */
5368 boolean startHomeActivityLocked(int userId, String reason, int displayId) {
5369 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL && mTopAction == null) {
5370 // We are running in factory test mode, but unable to find the factory test app, so just
5371 // sit around displaying the error message and don't try to start anything.
5372 return false;
5373 }
5374
5375 final Intent intent = getHomeIntent();
5376 ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
5377 if (aInfo != null) {
5378 intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
5379 // Don't do this if the home app is currently being instrumented.
5380 aInfo = new ActivityInfo(aInfo);
5381 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
5382 WindowProcessController app =
5383 getProcessController(aInfo.processName, aInfo.applicationInfo.uid);
5384 if (app == null || !app.isInstrumenting()) {
5385 intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
5386 final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
5387 // For ANR debugging to verify if the user activity is the one that actually
5388 // launched.
5389 final String myReason = reason + ":" + userId + ":" + resolvedUserId;
5390 getActivityStartController().startHomeActivity(intent, aInfo, myReason, displayId);
5391 }
5392 } else {
5393 Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
5394 }
5395
5396 return true;
5397 }
5398
5399 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
5400 ActivityInfo ai = null;
5401 final ComponentName comp = intent.getComponent();
5402 try {
5403 if (comp != null) {
5404 // Factory test.
5405 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
5406 } else {
5407 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
5408 intent,
5409 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5410 flags, userId);
5411
5412 if (info != null) {
5413 ai = info.activityInfo;
5414 }
5415 }
5416 } catch (RemoteException e) {
5417 // ignore
5418 }
5419
5420 return ai;
5421 }
5422
5423 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5424 if (info == null) return null;
5425 ApplicationInfo newInfo = new ApplicationInfo(info);
5426 newInfo.initForUser(userId);
5427 return newInfo;
5428 }
5429
Wale Ogunwale9c103022018-10-18 07:44:54 -07005430 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005431 if (uid == SYSTEM_UID) {
5432 // The system gets to run in any process. If there are multiple processes with the same
5433 // uid, just pick the first (this should never happen).
5434 final SparseArray<WindowProcessController> procs =
5435 mProcessNames.getMap().get(processName);
5436 if (procs == null) return null;
5437 final int procCount = procs.size();
5438 for (int i = 0; i < procCount; i++) {
5439 final int procUid = procs.keyAt(i);
5440 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5441 // Don't use an app process or different user process for system component.
5442 continue;
5443 }
5444 return procs.valueAt(i);
5445 }
5446 }
5447
5448 return mProcessNames.get(processName, uid);
5449 }
5450
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005451 WindowProcessController getProcessController(IApplicationThread thread) {
5452 if (thread == null) {
5453 return null;
5454 }
5455
5456 final IBinder threadBinder = thread.asBinder();
5457 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5458 for (int i = pmap.size()-1; i >= 0; i--) {
5459 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5460 for (int j = procs.size() - 1; j >= 0; j--) {
5461 final WindowProcessController proc = procs.valueAt(j);
5462 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5463 return proc;
5464 }
5465 }
5466 }
5467
5468 return null;
5469 }
5470
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005471 int getUidStateLocked(int uid) {
5472 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5473 }
5474
Wale Ogunwale9de19442018-10-18 19:05:03 -07005475 /**
5476 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5477 * the whitelist
5478 */
5479 String getPendingTempWhitelistTagForUidLocked(int uid) {
5480 return mPendingTempWhitelist.get(uid);
5481 }
5482
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005483 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5484 if (true || Build.IS_USER) {
5485 return;
5486 }
5487
5488 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5489 StrictMode.allowThreadDiskWrites();
5490 try {
5491 File tracesDir = new File("/data/anr");
5492 File tracesFile = null;
5493 try {
5494 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5495
5496 StringBuilder sb = new StringBuilder();
5497 Time tobj = new Time();
5498 tobj.set(System.currentTimeMillis());
5499 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5500 sb.append(": ");
5501 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5502 sb.append(" since ");
5503 sb.append(msg);
5504 FileOutputStream fos = new FileOutputStream(tracesFile);
5505 fos.write(sb.toString().getBytes());
5506 if (app == null) {
5507 fos.write("\n*** No application process!".getBytes());
5508 }
5509 fos.close();
5510 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5511 } catch (IOException e) {
5512 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5513 return;
5514 }
5515
5516 if (app != null && app.getPid() > 0) {
5517 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5518 firstPids.add(app.getPid());
5519 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5520 }
5521
5522 File lastTracesFile = null;
5523 File curTracesFile = null;
5524 for (int i=9; i>=0; i--) {
5525 String name = String.format(Locale.US, "slow%02d.txt", i);
5526 curTracesFile = new File(tracesDir, name);
5527 if (curTracesFile.exists()) {
5528 if (lastTracesFile != null) {
5529 curTracesFile.renameTo(lastTracesFile);
5530 } else {
5531 curTracesFile.delete();
5532 }
5533 }
5534 lastTracesFile = curTracesFile;
5535 }
5536 tracesFile.renameTo(curTracesFile);
5537 } finally {
5538 StrictMode.setThreadPolicy(oldPolicy);
5539 }
5540 }
5541
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005542 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005543 static final int REPORT_TIME_TRACKER_MSG = 1;
Wale Ogunwale98875612018-10-12 07:53:02 -07005544 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5545 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005546
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005547 public H(Looper looper) {
5548 super(looper, null, true);
5549 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005550
5551 @Override
5552 public void handleMessage(Message msg) {
5553 switch (msg.what) {
5554 case REPORT_TIME_TRACKER_MSG: {
5555 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5556 tracker.deliverResult(mContext);
5557 } break;
5558 }
5559 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005560 }
5561
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005562 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005563 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005564
5565 public UiHandler() {
5566 super(com.android.server.UiThread.get().getLooper(), null, true);
5567 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005568
5569 @Override
5570 public void handleMessage(Message msg) {
5571 switch (msg.what) {
5572 case DISMISS_DIALOG_UI_MSG: {
5573 final Dialog d = (Dialog) msg.obj;
5574 d.dismiss();
5575 break;
5576 }
5577 }
5578 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005579 }
5580
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005581 final class LocalService extends ActivityTaskManagerInternal {
5582 @Override
5583 public SleepToken acquireSleepToken(String tag, int displayId) {
5584 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005585 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005586 }
5587
5588 @Override
5589 public ComponentName getHomeActivityForUser(int userId) {
5590 synchronized (mGlobalLock) {
Louis Changbd48dca2018-08-29 17:44:34 +08005591 ActivityRecord homeActivity =
5592 mStackSupervisor.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005593 return homeActivity == null ? null : homeActivity.realActivity;
5594 }
5595 }
5596
5597 @Override
5598 public void onLocalVoiceInteractionStarted(IBinder activity,
5599 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5600 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005601 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005602 }
5603 }
5604
5605 @Override
5606 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5607 synchronized (mGlobalLock) {
5608 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5609 reasons, timestamp);
5610 }
5611 }
5612
5613 @Override
5614 public void notifyAppTransitionFinished() {
5615 synchronized (mGlobalLock) {
5616 mStackSupervisor.notifyAppTransitionDone();
5617 }
5618 }
5619
5620 @Override
5621 public void notifyAppTransitionCancelled() {
5622 synchronized (mGlobalLock) {
5623 mStackSupervisor.notifyAppTransitionDone();
5624 }
5625 }
5626
5627 @Override
5628 public List<IBinder> getTopVisibleActivities() {
5629 synchronized (mGlobalLock) {
5630 return mStackSupervisor.getTopVisibleActivities();
5631 }
5632 }
5633
5634 @Override
5635 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5636 synchronized (mGlobalLock) {
5637 mStackSupervisor.setDockedStackMinimized(minimized);
5638 }
5639 }
5640
5641 @Override
5642 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5643 Bundle bOptions) {
5644 Preconditions.checkNotNull(intents, "intents");
5645 final String[] resolvedTypes = new String[intents.length];
5646
5647 // UID of the package on user userId.
5648 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5649 // packageUid may not be initialized.
5650 int packageUid = 0;
5651 final long ident = Binder.clearCallingIdentity();
5652
5653 try {
5654 for (int i = 0; i < intents.length; i++) {
5655 resolvedTypes[i] =
5656 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5657 }
5658
5659 packageUid = AppGlobals.getPackageManager().getPackageUid(
5660 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5661 } catch (RemoteException e) {
5662 // Shouldn't happen.
5663 } finally {
5664 Binder.restoreCallingIdentity(ident);
5665 }
5666
5667 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005668 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005669 packageUid, packageName,
5670 intents, resolvedTypes, null /* resultTo */,
5671 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinski201bc0c2018-07-20 15:32:00 +01005672 false /* validateIncomingUser */, null /* originatingPendingIntent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005673 }
5674 }
5675
5676 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005677 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5678 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
5679 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent) {
5680 synchronized (mGlobalLock) {
5681 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5682 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
5683 originatingPendingIntent);
5684 }
5685 }
5686
5687 @Override
5688 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5689 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5690 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5691 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
5692 PendingIntentRecord originatingPendingIntent) {
5693 synchronized (mGlobalLock) {
5694 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5695 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5696 requestCode, startFlags, options, userId, inTask, reason,
5697 validateIncomingUser, originatingPendingIntent);
5698 }
5699 }
5700
5701 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005702 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5703 Intent intent, Bundle options, int userId) {
5704 return ActivityTaskManagerService.this.startActivityAsUser(
5705 caller, callerPacakge, intent,
5706 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5707 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5708 false /*validateIncomingUser*/);
5709 }
5710
5711 @Override
5712 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback) {
5713 synchronized (mGlobalLock) {
5714
5715 // We might change the visibilities here, so prepare an empty app transition which
5716 // might be overridden later if we actually change visibilities.
5717 final boolean wasTransitionSet =
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005718 mWindowManager.getPendingAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005719 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005720 mWindowManager.prepareAppTransition(TRANSIT_NONE,
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005721 false /* alwaysKeepCurrent */);
5722 }
5723 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5724
5725 // If there was a transition set already we don't want to interfere with it as we
5726 // might be starting it too early.
5727 if (!wasTransitionSet) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005728 mWindowManager.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005729 }
5730 }
5731 if (callback != null) {
5732 callback.run();
5733 }
5734 }
5735
5736 @Override
5737 public void notifyKeyguardTrustedChanged() {
5738 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005739 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005740 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
5741 }
5742 }
5743 }
5744
5745 /**
5746 * Called after virtual display Id is updated by
5747 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5748 * {@param vrVr2dDisplayId}.
5749 */
5750 @Override
5751 public void setVr2dDisplayId(int vr2dDisplayId) {
5752 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5753 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005754 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005755 }
5756 }
5757
5758 @Override
5759 public void setFocusedActivity(IBinder token) {
5760 synchronized (mGlobalLock) {
5761 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5762 if (r == null) {
5763 throw new IllegalArgumentException(
5764 "setFocusedActivity: No activity record matching token=" + token);
5765 }
Louis Chang19443452018-10-09 12:10:21 +08005766 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Andrii Kulianab132ee2018-07-24 22:10:21 +08005767 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005768 }
5769 }
5770 }
5771
5772 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005773 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005774 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005775 }
5776
5777 @Override
5778 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005779 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005780 }
5781
5782 @Override
5783 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005784 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005785 }
5786
5787 @Override
5788 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5789 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5790 }
5791
5792 @Override
5793 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005794 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005795 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005796
5797 @Override
5798 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5799 synchronized (mGlobalLock) {
5800 mActiveVoiceInteractionServiceComponent = component;
5801 }
5802 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005803
5804 @Override
5805 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5806 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5807 return;
5808 }
5809 synchronized (mGlobalLock) {
5810 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5811 if (types == null) {
5812 if (uid < 0) {
5813 return;
5814 }
5815 types = new ArrayMap<>();
5816 mAllowAppSwitchUids.put(userId, types);
5817 }
5818 if (uid < 0) {
5819 types.remove(type);
5820 } else {
5821 types.put(type, uid);
5822 }
5823 }
5824 }
5825
5826 @Override
5827 public void onUserStopped(int userId) {
5828 synchronized (mGlobalLock) {
5829 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5830 mAllowAppSwitchUids.remove(userId);
5831 }
5832 }
5833
5834 @Override
5835 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5836 synchronized (mGlobalLock) {
5837 return ActivityTaskManagerService.this.isGetTasksAllowed(
5838 caller, callingPid, callingUid);
5839 }
5840 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005841
5842 @Override
5843 public void onProcessAdded(WindowProcessController proc) {
5844 synchronized (mGlobalLock) {
5845 mProcessNames.put(proc.mName, proc.mUid, proc);
5846 }
5847 }
5848
5849 @Override
5850 public void onProcessRemoved(String name, int uid) {
5851 synchronized (mGlobalLock) {
5852 mProcessNames.remove(name, uid);
5853 }
5854 }
5855
5856 @Override
5857 public void onCleanUpApplicationRecord(WindowProcessController proc) {
5858 synchronized (mGlobalLock) {
5859 if (proc == mHomeProcess) {
5860 mHomeProcess = null;
5861 }
5862 if (proc == mPreviousProcess) {
5863 mPreviousProcess = null;
5864 }
5865 }
5866 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005867
5868 @Override
5869 public int getTopProcessState() {
5870 synchronized (mGlobalLock) {
5871 return mTopProcessState;
5872 }
5873 }
5874
5875 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07005876 public boolean isHeavyWeightProcess(WindowProcessController proc) {
5877 synchronized (mGlobalLock) {
5878 return proc == mHeavyWeightProcess;
5879 }
5880 }
5881
5882 @Override
5883 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5884 synchronized (mGlobalLock) {
5885 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
5886 }
5887 }
5888
5889 @Override
5890 public void finishHeavyWeightApp() {
5891 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07005892 if (mHeavyWeightProcess != null) {
5893 mHeavyWeightProcess.finishActivities();
5894 }
Wale Ogunwale53783742018-09-16 10:21:51 -07005895 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
5896 mHeavyWeightProcess);
5897 }
5898 }
5899
5900 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07005901 public boolean isSleeping() {
5902 synchronized (mGlobalLock) {
5903 return isSleepingLocked();
5904 }
5905 }
5906
5907 @Override
5908 public boolean isShuttingDown() {
5909 synchronized (mGlobalLock) {
5910 return mShuttingDown;
5911 }
5912 }
5913
5914 @Override
5915 public boolean shuttingDown(boolean booted, int timeout) {
5916 synchronized (mGlobalLock) {
5917 mShuttingDown = true;
5918 mStackSupervisor.prepareForShutdownLocked();
5919 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07005920 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005921 return mStackSupervisor.shutdownLocked(timeout);
5922 }
5923 }
5924
5925 @Override
5926 public void enableScreenAfterBoot(boolean booted) {
5927 synchronized (mGlobalLock) {
5928 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5929 SystemClock.uptimeMillis());
5930 mWindowManager.enableScreenAfterBoot();
5931 updateEventDispatchingLocked(booted);
5932 }
5933 }
5934
5935 @Override
5936 public boolean showStrictModeViolationDialog() {
5937 synchronized (mGlobalLock) {
5938 return mShowDialogs && !mSleeping && !mShuttingDown;
5939 }
5940 }
5941
5942 @Override
5943 public void showSystemReadyErrorDialogsIfNeeded() {
5944 synchronized (mGlobalLock) {
5945 try {
5946 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
5947 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
5948 + " data partition or your device will be unstable.");
5949 mUiHandler.post(() -> {
5950 if (mShowDialogs) {
5951 AlertDialog d = new BaseErrorDialog(mUiContext);
5952 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5953 d.setCancelable(false);
5954 d.setTitle(mUiContext.getText(R.string.android_system_label));
5955 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
5956 d.setButton(DialogInterface.BUTTON_POSITIVE,
5957 mUiContext.getText(R.string.ok),
5958 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5959 d.show();
5960 }
5961 });
5962 }
5963 } catch (RemoteException e) {
5964 }
5965
5966 if (!Build.isBuildConsistent()) {
5967 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
5968 mUiHandler.post(() -> {
5969 if (mShowDialogs) {
5970 AlertDialog d = new BaseErrorDialog(mUiContext);
5971 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
5972 d.setCancelable(false);
5973 d.setTitle(mUiContext.getText(R.string.android_system_label));
5974 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
5975 d.setButton(DialogInterface.BUTTON_POSITIVE,
5976 mUiContext.getText(R.string.ok),
5977 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
5978 d.show();
5979 }
5980 });
5981 }
5982 }
5983 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005984
5985 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005986 public void onProcessMapped(int pid, WindowProcessController proc) {
5987 synchronized (mGlobalLock) {
5988 mPidMap.put(pid, proc);
5989 }
5990 }
5991
5992 @Override
5993 public void onProcessUnMapped(int pid) {
5994 synchronized (mGlobalLock) {
5995 mPidMap.remove(pid);
5996 }
5997 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07005998
5999 @Override
6000 public void onPackageDataCleared(String name) {
6001 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006002 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006003 mAppWarnings.onPackageDataCleared(name);
6004 }
6005 }
6006
6007 @Override
6008 public void onPackageUninstalled(String name) {
6009 synchronized (mGlobalLock) {
6010 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006011 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006012 }
6013 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006014
6015 @Override
6016 public void onPackageAdded(String name, boolean replacing) {
6017 synchronized (mGlobalLock) {
6018 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6019 }
6020 }
6021
6022 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006023 public void onPackageReplaced(ApplicationInfo aInfo) {
6024 synchronized (mGlobalLock) {
6025 mStackSupervisor.updateActivityApplicationInfoLocked(aInfo);
6026 }
6027 }
6028
6029 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006030 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6031 synchronized (mGlobalLock) {
6032 return compatibilityInfoForPackageLocked(ai);
6033 }
6034 }
6035
Yunfan Chen75157d72018-07-27 14:47:21 +09006036 /**
6037 * Set the corresponding display information for the process global configuration. To be
6038 * called when we need to show IME on a different display.
6039 *
6040 * @param pid The process id associated with the IME window.
6041 * @param displayId The ID of the display showing the IME.
6042 */
6043 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006044 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006045 if (pid == MY_PID || pid < 0) {
6046 if (DEBUG_CONFIGURATION) {
6047 Slog.w(TAG,
6048 "Trying to update display configuration for system/invalid process.");
6049 }
6050 return;
6051 }
6052 mH.post(() -> {
6053 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006054 final ActivityDisplay activityDisplay =
6055 mStackSupervisor.getActivityDisplay(displayId);
6056 if (activityDisplay == null) {
6057 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006058 if (DEBUG_CONFIGURATION) {
6059 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006060 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006061 }
6062 return;
6063 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006064 final WindowProcessController process = mPidMap.get(pid);
6065 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006066 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006067 Slog.w(TAG, "Trying to update display configuration for invalid "
6068 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006069 }
6070 return;
6071 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006072 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006073 }
6074 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006075
Yunfan Chen75157d72018-07-27 14:47:21 +09006076 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006077
6078 @Override
6079 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6080 int requestCode, int resultCode, Intent data) {
6081 synchronized (mGlobalLock) {
6082 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6083 if (r != null && r.getStack() != null) {
6084 r.getStack().sendActivityResultLocked(callingUid, r, resultWho, requestCode,
6085 resultCode, data);
6086 }
6087 }
6088 }
6089
6090 @Override
6091 public void clearPendingResultForActivity(IBinder activityToken,
6092 WeakReference<PendingIntentRecord> pir) {
6093 synchronized (mGlobalLock) {
6094 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6095 if (r != null && r.pendingResults != null) {
6096 r.pendingResults.remove(pir);
6097 }
6098 }
6099 }
6100
6101 @Override
6102 public IIntentSender getIntentSender(int type, String packageName,
6103 int callingUid, int userId, IBinder token, String resultWho,
6104 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6105 Bundle bOptions) {
6106 synchronized (mGlobalLock) {
6107 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6108 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6109 }
6110 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006111
6112 @Override
6113 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6114 synchronized (mGlobalLock) {
6115 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6116 if (r == null) {
6117 return null;
6118 }
6119 if (r.mServiceConnectionsHolder == null) {
6120 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6121 ActivityTaskManagerService.this, r);
6122 }
6123
6124 return r.mServiceConnectionsHolder;
6125 }
6126 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006127
6128 @Override
6129 public Intent getHomeIntent() {
6130 synchronized (mGlobalLock) {
6131 return ActivityTaskManagerService.this.getHomeIntent();
6132 }
6133 }
6134
6135 @Override
6136 public boolean startHomeActivity(int userId, String reason) {
6137 synchronized (mGlobalLock) {
6138 return startHomeActivityLocked(userId, reason, DEFAULT_DISPLAY);
6139 }
6140 }
6141
6142 @Override
6143 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6144 synchronized (mGlobalLock) {
6145 if (mFactoryTest == FACTORY_TEST_OFF) {
6146 return false;
6147 }
6148 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6149 && wpc.mName.equals(mTopComponent.getPackageName())) {
6150 return true;
6151 }
6152 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6153 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6154 }
6155 }
6156
6157 @Override
6158 public void updateTopComponentForFactoryTest() {
6159 synchronized (mGlobalLock) {
6160 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6161 return;
6162 }
6163 final ResolveInfo ri = mContext.getPackageManager()
6164 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6165 final CharSequence errorMsg;
6166 if (ri != null) {
6167 final ActivityInfo ai = ri.activityInfo;
6168 final ApplicationInfo app = ai.applicationInfo;
6169 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6170 mTopAction = Intent.ACTION_FACTORY_TEST;
6171 mTopData = null;
6172 mTopComponent = new ComponentName(app.packageName, ai.name);
6173 errorMsg = null;
6174 } else {
6175 errorMsg = mContext.getResources().getText(
6176 com.android.internal.R.string.factorytest_not_system);
6177 }
6178 } else {
6179 errorMsg = mContext.getResources().getText(
6180 com.android.internal.R.string.factorytest_no_action);
6181 }
6182 if (errorMsg == null) {
6183 return;
6184 }
6185
6186 mTopAction = null;
6187 mTopData = null;
6188 mTopComponent = null;
6189 mUiHandler.post(() -> {
6190 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6191 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006192 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006193 });
6194 }
6195 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006196
6197 @Override
6198 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6199 Runnable finishInstrumentationCallback) {
6200 synchronized (mGlobalLock) {
6201 // Remove this application's activities from active lists.
6202 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(wpc);
6203
6204 wpc.clearRecentTasks();
6205 wpc.clearActivities();
6206
6207 if (wpc.isInstrumenting()) {
6208 finishInstrumentationCallback.run();
6209 }
6210
6211 mWindowManager.deferSurfaceLayout();
6212 try {
6213 if (!restarting && hasVisibleActivities
6214 && !mStackSupervisor.resumeFocusedStacksTopActivitiesLocked()) {
6215 // If there was nothing to resume, and we are not already restarting this
6216 // process, but there is a visible activity that is hosted by the process...
6217 // then make sure all visible activities are running, taking care of
6218 // restarting this process.
6219 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
6220 }
6221 } finally {
6222 mWindowManager.continueSurfaceLayout();
6223 }
6224 }
6225 }
6226
6227 @Override
6228 public void closeSystemDialogs(String reason) {
6229 enforceNotIsolatedCaller("closeSystemDialogs");
6230
6231 final int pid = Binder.getCallingPid();
6232 final int uid = Binder.getCallingUid();
6233 final long origId = Binder.clearCallingIdentity();
6234 try {
6235 synchronized (mGlobalLock) {
6236 // Only allow this from foreground processes, so that background
6237 // applications can't abuse it to prevent system UI from being shown.
6238 if (uid >= FIRST_APPLICATION_UID) {
6239 final WindowProcessController proc = mPidMap.get(pid);
6240 if (!proc.isPerceptible()) {
6241 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6242 + " from background process " + proc);
6243 return;
6244 }
6245 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006246 mWindowManager.closeSystemDialogs(reason);
6247
6248 mStackSupervisor.closeSystemDialogsLocked();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006249 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006250 // Call into AM outside the synchronized block.
6251 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006252 } finally {
6253 Binder.restoreCallingIdentity(origId);
6254 }
6255 }
6256
6257 @Override
6258 public void cleanupDisabledPackageComponents(
6259 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6260 synchronized (mGlobalLock) {
6261 // Clean-up disabled activities.
6262 if (mStackSupervisor.finishDisabledPackageActivitiesLocked(
6263 packageName, disabledClasses, true, false, userId) && booted) {
6264 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6265 mStackSupervisor.scheduleIdleLocked();
6266 }
6267
6268 // Clean-up disabled tasks
6269 getRecentTasks().cleanupDisabledPackageTasksLocked(
6270 packageName, disabledClasses, userId);
6271 }
6272 }
6273
6274 @Override
6275 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6276 int userId) {
6277 synchronized (mGlobalLock) {
6278
6279 boolean didSomething =
6280 getActivityStartController().clearPendingActivityLaunches(packageName);
6281 didSomething |= mStackSupervisor.finishDisabledPackageActivitiesLocked(packageName,
6282 null, doit, evenPersistent, userId);
6283 return didSomething;
6284 }
6285 }
6286
6287 @Override
6288 public void resumeTopActivities(boolean scheduleIdle) {
6289 synchronized (mGlobalLock) {
6290 mStackSupervisor.resumeFocusedStacksTopActivitiesLocked();
6291 if (scheduleIdle) {
6292 mStackSupervisor.scheduleIdleLocked();
6293 }
6294 }
6295 }
6296
6297 @Override
6298 public void preBindApplication(WindowProcessController wpc) {
6299 synchronized (mGlobalLock) {
6300 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6301 }
6302 }
6303
6304 @Override
6305 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6306 synchronized (mGlobalLock) {
6307 return mStackSupervisor.attachApplicationLocked(wpc);
6308 }
6309 }
6310
6311 @Override
6312 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6313 try {
6314 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6315 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6316 }
6317 } catch (RemoteException ex) {
6318 throw new SecurityException("Fail to check is caller a privileged app", ex);
6319 }
6320
6321 synchronized (mGlobalLock) {
6322 final long ident = Binder.clearCallingIdentity();
6323 try {
6324 if (mAmInternal.shouldConfirmCredentials(userId)) {
6325 if (mKeyguardController.isKeyguardLocked()) {
6326 // Showing launcher to avoid user entering credential twice.
6327 startHomeActivity(currentUserId, "notifyLockedProfile");
6328 }
6329 mStackSupervisor.lockAllProfileTasks(userId);
6330 }
6331 } finally {
6332 Binder.restoreCallingIdentity(ident);
6333 }
6334 }
6335 }
6336
6337 @Override
6338 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6339 mAmInternal.enforceCallingPermission(
6340 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6341
6342 synchronized (mGlobalLock) {
6343 final long ident = Binder.clearCallingIdentity();
6344 try {
6345 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6346 FLAG_ACTIVITY_TASK_ON_HOME);
6347 ActivityOptions activityOptions = options != null
6348 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
6349 activityOptions.setLaunchTaskId(
6350 mStackSupervisor.getDefaultDisplayHomeActivity().getTask().taskId);
6351 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6352 UserHandle.CURRENT);
6353 } finally {
6354 Binder.restoreCallingIdentity(ident);
6355 }
6356 }
6357 }
6358
6359 @Override
6360 public void writeActivitiesToProto(ProtoOutputStream proto) {
6361 synchronized (mGlobalLock) {
6362 // The output proto of "activity --proto activities"
6363 // is ActivityManagerServiceDumpActivitiesProto
6364 mStackSupervisor.writeToProto(proto,
6365 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6366 }
6367 }
6368
6369 @Override
6370 public void saveANRState(String reason) {
6371 synchronized (mGlobalLock) {
6372 final StringWriter sw = new StringWriter();
6373 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6374 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6375 if (reason != null) {
6376 pw.println(" Reason: " + reason);
6377 }
6378 pw.println();
6379 getActivityStartController().dump(pw, " ", null);
6380 pw.println();
6381 pw.println("-------------------------------------------------------------------------------");
6382 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6383 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6384 "" /* header */);
6385 pw.println();
6386 pw.close();
6387
6388 mLastANRState = sw.toString();
6389 }
6390 }
6391
6392 @Override
6393 public void clearSavedANRState() {
6394 synchronized (mGlobalLock) {
6395 mLastANRState = null;
6396 }
6397 }
6398
6399 @Override
6400 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6401 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6402 synchronized (mGlobalLock) {
6403 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6404 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6405 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6406 dumpLastANRLocked(pw);
6407 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6408 dumpLastANRTracesLocked(pw);
6409 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6410 dumpActivityStarterLocked(pw, dumpPackage);
6411 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6412 dumpActivityContainersLocked(pw);
6413 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6414 if (getRecentTasks() != null) {
6415 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6416 }
6417 }
6418 }
6419 }
6420
6421 @Override
6422 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6423 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6424 int wakefulness) {
6425 synchronized (mGlobalLock) {
6426 if (mHomeProcess != null && (dumpPackage == null
6427 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6428 if (needSep) {
6429 pw.println();
6430 needSep = false;
6431 }
6432 pw.println(" mHomeProcess: " + mHomeProcess);
6433 }
6434 if (mPreviousProcess != null && (dumpPackage == null
6435 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6436 if (needSep) {
6437 pw.println();
6438 needSep = false;
6439 }
6440 pw.println(" mPreviousProcess: " + mPreviousProcess);
6441 }
6442 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6443 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6444 StringBuilder sb = new StringBuilder(128);
6445 sb.append(" mPreviousProcessVisibleTime: ");
6446 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6447 pw.println(sb);
6448 }
6449 if (mHeavyWeightProcess != null && (dumpPackage == null
6450 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6451 if (needSep) {
6452 pw.println();
6453 needSep = false;
6454 }
6455 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6456 }
6457 if (dumpPackage == null) {
6458 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
6459 mStackSupervisor.dumpDisplayConfigs(pw, " ");
6460 }
6461 if (dumpAll) {
6462 if (dumpPackage == null) {
6463 pw.println(" mConfigWillChange: "
6464 + getTopDisplayFocusedStack().mConfigWillChange);
6465 }
6466 if (mCompatModePackages.getPackages().size() > 0) {
6467 boolean printed = false;
6468 for (Map.Entry<String, Integer> entry
6469 : mCompatModePackages.getPackages().entrySet()) {
6470 String pkg = entry.getKey();
6471 int mode = entry.getValue();
6472 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6473 continue;
6474 }
6475 if (!printed) {
6476 pw.println(" mScreenCompatPackages:");
6477 printed = true;
6478 }
6479 pw.println(" " + pkg + ": " + mode);
6480 }
6481 }
6482 }
6483
6484 if (dumpPackage == null) {
6485 pw.println(" mWakefulness="
6486 + PowerManagerInternal.wakefulnessToString(wakefulness));
6487 pw.println(" mSleepTokens=" + mStackSupervisor.mSleepTokens);
6488 if (mRunningVoice != null) {
6489 pw.println(" mRunningVoice=" + mRunningVoice);
6490 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6491 }
6492 pw.println(" mSleeping=" + mSleeping);
6493 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6494 pw.println(" mVrController=" + mVrController);
6495 }
6496 if (mCurAppTimeTracker != null) {
6497 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6498 }
6499 if (mAllowAppSwitchUids.size() > 0) {
6500 boolean printed = false;
6501 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6502 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6503 for (int j = 0; j < types.size(); j++) {
6504 if (dumpPackage == null ||
6505 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6506 if (needSep) {
6507 pw.println();
6508 needSep = false;
6509 }
6510 if (!printed) {
6511 pw.println(" mAllowAppSwitchUids:");
6512 printed = true;
6513 }
6514 pw.print(" User ");
6515 pw.print(mAllowAppSwitchUids.keyAt(i));
6516 pw.print(": Type ");
6517 pw.print(types.keyAt(j));
6518 pw.print(" = ");
6519 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6520 pw.println();
6521 }
6522 }
6523 }
6524 }
6525 if (dumpPackage == null) {
6526 if (mController != null) {
6527 pw.println(" mController=" + mController
6528 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6529 }
6530 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6531 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6532 }
6533
6534 return needSep;
6535 }
6536 }
6537
6538 @Override
6539 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage) {
6540 synchronized (mGlobalLock) {
6541 if (dumpPackage == null) {
6542 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6543 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
6544 writeSleepStateToProto(proto);
6545 if (mController != null) {
6546 final long token = proto.start(CONTROLLER);
6547 proto.write(CONTROLLER, mController.toString());
6548 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6549 proto.end(token);
6550 }
6551 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6552 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6553 }
6554
6555 if (mHomeProcess != null && (dumpPackage == null
6556 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006557 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006558 }
6559
6560 if (mPreviousProcess != null && (dumpPackage == null
6561 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006562 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006563 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6564 }
6565
6566 if (mHeavyWeightProcess != null && (dumpPackage == null
6567 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006568 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006569 }
6570
6571 for (Map.Entry<String, Integer> entry
6572 : mCompatModePackages.getPackages().entrySet()) {
6573 String pkg = entry.getKey();
6574 int mode = entry.getValue();
6575 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6576 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6577 proto.write(PACKAGE, pkg);
6578 proto.write(MODE, mode);
6579 proto.end(compatToken);
6580 }
6581 }
6582
6583 if (mCurAppTimeTracker != null) {
6584 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6585 }
6586
6587 }
6588 }
6589
6590 @Override
6591 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6592 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6593 boolean dumpFocusedStackOnly) {
6594 synchronized (mGlobalLock) {
6595 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6596 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6597 }
6598 }
6599
6600 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006601 public void dumpForOom(PrintWriter pw) {
6602 synchronized (mGlobalLock) {
6603 pw.println(" mHomeProcess: " + mHomeProcess);
6604 pw.println(" mPreviousProcess: " + mPreviousProcess);
6605 if (mHeavyWeightProcess != null) {
6606 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6607 }
6608 }
6609 }
6610
6611 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006612 public boolean canGcNow() {
6613 synchronized (mGlobalLock) {
6614 return isSleeping() || mStackSupervisor.allResumedActivitiesIdle();
6615 }
6616 }
6617
6618 @Override
6619 public WindowProcessController getTopApp() {
6620 synchronized (mGlobalLock) {
6621 final ActivityRecord top = mStackSupervisor.getTopResumedActivity();
6622 return top != null ? top.app : null;
6623 }
6624 }
6625
6626 @Override
6627 public void rankTaskLayersIfNeeded() {
6628 synchronized (mGlobalLock) {
6629 if (mStackSupervisor != null) {
6630 mStackSupervisor.rankTaskLayersIfNeeded();
6631 }
6632 }
6633 }
6634
6635 @Override
6636 public void scheduleDestroyAllActivities(String reason) {
6637 synchronized (mGlobalLock) {
6638 mStackSupervisor.scheduleDestroyAllActivities(null, reason);
6639 }
6640 }
6641
6642 @Override
6643 public void removeUser(int userId) {
6644 synchronized (mGlobalLock) {
6645 mStackSupervisor.removeUserLocked(userId);
6646 }
6647 }
6648
6649 @Override
6650 public boolean switchUser(int userId, UserState userState) {
6651 synchronized (mGlobalLock) {
6652 return mStackSupervisor.switchUserLocked(userId, userState);
6653 }
6654 }
6655
6656 @Override
6657 public void onHandleAppCrash(WindowProcessController wpc) {
6658 synchronized (mGlobalLock) {
6659 mStackSupervisor.handleAppCrashLocked(wpc);
6660 }
6661 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006662
6663 @Override
6664 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6665 synchronized (mGlobalLock) {
6666 return mStackSupervisor.finishTopCrashedActivitiesLocked(crashedApp, reason);
6667 }
6668 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006669
6670 @Override
6671 public void onUidActive(int uid, int procState) {
6672 synchronized (mGlobalLock) {
6673 mActiveUids.put(uid, procState);
6674 }
6675 }
6676
6677 @Override
6678 public void onUidInactive(int uid) {
6679 synchronized (mGlobalLock) {
6680 mActiveUids.remove(uid);
6681 }
6682 }
6683
6684 @Override
6685 public void onActiveUidsCleared() {
6686 synchronized (mGlobalLock) {
6687 mActiveUids.clear();
6688 }
6689 }
6690
6691 @Override
6692 public void onUidProcStateChanged(int uid, int procState) {
6693 synchronized (mGlobalLock) {
6694 if (mActiveUids.get(uid) != null) {
6695 mActiveUids.put(uid, procState);
6696 }
6697 }
6698 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006699
6700 @Override
6701 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6702 synchronized (mGlobalLock) {
6703 mPendingTempWhitelist.put(uid, tag);
6704 }
6705 }
6706
6707 @Override
6708 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6709 synchronized (mGlobalLock) {
6710 mPendingTempWhitelist.remove(uid);
6711 }
6712 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006713
6714 @Override
6715 public boolean handleAppCrashInActivityController(String processName, int pid,
6716 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6717 Runnable killCrashingAppCallback) {
6718 synchronized (mGlobalLock) {
6719 if (mController == null) {
6720 return false;
6721 }
6722
6723 try {
6724 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6725 stackTrace)) {
6726 killCrashingAppCallback.run();
6727 return true;
6728 }
6729 } catch (RemoteException e) {
6730 mController = null;
6731 Watchdog.getInstance().setActivityController(null);
6732 }
6733 return false;
6734 }
6735 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006736
6737 @Override
6738 public void removeRecentTasksByPackageName(String packageName, int userId) {
6739 synchronized (mGlobalLock) {
6740 mRecentTasks.removeTasksByPackageName(packageName, userId);
6741 }
6742 }
6743
6744 @Override
6745 public void cleanupRecentTasksForUser(int userId) {
6746 synchronized (mGlobalLock) {
6747 mRecentTasks.cleanupLocked(userId);
6748 }
6749 }
6750
6751 @Override
6752 public void loadRecentTasksForUser(int userId) {
6753 synchronized (mGlobalLock) {
6754 mRecentTasks.loadUserRecentsLocked(userId);
6755 }
6756 }
6757
6758 @Override
6759 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6760 synchronized (mGlobalLock) {
6761 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6762 }
6763 }
6764
6765 @Override
6766 public void flushRecentTasks() {
6767 mRecentTasks.flush();
6768 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006769
6770 @Override
6771 public WindowProcessController getHomeProcess() {
6772 synchronized (mGlobalLock) {
6773 return mHomeProcess;
6774 }
6775 }
6776
6777 @Override
6778 public WindowProcessController getPreviousProcess() {
6779 synchronized (mGlobalLock) {
6780 return mPreviousProcess;
6781 }
6782 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006783
6784 @Override
6785 public void clearLockedTasks(String reason) {
6786 synchronized (mGlobalLock) {
6787 getLockTaskController().clearLockedTasks(reason);
6788 }
6789 }
6790
6791 @Override
6792 public void updateUserConfiguration() {
6793 synchronized (mGlobalLock) {
6794 final Configuration configuration = new Configuration(getGlobalConfiguration());
6795 final int currentUserId = mAmInternal.getCurrentUserId();
6796 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6797 configuration, currentUserId, Settings.System.canWrite(mContext));
6798 updateConfigurationLocked(configuration, null /* starting */,
6799 false /* initLocale */, false /* persistent */, currentUserId,
6800 false /* deferResume */);
6801 }
6802 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006803
6804 @Override
6805 public boolean canShowErrorDialogs() {
6806 synchronized (mGlobalLock) {
6807 return mShowDialogs && !mSleeping && !mShuttingDown
6808 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6809 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6810 mAmInternal.getCurrentUserId())
6811 && !(UserManager.isDeviceInDemoMode(mContext)
6812 && mAmInternal.getCurrentUser().isDemo());
6813 }
6814 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07006815 }
Wale Ogunwale65ebd952018-04-25 15:41:44 -07006816}