blob: 6a495d4e96831918ae9e64033e7486574d6946a2 [file] [log] [blame]
Wale Ogunwale65ebd952018-04-25 15:41:44 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
Wale Ogunwale59507092018-10-29 09:00:30 -070017package com.android.server.wm;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070018
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070019import static android.Manifest.permission.BIND_VOICE_INTERACTION;
20import static android.Manifest.permission.CHANGE_CONFIGURATION;
21import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
22import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070023import static android.Manifest.permission.MANAGE_ACTIVITY_STACKS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070024import static android.Manifest.permission.READ_FRAME_BUFFER;
25import static android.Manifest.permission.REMOVE_TASKS;
26import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070027import static android.Manifest.permission.STOP_APP_SWITCHES;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070028import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
Wale Ogunwalebff2df42018-10-18 17:09:19 -070029import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
Evan Rosky4505b352018-09-06 11:20:40 -070030import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
Yunfan Chen79b96062018-10-17 12:45:23 -070031import static android.app.ActivityTaskManager.INVALID_TASK_ID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070032import static android.app.ActivityTaskManager.RESIZE_MODE_PRESERVE_WINDOW;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070033import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
34import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070035import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
36import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070037import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
38import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070039import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
Wale Ogunwale65ebd952018-04-25 15:41:44 -070040import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
Wale Ogunwale31913b52018-10-13 08:29:31 -070041import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070042import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
Wale Ogunwale31913b52018-10-13 08:29:31 -070043import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
Wale Ogunwale214f3482018-10-04 11:00:47 -070044import static android.content.pm.ApplicationInfo.FLAG_FACTORY_TEST;
Wale Ogunwale342fbe92018-10-09 08:44:10 -070045import static android.content.pm.ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070046import static android.content.pm.PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS;
47import static android.content.pm.PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT;
Evan Rosky4505b352018-09-06 11:20:40 -070048import static android.content.pm.PackageManager.FEATURE_PC;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070049import static android.content.pm.PackageManager.FEATURE_PICTURE_IN_PICTURE;
Wale Ogunwaled0412b32018-05-08 09:25:50 -070050import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070051import static android.content.res.Configuration.UI_MODE_TYPE_TELEVISION;
52import static android.os.Build.VERSION_CODES.N;
Wale Ogunwale214f3482018-10-04 11:00:47 -070053import static android.os.FactoryTest.FACTORY_TEST_HIGH_LEVEL;
54import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
55import static android.os.FactoryTest.FACTORY_TEST_OFF;
Wale Ogunwale31913b52018-10-13 08:29:31 -070056import static android.os.Process.FIRST_APPLICATION_UID;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070057import static android.os.Process.SYSTEM_UID;
Evan Rosky4505b352018-09-06 11:20:40 -070058import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
Wale Ogunwalea6191b42018-05-09 07:41:32 -070059import static android.provider.Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT;
60import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES;
61import static android.provider.Settings.Global.DEVELOPMENT_FORCE_RTL;
Evan Rosky4505b352018-09-06 11:20:40 -070062import static android.provider.Settings.Global.HIDE_ERROR_DIALOGS;
63import static android.provider.Settings.System.FONT_SCALE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070064import static android.service.voice.VoiceInteractionSession.SHOW_SOURCE_APPLICATION;
Alison Cichowlas3e340502018-08-07 17:15:01 -040065import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070066import static android.view.Display.DEFAULT_DISPLAY;
67import static android.view.Display.INVALID_DISPLAY;
Wale Ogunwale6767eae2018-05-03 15:52:51 -070068import static android.view.WindowManager.TRANSIT_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -070069import static android.view.WindowManager.TRANSIT_TASK_IN_PLACE;
Evan Rosky4505b352018-09-06 11:20:40 -070070
Yunfan Chen79b96062018-10-17 12:45:23 -070071import static com.android.server.am.ActivityManagerService.ANR_TRACE_DIR;
72import static com.android.server.am.ActivityManagerService.MY_PID;
73import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS;
74import static com.android.server.am.ActivityManagerService.dumpStackTraces;
Wale Ogunwale31913b52018-10-13 08:29:31 -070075import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONFIG_WILL_CHANGE;
76import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CONTROLLER;
77import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.CURRENT_TRACKER;
78import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Controller.IS_A_MONKEY;
79import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GLOBAL_CONFIGURATION;
80import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.GOING_TO_SLEEP;
81import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HEAVY_WEIGHT_PROC;
82import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
83import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
84import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
Yunfan Chen279f5582018-12-12 15:24:50 -080085import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
Wale Ogunwale31913b52018-10-13 08:29:31 -070086import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
Yunfan Chen279f5582018-12-12 15:24:50 -080087import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
88import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
Wale Ogunwale59507092018-10-29 09:00:30 -070089import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
90import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
Wale Ogunwale59507092018-10-29 09:00:30 -070091import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
92import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
93import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
94import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
95import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
96import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
97import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
98import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
99import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
100import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
101import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
102import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
103import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
104import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
105import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
106import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
107import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
108import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
109import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
110import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
111import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
Evan Rosky4505b352018-09-06 11:20:40 -0700112import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
113import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
114import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
115import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_STRUCTURE;
wilsonshihe7903ea2018-09-26 16:17:59 +0800116import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
117import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700118import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
119import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800120import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_ONLY;
121import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
wilsonshihe7903ea2018-09-26 16:17:59 +0800122import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
123import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
124import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700125
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700126import android.Manifest;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700127import android.annotation.NonNull;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700128import android.annotation.Nullable;
129import android.annotation.UserIdInt;
130import android.app.Activity;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700131import android.app.ActivityManager;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700132import android.app.ActivityManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700133import android.app.ActivityOptions;
134import android.app.ActivityTaskManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700135import android.app.ActivityThread;
136import android.app.AlertDialog;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700137import android.app.AppGlobals;
Evan Rosky4505b352018-09-06 11:20:40 -0700138import android.app.Dialog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700139import android.app.IActivityController;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700140import android.app.IActivityTaskManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700141import android.app.IApplicationThread;
142import android.app.IAssistDataReceiver;
Wale Ogunwale53783742018-09-16 10:21:51 -0700143import android.app.INotificationManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700144import android.app.ITaskStackListener;
Wale Ogunwale53783742018-09-16 10:21:51 -0700145import android.app.Notification;
146import android.app.NotificationManager;
147import android.app.PendingIntent;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700148import android.app.PictureInPictureParams;
149import android.app.ProfilerInfo;
150import android.app.RemoteAction;
151import android.app.WaitResult;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700152import android.app.WindowConfiguration;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700153import android.app.admin.DevicePolicyCache;
154import android.app.assist.AssistContent;
155import android.app.assist.AssistStructure;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700156import android.app.usage.UsageStatsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700157import android.content.ActivityNotFoundException;
158import android.content.ComponentName;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700159import android.content.ContentResolver;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700160import android.content.Context;
Evan Rosky4505b352018-09-06 11:20:40 -0700161import android.content.DialogInterface;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700162import android.content.IIntentSender;
163import android.content.Intent;
164import android.content.pm.ActivityInfo;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700165import android.content.pm.ApplicationInfo;
Yunfan Chen75157d72018-07-27 14:47:21 +0900166import android.content.pm.ConfigurationInfo;
Evan Rosky4505b352018-09-06 11:20:40 -0700167import android.content.pm.IPackageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700168import android.content.pm.PackageManager;
Evan Rosky4505b352018-09-06 11:20:40 -0700169import android.content.pm.PackageManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700170import android.content.pm.ParceledListSlice;
171import android.content.pm.ResolveInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -0700172import android.content.res.CompatibilityInfo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700173import android.content.res.Configuration;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700174import android.content.res.Resources;
Evan Rosky4505b352018-09-06 11:20:40 -0700175import android.database.ContentObserver;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700176import android.graphics.Bitmap;
177import android.graphics.Point;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700178import android.graphics.Rect;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700179import android.metrics.LogMaker;
180import android.net.Uri;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700181import android.os.Binder;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700182import android.os.Build;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700183import android.os.Bundle;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700184import android.os.FactoryTest;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700185import android.os.FileUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700186import android.os.Handler;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700187import android.os.IBinder;
Evan Rosky4505b352018-09-06 11:20:40 -0700188import android.os.IUserManager;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700189import android.os.LocaleList;
Riddle Hsud93a6c42018-11-29 21:50:06 +0800190import android.os.Looper;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700191import android.os.Message;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700192import android.os.PersistableBundle;
Evan Rosky4505b352018-09-06 11:20:40 -0700193import android.os.PowerManager;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700194import android.os.PowerManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700195import android.os.RemoteException;
Evan Rosky4505b352018-09-06 11:20:40 -0700196import android.os.ServiceManager;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700197import android.os.StrictMode;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700198import android.os.SystemClock;
199import android.os.SystemProperties;
Evan Rosky4505b352018-09-06 11:20:40 -0700200import android.os.Trace;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700201import android.os.UpdateLock;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700202import android.os.UserHandle;
Evan Rosky4505b352018-09-06 11:20:40 -0700203import android.os.UserManager;
204import android.os.WorkSource;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700205import android.os.storage.IStorageManager;
206import android.os.storage.StorageManager;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700207import android.provider.Settings;
208import android.service.voice.IVoiceInteractionSession;
209import android.service.voice.VoiceInteractionManagerInternal;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900210import android.sysprop.DisplayProperties;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700211import android.telecom.TelecomManager;
212import android.text.TextUtils;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700213import android.text.format.Time;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700214import android.util.ArrayMap;
215import android.util.EventLog;
216import android.util.Log;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700217import android.util.Slog;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700218import android.util.SparseArray;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700219import android.util.SparseIntArray;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700220import android.util.StatsLog;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700221import android.util.TimeUtils;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700222import android.util.proto.ProtoOutputStream;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700223import android.view.IRecentsAnimationRunner;
224import android.view.RemoteAnimationAdapter;
225import android.view.RemoteAnimationDefinition;
Evan Rosky4505b352018-09-06 11:20:40 -0700226import android.view.WindowManager;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700227
Evan Rosky4505b352018-09-06 11:20:40 -0700228import com.android.internal.R;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700229import com.android.internal.annotations.VisibleForTesting;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700230import com.android.internal.app.AssistUtils;
Evan Rosky4505b352018-09-06 11:20:40 -0700231import com.android.internal.app.IAppOpsService;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700232import com.android.internal.app.IVoiceInteractor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700233import com.android.internal.app.ProcessMap;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700234import com.android.internal.logging.MetricsLogger;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700235import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Wale Ogunwale53783742018-09-16 10:21:51 -0700236import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
237import com.android.internal.notification.SystemNotificationChannels;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700238import com.android.internal.os.TransferPipe;
Evan Rosky4505b352018-09-06 11:20:40 -0700239import com.android.internal.os.logging.MetricsLoggerWrapper;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700240import com.android.internal.policy.IKeyguardDismissCallback;
241import com.android.internal.policy.KeyguardDismissCallback;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700242import com.android.internal.util.ArrayUtils;
243import com.android.internal.util.FastPrintWriter;
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700244import com.android.internal.util.Preconditions;
Wale Ogunwale53783742018-09-16 10:21:51 -0700245import com.android.internal.util.function.pooled.PooledLambda;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700246import com.android.server.AttributeCache;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700247import com.android.server.LocalServices;
248import com.android.server.SystemService;
Evan Rosky4505b352018-09-06 11:20:40 -0700249import com.android.server.SystemServiceManager;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800250import com.android.server.UiThread;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700251import com.android.server.Watchdog;
Wale Ogunwale59507092018-10-29 09:00:30 -0700252import com.android.server.am.ActivityManagerService;
253import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
254import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
255import com.android.server.am.AppTimeTracker;
256import com.android.server.am.BaseErrorDialog;
257import com.android.server.am.EventLogTags;
258import com.android.server.am.PendingIntentController;
259import com.android.server.am.PendingIntentRecord;
260import com.android.server.am.UserState;
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900261import com.android.server.appop.AppOpsService;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700262import com.android.server.firewall.IntentFirewall;
Evan Rosky4505b352018-09-06 11:20:40 -0700263import com.android.server.pm.UserManagerService;
264import com.android.server.uri.UriGrantsManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700265import com.android.server.vr.VrManagerInternal;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700266
Wale Ogunwale31913b52018-10-13 08:29:31 -0700267import java.io.BufferedReader;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700268import java.io.File;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700269import java.io.FileDescriptor;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700270import java.io.FileOutputStream;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700271import java.io.FileReader;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700272import java.io.IOException;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700273import java.io.PrintWriter;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700274import java.io.StringWriter;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700275import java.lang.ref.WeakReference;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700276import java.text.DateFormat;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700277import java.util.ArrayList;
Wale Ogunwale27c48ae2018-10-25 19:01:01 -0700278import java.util.Arrays;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700279import java.util.Date;
Alison Cichowlas3e340502018-08-07 17:15:01 -0400280import java.util.HashMap;
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700281import java.util.HashSet;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700282import java.util.List;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700283import java.util.Locale;
Wale Ogunwale31913b52018-10-13 08:29:31 -0700284import java.util.Map;
285import java.util.Set;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700286
287/**
288 * System service for managing activities and their containers (task, stacks, displays,... ).
289 *
290 * {@hide}
291 */
292public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
Wale Ogunwale98875612018-10-12 07:53:02 -0700293 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityTaskManagerService" : TAG_ATM;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700294 private static final String TAG_STACK = TAG + POSTFIX_STACK;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700295 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
296 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE;
297 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
298 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;
299 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700300 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700301
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700302 // How long we wait until we timeout on key dispatching.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700303 public static final int KEY_DISPATCHING_TIMEOUT_MS = 5 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700304 // How long we wait until we timeout on key dispatching during instrumentation.
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700305 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS = 60 * 1000;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700306
Wale Ogunwale98875612018-10-12 07:53:02 -0700307 /** Used to indicate that an app transition should be animated. */
308 static final boolean ANIMATE = true;
309
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700310 /** Hardware-reported OpenGLES version. */
311 final int GL_ES_VERSION;
312
Wale Ogunwale31913b52018-10-13 08:29:31 -0700313 public static final String DUMP_ACTIVITIES_CMD = "activities" ;
314 public static final String DUMP_ACTIVITIES_SHORT_CMD = "a" ;
315 public static final String DUMP_LASTANR_CMD = "lastanr" ;
316 public static final String DUMP_LASTANR_TRACES_CMD = "lastanr-traces" ;
317 public static final String DUMP_STARTER_CMD = "starter" ;
318 public static final String DUMP_CONTAINERS_CMD = "containers" ;
319 public static final String DUMP_RECENTS_CMD = "recents" ;
320 public static final String DUMP_RECENTS_SHORT_CMD = "r" ;
321
Wale Ogunwale64258362018-10-16 15:13:37 -0700322 /** This activity is not being relaunched, or being relaunched for a non-resize reason. */
323 public static final int RELAUNCH_REASON_NONE = 0;
324 /** This activity is being relaunched due to windowing mode change. */
325 public static final int RELAUNCH_REASON_WINDOWING_MODE_RESIZE = 1;
326 /** This activity is being relaunched due to a free-resize operation. */
327 public static final int RELAUNCH_REASON_FREE_RESIZE = 2;
328
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700329 Context mContext;
Wale Ogunwale64258362018-10-16 15:13:37 -0700330
Wale Ogunwalef6733932018-06-27 05:14:34 -0700331 /**
332 * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
333 * change at runtime. Use mContext for non-UI purposes.
334 */
335 final Context mUiContext;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700336 final ActivityThread mSystemThread;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700337 H mH;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700338 UiHandler mUiHandler;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700339 ActivityManagerInternal mAmInternal;
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -0700340 UriGrantsManagerInternal mUgmInternal;
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700341 private PackageManagerInternal mPmInternal;
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800342 @VisibleForTesting
343 final ActivityTaskManagerInternal mInternal;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700344 PowerManagerInternal mPowerManagerInternal;
345 private UsageStatsManagerInternal mUsageStatsInternal;
346
Wale Ogunwaleee6eca12018-09-19 20:37:53 -0700347 PendingIntentController mPendingIntentController;
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700348 IntentFirewall mIntentFirewall;
349
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700350 /* Global service lock used by the package the owns this service. */
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800351 final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700352 ActivityStackSupervisor mStackSupervisor;
Wale Ogunwaled32da472018-11-16 07:19:28 -0800353 RootActivityContainer mRootActivityContainer;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700354 WindowManagerService mWindowManager;
Wale Ogunwalef6733932018-06-27 05:14:34 -0700355 private UserManagerService mUserManager;
356 private AppOpsService mAppOpsService;
Wale Ogunwalebff2df42018-10-18 17:09:19 -0700357 /** All active uids in the system. */
Wale Ogunwale9de19442018-10-18 19:05:03 -0700358 private final SparseArray<Integer> mActiveUids = new SparseArray<>();
359 private final SparseArray<String> mPendingTempWhitelist = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700360 /** All processes currently running that might have a window organized by name. */
361 final ProcessMap<WindowProcessController> mProcessNames = new ProcessMap<>();
Wale Ogunwale906f9c62018-07-23 11:23:44 -0700362 /** All processes we currently have running mapped by pid */
363 final SparseArray<WindowProcessController> mPidMap = new SparseArray<>();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700364 /** This is the process holding what we currently consider to be the "home" activity. */
365 WindowProcessController mHomeProcess;
Wale Ogunwale53783742018-09-16 10:21:51 -0700366 /** The currently running heavy-weight process, if any. */
367 WindowProcessController mHeavyWeightProcess = null;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700368 boolean mHasHeavyWeightFeature;
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700369 /**
370 * This is the process holding the activity the user last visited that is in a different process
371 * from the one they are currently in.
372 */
373 WindowProcessController mPreviousProcess;
374 /** The time at which the previous process was last visible. */
375 long mPreviousProcessVisibleTime;
376
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700377 /** List of intents that were used to start the most recent tasks. */
378 private RecentTasks mRecentTasks;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700379 /** State of external calls telling us if the device is awake or asleep. */
380 private boolean mKeyguardShown = false;
381
382 // Wrapper around VoiceInteractionServiceManager
383 private AssistUtils mAssistUtils;
384
385 // VoiceInteraction session ID that changes for each new request except when
386 // being called for multi-window assist in a single session.
387 private int mViSessionId = 1000;
388
389 // How long to wait in getAssistContextExtras for the activity and foreground services
390 // to respond with the result.
391 private static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
392
393 // How long top wait when going through the modern assist (which doesn't need to block
394 // on getting this result before starting to launch its UI).
395 private static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000;
396
397 // How long to wait in getAutofillAssistStructure() for the activity to respond with the result.
398 private static final int PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT = 2000;
399
Alison Cichowlas3e340502018-08-07 17:15:01 -0400400 // Permission tokens are used to temporarily granted a trusted app the ability to call
401 // #startActivityAsCaller. A client is expected to dump its token after this time has elapsed,
402 // showing any appropriate error messages to the user.
403 private static final long START_AS_CALLER_TOKEN_TIMEOUT =
404 10 * MINUTE_IN_MILLIS;
405
406 // How long before the service actually expires a token. This is slightly longer than
407 // START_AS_CALLER_TOKEN_TIMEOUT, to provide a buffer so clients will rarely encounter the
408 // expiration exception.
409 private static final long START_AS_CALLER_TOKEN_TIMEOUT_IMPL =
410 START_AS_CALLER_TOKEN_TIMEOUT + 2 * 1000;
411
412 // How long the service will remember expired tokens, for the purpose of providing error
413 // messaging when a client uses an expired token.
414 private static final long START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT =
415 START_AS_CALLER_TOKEN_TIMEOUT_IMPL + 20 * MINUTE_IN_MILLIS;
416
417 // Activity tokens of system activities that are delegating their call to
418 // #startActivityByCaller, keyed by the permissionToken granted to the delegate.
419 final HashMap<IBinder, IBinder> mStartActivitySources = new HashMap<>();
420
421 // Permission tokens that have expired, but we remember for error reporting.
422 final ArrayList<IBinder> mExpiredStartAsCallerTokens = new ArrayList<>();
423
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700424 private final ArrayList<PendingAssistExtras> mPendingAssistExtras = new ArrayList<>();
425
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700426 // Keeps track of the active voice interaction service component, notified from
427 // VoiceInteractionManagerService
428 ComponentName mActiveVoiceInteractionServiceComponent;
429
Wale Ogunwalee2172292018-10-25 10:11:10 -0700430 VrController mVrController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700431 KeyguardController mKeyguardController;
432 private final ClientLifecycleManager mLifecycleManager;
433 private TaskChangeNotificationController mTaskChangeNotificationController;
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700434 /** The controller for all operations related to locktask. */
435 private LockTaskController mLockTaskController;
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700436 private ActivityStartController mActivityStartController;
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700437
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700438 boolean mSuppressResizeConfigChanges;
439
440 private final UpdateConfigurationResult mTmpUpdateConfigurationResult =
441 new UpdateConfigurationResult();
442
443 static final class UpdateConfigurationResult {
444 // Configuration changes that were updated.
445 int changes;
446 // If the activity was relaunched to match the new configuration.
447 boolean activityRelaunched;
448
449 void reset() {
450 changes = 0;
451 activityRelaunched = false;
452 }
453 }
454
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700455 /** Current sequencing integer of the configuration, for skipping old configurations. */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700456 private int mConfigurationSeq;
457 // To cache the list of supported system locales
458 private String[] mSupportedSystemLocales = null;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700459
460 /**
461 * Temp object used when global and/or display override configuration is updated. It is also
462 * sent to outer world instead of {@link #getGlobalConfiguration} because we don't trust
463 * anyone...
464 */
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700465 private Configuration mTempConfig = new Configuration();
466
Wale Ogunwalef6733932018-06-27 05:14:34 -0700467 /** Temporary to avoid allocations. */
468 final StringBuilder mStringBuilder = new StringBuilder(256);
469
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700470 // Amount of time after a call to stopAppSwitches() during which we will
471 // prevent further untrusted switches from happening.
472 private static final long APP_SWITCH_DELAY_TIME = 5 * 1000;
473
474 /**
475 * The time at which we will allow normal application switches again,
476 * after a call to {@link #stopAppSwitches()}.
477 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700478 private long mAppSwitchesAllowedTime;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700479 /**
480 * This is set to true after the first switch after mAppSwitchesAllowedTime
481 * is set; any switches after that will clear the time.
482 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700483 private boolean mDidAppSwitch;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700484
485 IActivityController mController = null;
486 boolean mControllerIsAMonkey = false;
487
Wale Ogunwale214f3482018-10-04 11:00:47 -0700488 final int mFactoryTest;
489
490 /** Used to control how we initialize the service. */
491 ComponentName mTopComponent;
492 String mTopAction = Intent.ACTION_MAIN;
493 String mTopData;
494
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800495 /** Profiling app information. */
496 String mProfileApp = null;
497 WindowProcessController mProfileProc = null;
498 ProfilerInfo mProfilerInfo = null;
499
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700500 /**
Wale Ogunwale31913b52018-10-13 08:29:31 -0700501 * Dump of the activity state at the time of the last ANR. Cleared after
502 * {@link WindowManagerService#LAST_ANR_LIFETIME_DURATION_MSECS}
503 */
504 String mLastANRState;
505
506 /**
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700507 * Used to retain an update lock when the foreground activity is in
508 * immersive mode.
509 */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700510 private final UpdateLock mUpdateLock = new UpdateLock("immersive");
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700511
512 /**
513 * Packages that are being allowed to perform unrestricted app switches. Mapping is
514 * User -> Type -> uid.
515 */
516 final SparseArray<ArrayMap<String, Integer>> mAllowAppSwitchUids = new SparseArray<>();
517
518 /** The dimensions of the thumbnails in the Recents UI. */
Wale Ogunwalef6733932018-06-27 05:14:34 -0700519 private int mThumbnailWidth;
520 private int mThumbnailHeight;
521 private float mFullscreenThumbnailScale;
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700522
523 /**
524 * Flag that indicates if multi-window is enabled.
525 *
526 * For any particular form of multi-window to be enabled, generic multi-window must be enabled
527 * in {@link com.android.internal.R.bool#config_supportsMultiWindow} config or
528 * {@link Settings.Global#DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES} development option set.
529 * At least one of the forms of multi-window must be enabled in order for this flag to be
530 * initialized to 'true'.
531 *
532 * @see #mSupportsSplitScreenMultiWindow
533 * @see #mSupportsFreeformWindowManagement
534 * @see #mSupportsPictureInPicture
535 * @see #mSupportsMultiDisplay
536 */
537 boolean mSupportsMultiWindow;
538 boolean mSupportsSplitScreenMultiWindow;
539 boolean mSupportsFreeformWindowManagement;
540 boolean mSupportsPictureInPicture;
541 boolean mSupportsMultiDisplay;
542 boolean mForceResizableActivities;
543
544 final List<ActivityTaskManagerInternal.ScreenObserver> mScreenObservers = new ArrayList<>();
545
546 // VR Vr2d Display Id.
547 int mVr2dDisplayId = INVALID_DISPLAY;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700548
Wale Ogunwalef6733932018-06-27 05:14:34 -0700549 /**
550 * Set while we are wanting to sleep, to prevent any
551 * activities from being started/resumed.
552 *
553 * TODO(b/33594039): Clarify the actual state transitions represented by mSleeping.
554 *
555 * Currently mSleeping is set to true when transitioning into the sleep state, and remains true
556 * while in the sleep state until there is a pending transition out of sleep, in which case
557 * mSleeping is set to false, and remains false while awake.
558 *
559 * Whether mSleeping can quickly toggled between true/false without the device actually
560 * display changing states is undefined.
561 */
562 private boolean mSleeping = false;
563
564 /**
565 * The process state used for processes that are running the top activities.
566 * This changes between TOP and TOP_SLEEPING to following mSleeping.
567 */
568 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
569
570 // Whether we should show our dialogs (ANR, crash, etc) or just perform their default action
571 // automatically. Important for devices without direct input devices.
572 private boolean mShowDialogs = true;
573
574 /** Set if we are shutting down the system, similar to sleeping. */
575 boolean mShuttingDown = false;
576
577 /**
578 * We want to hold a wake lock while running a voice interaction session, since
579 * this may happen with the screen off and we need to keep the CPU running to
580 * be able to continue to interact with the user.
581 */
582 PowerManager.WakeLock mVoiceWakeLock;
583
584 /**
585 * Set while we are running a voice interaction. This overrides sleeping while it is active.
586 */
587 IVoiceInteractionSession mRunningVoice;
588
589 /**
590 * The last resumed activity. This is identical to the current resumed activity most
591 * of the time but could be different when we're pausing one activity before we resume
592 * another activity.
593 */
594 ActivityRecord mLastResumedActivity;
595
596 /**
597 * The activity that is currently being traced as the active resumed activity.
598 *
599 * @see #updateResumedAppTrace
600 */
601 private @Nullable ActivityRecord mTracedResumedActivity;
602
603 /** If non-null, we are tracking the time the user spends in the currently focused app. */
604 AppTimeTracker mCurAppTimeTracker;
605
Wale Ogunwale008163e2018-07-23 23:11:08 -0700606 private AppWarnings mAppWarnings;
607
Wale Ogunwale53783742018-09-16 10:21:51 -0700608 /**
609 * Packages that the user has asked to have run in screen size
610 * compatibility mode instead of filling the screen.
611 */
612 CompatModePackages mCompatModePackages;
613
Wale Ogunwalef6733932018-06-27 05:14:34 -0700614 private FontScaleSettingObserver mFontScaleSettingObserver;
615
616 private final class FontScaleSettingObserver extends ContentObserver {
617 private final Uri mFontScaleUri = Settings.System.getUriFor(FONT_SCALE);
618 private final Uri mHideErrorDialogsUri = Settings.Global.getUriFor(HIDE_ERROR_DIALOGS);
619
620 public FontScaleSettingObserver() {
621 super(mH);
622 final ContentResolver resolver = mContext.getContentResolver();
623 resolver.registerContentObserver(mFontScaleUri, false, this, UserHandle.USER_ALL);
624 resolver.registerContentObserver(mHideErrorDialogsUri, false, this,
625 UserHandle.USER_ALL);
626 }
627
628 @Override
629 public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
630 if (mFontScaleUri.equals(uri)) {
631 updateFontScaleIfNeeded(userId);
632 } else if (mHideErrorDialogsUri.equals(uri)) {
633 synchronized (mGlobalLock) {
634 updateShouldShowDialogsLocked(getGlobalConfiguration());
635 }
636 }
637 }
638 }
639
Charles Chen8d98dd22018-12-26 17:36:54 +0800640 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
641 public ActivityTaskManagerService(Context context) {
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700642 mContext = context;
Wale Ogunwale214f3482018-10-04 11:00:47 -0700643 mFactoryTest = FactoryTest.getMode();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700644 mSystemThread = ActivityThread.currentActivityThread();
645 mUiContext = mSystemThread.getSystemUiContext();
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700646 mLifecycleManager = new ClientLifecycleManager();
Wale Ogunwaleb73f3962018-11-20 07:58:22 -0800647 mInternal = new LocalService();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700648 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700649 }
650
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700651 public void onSystemReady() {
652 synchronized (mGlobalLock) {
653 mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
654 PackageManager.FEATURE_CANT_SAVE_STATE);
655 mAssistUtils = new AssistUtils(mContext);
656 mVrController.onSystemReady();
657 mRecentTasks.onSystemReadyLocked();
Garfield Tan891146c2018-10-09 12:14:00 -0700658 mStackSupervisor.onSystemReady();
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700659 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700660 }
661
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700662 public void onInitPowerManagement() {
663 synchronized (mGlobalLock) {
664 mStackSupervisor.initPowerManagement();
665 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
666 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
667 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
668 mVoiceWakeLock.setReferenceCounted(false);
669 }
Wale Ogunwalef6733932018-06-27 05:14:34 -0700670 }
671
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700672 public void installSystemProviders() {
Wale Ogunwalef6733932018-06-27 05:14:34 -0700673 mFontScaleSettingObserver = new FontScaleSettingObserver();
674 }
675
Wale Ogunwale59507092018-10-29 09:00:30 -0700676 public void retrieveSettings(ContentResolver resolver) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700677 final boolean freeformWindowManagement =
678 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
679 || Settings.Global.getInt(
680 resolver, DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 0) != 0;
681
682 final boolean supportsMultiWindow = ActivityTaskManager.supportsMultiWindow(mContext);
683 final boolean supportsPictureInPicture = supportsMultiWindow &&
684 mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE);
685 final boolean supportsSplitScreenMultiWindow =
686 ActivityTaskManager.supportsSplitScreenMultiWindow(mContext);
687 final boolean supportsMultiDisplay = mContext.getPackageManager()
688 .hasSystemFeature(FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700689 final boolean forceRtl = Settings.Global.getInt(resolver, DEVELOPMENT_FORCE_RTL, 0) != 0;
690 final boolean forceResizable = Settings.Global.getInt(
691 resolver, DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 0) != 0;
Garfield Tane0846042018-07-26 13:42:04 -0700692 final boolean isPc = mContext.getPackageManager().hasSystemFeature(FEATURE_PC);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700693
694 // Transfer any global setting for forcing RTL layout, into a System Property
Kiyoung Kim0fe161d2018-12-20 18:26:10 +0900695 DisplayProperties.debug_force_rtl(forceRtl);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700696
697 final Configuration configuration = new Configuration();
698 Settings.System.getConfiguration(resolver, configuration);
699 if (forceRtl) {
700 // This will take care of setting the correct layout direction flags
701 configuration.setLayoutDirection(configuration.locale);
702 }
703
704 synchronized (mGlobalLock) {
705 mForceResizableActivities = forceResizable;
706 final boolean multiWindowFormEnabled = freeformWindowManagement
707 || supportsSplitScreenMultiWindow
708 || supportsPictureInPicture
709 || supportsMultiDisplay;
710 if ((supportsMultiWindow || forceResizable) && multiWindowFormEnabled) {
711 mSupportsMultiWindow = true;
712 mSupportsFreeformWindowManagement = freeformWindowManagement;
713 mSupportsSplitScreenMultiWindow = supportsSplitScreenMultiWindow;
714 mSupportsPictureInPicture = supportsPictureInPicture;
715 mSupportsMultiDisplay = supportsMultiDisplay;
716 } else {
717 mSupportsMultiWindow = false;
718 mSupportsFreeformWindowManagement = false;
719 mSupportsSplitScreenMultiWindow = false;
720 mSupportsPictureInPicture = false;
721 mSupportsMultiDisplay = false;
722 }
723 mWindowManager.setForceResizableTasks(mForceResizableActivities);
724 mWindowManager.setSupportsPictureInPicture(mSupportsPictureInPicture);
Garfield Tane0846042018-07-26 13:42:04 -0700725 mWindowManager.setSupportsFreeformWindowManagement(mSupportsFreeformWindowManagement);
726 mWindowManager.setIsPc(isPc);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700727 // This happens before any activities are started, so we can change global configuration
728 // in-place.
729 updateConfigurationLocked(configuration, null, true);
730 final Configuration globalConfig = getGlobalConfiguration();
731 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Initial config: " + globalConfig);
732
733 // Load resources only after the current configuration has been set.
734 final Resources res = mContext.getResources();
735 mThumbnailWidth = res.getDimensionPixelSize(
736 com.android.internal.R.dimen.thumbnail_width);
737 mThumbnailHeight = res.getDimensionPixelSize(
738 com.android.internal.R.dimen.thumbnail_height);
739
740 if ((globalConfig.uiMode & UI_MODE_TYPE_TELEVISION) == UI_MODE_TYPE_TELEVISION) {
741 mFullscreenThumbnailScale = (float) res
742 .getInteger(com.android.internal.R.integer.thumbnail_width_tv) /
743 (float) globalConfig.screenWidthDp;
744 } else {
745 mFullscreenThumbnailScale = res.getFraction(
746 com.android.internal.R.fraction.thumbnail_fullscreen_scale, 1, 1);
747 }
748 }
749 }
750
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800751 public WindowManagerGlobalLock getGlobalLock() {
752 return mGlobalLock;
753 }
754
Riddle Hsud93a6c42018-11-29 21:50:06 +0800755 public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
756 Looper looper) {
757 mH = new H(looper);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700758 mUiHandler = new UiHandler();
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700759 mIntentFirewall = intentFirewall;
Wale Ogunwale53783742018-09-16 10:21:51 -0700760 final File systemDir = SystemServiceManager.ensureSystemDir();
761 mAppWarnings = new AppWarnings(this, mUiContext, mH, mUiHandler, systemDir);
762 mCompatModePackages = new CompatModePackages(this, systemDir, mH);
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700763 mPendingIntentController = intentController;
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700764
765 mTempConfig.setToDefaults();
766 mTempConfig.setLocales(LocaleList.getDefault());
767 mConfigurationSeq = mTempConfig.seq = 1;
768 mStackSupervisor = createStackSupervisor();
Wale Ogunwaled32da472018-11-16 07:19:28 -0800769 mRootActivityContainer = new RootActivityContainer(this);
770 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700771
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700772 mTaskChangeNotificationController =
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700773 new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700774 mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700775 mActivityStartController = new ActivityStartController(this);
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700776 mRecentTasks = createRecentTasks();
777 mStackSupervisor.setRecentTasks(mRecentTasks);
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700778 mVrController = new VrController(mGlobalLock);
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700779 mKeyguardController = mStackSupervisor.getKeyguardController();
780 }
781
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700782 public void onActivityManagerInternalAdded() {
783 synchronized (mGlobalLock) {
784 mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
785 mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
786 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -0700787 }
788
Yunfan Chen75157d72018-07-27 14:47:21 +0900789 int increaseConfigurationSeqLocked() {
790 mConfigurationSeq = Math.max(++mConfigurationSeq, 1);
791 return mConfigurationSeq;
792 }
793
Wale Ogunwalec9e57de2018-05-08 14:28:07 -0700794 protected ActivityStackSupervisor createStackSupervisor() {
795 final ActivityStackSupervisor supervisor = new ActivityStackSupervisor(this, mH.getLooper());
796 supervisor.initialize();
797 return supervisor;
798 }
799
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700800 public void setWindowManager(WindowManagerService wm) {
801 synchronized (mGlobalLock) {
802 mWindowManager = wm;
803 mLockTaskController.setWindowManager(wm);
804 mStackSupervisor.setWindowManager(wm);
Wale Ogunwaled32da472018-11-16 07:19:28 -0800805 mRootActivityContainer.setWindowManager(wm);
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700806 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700807 }
808
Wale Ogunwale387b34c2018-10-25 19:59:40 -0700809 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
810 synchronized (mGlobalLock) {
811 mUsageStatsInternal = usageStatsManager;
812 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700813 }
814
Wale Ogunwalef6733932018-06-27 05:14:34 -0700815 UserManagerService getUserManager() {
816 if (mUserManager == null) {
817 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
818 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
819 }
820 return mUserManager;
821 }
822
823 AppOpsService getAppOpsService() {
824 if (mAppOpsService == null) {
825 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE);
826 mAppOpsService = (AppOpsService) IAppOpsService.Stub.asInterface(b);
827 }
828 return mAppOpsService;
829 }
830
831 boolean hasUserRestriction(String restriction, int userId) {
832 return getUserManager().hasUserRestriction(restriction, userId);
833 }
834
Wale Ogunwale16e505a2018-05-07 15:00:49 -0700835 protected RecentTasks createRecentTasks() {
836 return new RecentTasks(this, mStackSupervisor);
837 }
838
839 RecentTasks getRecentTasks() {
840 return mRecentTasks;
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700841 }
842
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700843 ClientLifecycleManager getLifecycleManager() {
844 return mLifecycleManager;
845 }
846
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700847 ActivityStartController getActivityStartController() {
848 return mActivityStartController;
849 }
850
Wale Ogunwaled0412b32018-05-08 09:25:50 -0700851 TaskChangeNotificationController getTaskChangeNotificationController() {
852 return mTaskChangeNotificationController;
853 }
854
Wale Ogunwaled95c06b2018-05-08 10:35:38 -0700855 LockTaskController getLockTaskController() {
856 return mLockTaskController;
857 }
858
Yunfan Chen75157d72018-07-27 14:47:21 +0900859 /**
860 * Return the global configuration used by the process corresponding to the input pid. This is
861 * usually the global configuration with some overrides specific to that process.
862 */
863 Configuration getGlobalConfigurationForCallingPid() {
864 final int pid = Binder.getCallingPid();
Yunfan Chenc2ff6cf2018-12-04 16:56:21 -0800865 return getGlobalConfigurationForPid(pid);
866 }
867
868 /**
869 * Return the global configuration used by the process corresponding to the given pid.
870 */
871 Configuration getGlobalConfigurationForPid(int pid) {
Yunfan Chen75157d72018-07-27 14:47:21 +0900872 if (pid == MY_PID || pid < 0) {
873 return getGlobalConfiguration();
874 }
875 synchronized (mGlobalLock) {
876 final WindowProcessController app = mPidMap.get(pid);
877 return app != null ? app.getConfiguration() : getGlobalConfiguration();
878 }
879 }
880
881 /**
882 * Return the device configuration info used by the process corresponding to the input pid.
883 * The value is consistent with the global configuration for the process.
884 */
885 @Override
886 public ConfigurationInfo getDeviceConfigurationInfo() {
887 ConfigurationInfo config = new ConfigurationInfo();
888 synchronized (mGlobalLock) {
889 final Configuration globalConfig = getGlobalConfigurationForCallingPid();
890 config.reqTouchScreen = globalConfig.touchscreen;
891 config.reqKeyboardType = globalConfig.keyboard;
892 config.reqNavigation = globalConfig.navigation;
893 if (globalConfig.navigation == Configuration.NAVIGATION_DPAD
894 || globalConfig.navigation == Configuration.NAVIGATION_TRACKBALL) {
895 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
896 }
897 if (globalConfig.keyboard != Configuration.KEYBOARD_UNDEFINED
898 && globalConfig.keyboard != Configuration.KEYBOARD_NOKEYS) {
899 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
900 }
Wale Ogunwale342fbe92018-10-09 08:44:10 -0700901 config.reqGlEsVersion = GL_ES_VERSION;
Yunfan Chen75157d72018-07-27 14:47:21 +0900902 }
903 return config;
904 }
905
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700906 private void start() {
Wale Ogunwale53783742018-09-16 10:21:51 -0700907 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700908 }
909
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700910 public static final class Lifecycle extends SystemService {
911 private final ActivityTaskManagerService mService;
912
913 public Lifecycle(Context context) {
914 super(context);
915 mService = new ActivityTaskManagerService(context);
916 }
917
918 @Override
919 public void onStart() {
920 publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
Wale Ogunwale6767eae2018-05-03 15:52:51 -0700921 mService.start();
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700922 }
923
Garfield Tan891146c2018-10-09 12:14:00 -0700924 @Override
925 public void onUnlockUser(int userId) {
926 synchronized (mService.getGlobalLock()) {
927 mService.mStackSupervisor.mLaunchParamsPersister.onUnlockUser(userId);
928 }
929 }
930
931 @Override
932 public void onCleanupUser(int userId) {
933 synchronized (mService.getGlobalLock()) {
934 mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
935 }
936 }
937
Wale Ogunwale65ebd952018-04-25 15:41:44 -0700938 public ActivityTaskManagerService getService() {
939 return mService;
940 }
941 }
942
943 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700944 public final int startActivity(IApplicationThread caller, String callingPackage,
945 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
946 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
947 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
948 resultWho, requestCode, startFlags, profilerInfo, bOptions,
949 UserHandle.getCallingUserId());
950 }
951
952 @Override
953 public final int startActivities(IApplicationThread caller, String callingPackage,
954 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle bOptions,
955 int userId) {
956 final String reason = "startActivities";
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700957 enforceNotIsolatedCaller(reason);
958 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, reason);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700959 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700960 return getActivityStartController().startActivities(caller, -1, callingPackage, intents,
Michal Karpinski201bc0c2018-07-20 15:32:00 +0100961 resolvedTypes, resultTo, SafeActivityOptions.fromBundle(bOptions), userId, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +0000962 null /* originatingPendingIntent */, false /* allowBackgroundActivityStart */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700963 }
964
965 @Override
966 public int startActivityAsUser(IApplicationThread caller, String callingPackage,
967 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
968 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
969 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
970 resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
971 true /*validateIncomingUser*/);
972 }
973
974 int startActivityAsUser(IApplicationThread caller, String callingPackage,
975 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
976 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
977 boolean validateIncomingUser) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -0700978 enforceNotIsolatedCaller("startActivityAsUser");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700979
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700980 userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700981 Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
982
983 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -0700984 return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -0700985 .setCaller(caller)
986 .setCallingPackage(callingPackage)
987 .setResolvedType(resolvedType)
988 .setResultTo(resultTo)
989 .setResultWho(resultWho)
990 .setRequestCode(requestCode)
991 .setStartFlags(startFlags)
992 .setProfilerInfo(profilerInfo)
993 .setActivityOptions(bOptions)
994 .setMayWait(userId)
995 .execute();
996
997 }
998
999 @Override
1000 public int startActivityIntentSender(IApplicationThread caller, IIntentSender target,
1001 IBinder whitelistToken, Intent fillInIntent, String resolvedType, IBinder resultTo,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001002 String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle bOptions) {
1003 enforceNotIsolatedCaller("startActivityIntentSender");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001004 // Refuse possible leaked file descriptors
1005 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
1006 throw new IllegalArgumentException("File descriptors passed in Intent");
1007 }
1008
1009 if (!(target instanceof PendingIntentRecord)) {
1010 throw new IllegalArgumentException("Bad PendingIntent object");
1011 }
1012
1013 PendingIntentRecord pir = (PendingIntentRecord)target;
1014
1015 synchronized (mGlobalLock) {
1016 // If this is coming from the currently resumed activity, it is
1017 // effectively saying that app switches are allowed at this point.
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001018 final ActivityStack stack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 if (stack.mResumedActivity != null &&
1020 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001021 mAppSwitchesAllowedTime = 0;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001022 }
1023 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001024 return pir.sendInner(0, fillInIntent, resolvedType, whitelistToken, null, null,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001025 resultTo, resultWho, requestCode, flagsMask, flagsValues, bOptions);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001026 }
1027
1028 @Override
1029 public boolean startNextMatchingActivity(IBinder callingActivity, Intent intent,
1030 Bundle bOptions) {
1031 // Refuse possible leaked file descriptors
1032 if (intent != null && intent.hasFileDescriptors()) {
1033 throw new IllegalArgumentException("File descriptors passed in Intent");
1034 }
1035 SafeActivityOptions options = SafeActivityOptions.fromBundle(bOptions);
1036
1037 synchronized (mGlobalLock) {
1038 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
1039 if (r == null) {
1040 SafeActivityOptions.abort(options);
1041 return false;
1042 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001043 if (!r.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001044 // The caller is not running... d'oh!
1045 SafeActivityOptions.abort(options);
1046 return false;
1047 }
1048 intent = new Intent(intent);
1049 // The caller is not allowed to change the data.
1050 intent.setDataAndType(r.intent.getData(), r.intent.getType());
1051 // And we are resetting to find the next component...
1052 intent.setComponent(null);
1053
1054 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
1055
1056 ActivityInfo aInfo = null;
1057 try {
1058 List<ResolveInfo> resolves =
1059 AppGlobals.getPackageManager().queryIntentActivities(
1060 intent, r.resolvedType,
1061 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
1062 UserHandle.getCallingUserId()).getList();
1063
1064 // Look for the original activity in the list...
1065 final int N = resolves != null ? resolves.size() : 0;
1066 for (int i=0; i<N; i++) {
1067 ResolveInfo rInfo = resolves.get(i);
1068 if (rInfo.activityInfo.packageName.equals(r.packageName)
1069 && rInfo.activityInfo.name.equals(r.info.name)) {
1070 // We found the current one... the next matching is
1071 // after it.
1072 i++;
1073 if (i<N) {
1074 aInfo = resolves.get(i).activityInfo;
1075 }
1076 if (debug) {
1077 Slog.v(TAG, "Next matching activity: found current " + r.packageName
1078 + "/" + r.info.name);
1079 Slog.v(TAG, "Next matching activity: next is " + ((aInfo == null)
1080 ? "null" : aInfo.packageName + "/" + aInfo.name));
1081 }
1082 break;
1083 }
1084 }
1085 } catch (RemoteException e) {
1086 }
1087
1088 if (aInfo == null) {
1089 // Nobody who is next!
1090 SafeActivityOptions.abort(options);
1091 if (debug) Slog.d(TAG, "Next matching activity: nothing found");
1092 return false;
1093 }
1094
1095 intent.setComponent(new ComponentName(
1096 aInfo.applicationInfo.packageName, aInfo.name));
1097 intent.setFlags(intent.getFlags()&~(
1098 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
1099 Intent.FLAG_ACTIVITY_CLEAR_TOP|
1100 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
1101 FLAG_ACTIVITY_NEW_TASK));
1102
1103 // Okay now we need to start the new activity, replacing the currently running activity.
1104 // This is a little tricky because we want to start the new one as if the current one is
1105 // finished, but not finish the current one first so that there is no flicker.
1106 // And thus...
1107 final boolean wasFinishing = r.finishing;
1108 r.finishing = true;
1109
1110 // Propagate reply information over to the new activity.
1111 final ActivityRecord resultTo = r.resultTo;
1112 final String resultWho = r.resultWho;
1113 final int requestCode = r.requestCode;
1114 r.resultTo = null;
1115 if (resultTo != null) {
1116 resultTo.removeResultsLocked(r, resultWho, requestCode);
1117 }
1118
1119 final long origId = Binder.clearCallingIdentity();
1120 // TODO(b/64750076): Check if calling pid should really be -1.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001121 final int res = getActivityStartController()
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001122 .obtainStarter(intent, "startNextMatchingActivity")
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001123 .setCaller(r.app.getThread())
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001124 .setResolvedType(r.resolvedType)
1125 .setActivityInfo(aInfo)
1126 .setResultTo(resultTo != null ? resultTo.appToken : null)
1127 .setResultWho(resultWho)
1128 .setRequestCode(requestCode)
1129 .setCallingPid(-1)
1130 .setCallingUid(r.launchedFromUid)
1131 .setCallingPackage(r.launchedFromPackage)
1132 .setRealCallingPid(-1)
1133 .setRealCallingUid(r.launchedFromUid)
1134 .setActivityOptions(options)
1135 .execute();
1136 Binder.restoreCallingIdentity(origId);
1137
1138 r.finishing = wasFinishing;
1139 if (res != ActivityManager.START_SUCCESS) {
1140 return false;
1141 }
1142 return true;
1143 }
1144 }
1145
1146 @Override
1147 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
1148 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1149 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
1150 final WaitResult res = new WaitResult();
1151 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001152 enforceNotIsolatedCaller("startActivityAndWait");
1153 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
1154 userId, "startActivityAndWait");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001155 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001156 getActivityStartController().obtainStarter(intent, "startActivityAndWait")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001157 .setCaller(caller)
1158 .setCallingPackage(callingPackage)
1159 .setResolvedType(resolvedType)
1160 .setResultTo(resultTo)
1161 .setResultWho(resultWho)
1162 .setRequestCode(requestCode)
1163 .setStartFlags(startFlags)
1164 .setActivityOptions(bOptions)
1165 .setMayWait(userId)
1166 .setProfilerInfo(profilerInfo)
1167 .setWaitResult(res)
1168 .execute();
1169 }
1170 return res;
1171 }
1172
1173 @Override
1174 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
1175 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
1176 int startFlags, Configuration config, Bundle bOptions, int userId) {
1177 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001178 enforceNotIsolatedCaller("startActivityWithConfig");
1179 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
1180 "startActivityWithConfig");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001181 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001182 return getActivityStartController().obtainStarter(intent, "startActivityWithConfig")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001183 .setCaller(caller)
1184 .setCallingPackage(callingPackage)
1185 .setResolvedType(resolvedType)
1186 .setResultTo(resultTo)
1187 .setResultWho(resultWho)
1188 .setRequestCode(requestCode)
1189 .setStartFlags(startFlags)
1190 .setGlobalConfiguration(config)
1191 .setActivityOptions(bOptions)
1192 .setMayWait(userId)
1193 .execute();
1194 }
1195 }
1196
Alison Cichowlas3e340502018-08-07 17:15:01 -04001197
1198 @Override
1199 public IBinder requestStartActivityPermissionToken(IBinder delegatorToken) {
1200 int callingUid = Binder.getCallingUid();
1201 if (UserHandle.getAppId(callingUid) != SYSTEM_UID) {
1202 throw new SecurityException("Only the system process can request a permission token, "
1203 + "received request from uid: " + callingUid);
1204 }
1205 IBinder permissionToken = new Binder();
1206 synchronized (mGlobalLock) {
1207 mStartActivitySources.put(permissionToken, delegatorToken);
1208 }
1209
1210 Message expireMsg = PooledLambda.obtainMessage(
1211 ActivityTaskManagerService::expireStartAsCallerTokenMsg, this, permissionToken);
1212 mUiHandler.sendMessageDelayed(expireMsg, START_AS_CALLER_TOKEN_TIMEOUT_IMPL);
1213
1214 Message forgetMsg = PooledLambda.obtainMessage(
1215 ActivityTaskManagerService::forgetStartAsCallerTokenMsg, this, permissionToken);
1216 mUiHandler.sendMessageDelayed(forgetMsg, START_AS_CALLER_TOKEN_EXPIRED_TIMEOUT);
1217
1218 return permissionToken;
1219 }
1220
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001221 @Override
1222 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
1223 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
Alison Cichowlas3e340502018-08-07 17:15:01 -04001224 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, IBinder permissionToken,
1225 boolean ignoreTargetSecurity, int userId) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001226 // This is very dangerous -- it allows you to perform a start activity (including
Alison Cichowlas3e340502018-08-07 17:15:01 -04001227 // permission grants) as any app that may launch one of your own activities. So we only
1228 // allow this in two cases:
1229 // 1) The caller is an activity that is part of the core framework, and then only when it
1230 // is running as the system.
1231 // 2) The caller provides a valid permissionToken. Permission tokens are one-time use and
1232 // can only be requested by a system activity, which may then delegate this call to
1233 // another app.
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001234 final ActivityRecord sourceRecord;
1235 final int targetUid;
1236 final String targetPackage;
1237 final boolean isResolver;
1238 synchronized (mGlobalLock) {
1239 if (resultTo == null) {
1240 throw new SecurityException("Must be called from an activity");
1241 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001242 final IBinder sourceToken;
1243 if (permissionToken != null) {
1244 // To even attempt to use a permissionToken, an app must also have this signature
1245 // permission.
1246 mAmInternal.enforceCallingPermission(
1247 android.Manifest.permission.START_ACTIVITY_AS_CALLER,
1248 "startActivityAsCaller");
1249 // If called with a permissionToken, we want the sourceRecord from the delegator
1250 // activity that requested this token.
1251 sourceToken = mStartActivitySources.remove(permissionToken);
1252 if (sourceToken == null) {
1253 // Invalid permissionToken, check if it recently expired.
1254 if (mExpiredStartAsCallerTokens.contains(permissionToken)) {
1255 throw new SecurityException("Called with expired permission token: "
1256 + permissionToken);
1257 } else {
1258 throw new SecurityException("Called with invalid permission token: "
1259 + permissionToken);
1260 }
1261 }
1262 } else {
1263 // This method was called directly by the source.
1264 sourceToken = resultTo;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001265 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001266
Wale Ogunwaled32da472018-11-16 07:19:28 -08001267 sourceRecord = mRootActivityContainer.isInAnyStack(sourceToken);
Alison Cichowlas3e340502018-08-07 17:15:01 -04001268 if (sourceRecord == null) {
1269 throw new SecurityException("Called with bad activity token: " + sourceToken);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001270 }
1271 if (sourceRecord.app == null) {
1272 throw new SecurityException("Called without a process attached to activity");
1273 }
Alison Cichowlas3e340502018-08-07 17:15:01 -04001274
1275 // Whether called directly or from a delegate, the source activity must be from the
1276 // android package.
1277 if (!sourceRecord.info.packageName.equals("android")) {
1278 throw new SecurityException("Must be called from an activity that is "
1279 + "declared in the android package");
1280 }
1281
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001282 if (UserHandle.getAppId(sourceRecord.app.mUid) != SYSTEM_UID) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001283 // This is still okay, as long as this activity is running under the
1284 // uid of the original calling activity.
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001285 if (sourceRecord.app.mUid != sourceRecord.launchedFromUid) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001286 throw new SecurityException(
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001287 "Calling activity in uid " + sourceRecord.app.mUid
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001288 + " must be system uid or original calling uid "
1289 + sourceRecord.launchedFromUid);
1290 }
1291 }
1292 if (ignoreTargetSecurity) {
1293 if (intent.getComponent() == null) {
1294 throw new SecurityException(
1295 "Component must be specified with ignoreTargetSecurity");
1296 }
1297 if (intent.getSelector() != null) {
1298 throw new SecurityException(
1299 "Selector not allowed with ignoreTargetSecurity");
1300 }
1301 }
1302 targetUid = sourceRecord.launchedFromUid;
1303 targetPackage = sourceRecord.launchedFromPackage;
1304 isResolver = sourceRecord.isResolverOrChildActivity();
1305 }
1306
1307 if (userId == UserHandle.USER_NULL) {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001308 userId = UserHandle.getUserId(sourceRecord.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001309 }
1310
1311 // TODO: Switch to user app stacks here.
1312 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001313 return getActivityStartController().obtainStarter(intent, "startActivityAsCaller")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001314 .setCallingUid(targetUid)
1315 .setCallingPackage(targetPackage)
1316 .setResolvedType(resolvedType)
1317 .setResultTo(resultTo)
1318 .setResultWho(resultWho)
1319 .setRequestCode(requestCode)
1320 .setStartFlags(startFlags)
1321 .setActivityOptions(bOptions)
1322 .setMayWait(userId)
1323 .setIgnoreTargetSecurity(ignoreTargetSecurity)
1324 .setFilterCallingUid(isResolver ? 0 /* system */ : targetUid)
1325 .execute();
1326 } catch (SecurityException e) {
1327 // XXX need to figure out how to propagate to original app.
1328 // A SecurityException here is generally actually a fault of the original
1329 // calling activity (such as a fairly granting permissions), so propagate it
1330 // back to them.
1331 /*
1332 StringBuilder msg = new StringBuilder();
1333 msg.append("While launching");
1334 msg.append(intent.toString());
1335 msg.append(": ");
1336 msg.append(e.getMessage());
1337 */
1338 throw e;
1339 }
1340 }
1341
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001342 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
1343 return mAmInternal.handleIncomingUser(callingPid, callingUid, userId, false /* allowAll */,
1344 ALLOW_FULL_ONLY, name, null /* callerPackage */);
1345 }
1346
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001347 @Override
1348 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
1349 Intent intent, String resolvedType, IVoiceInteractionSession session,
1350 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo,
1351 Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001352 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startVoiceActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001353 if (session == null || interactor == null) {
1354 throw new NullPointerException("null session or interactor");
1355 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001356 userId = handleIncomingUser(callingPid, callingUid, userId, "startVoiceActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001357 // TODO: Switch to user app stacks here.
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001358 return getActivityStartController().obtainStarter(intent, "startVoiceActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001359 .setCallingUid(callingUid)
1360 .setCallingPackage(callingPackage)
1361 .setResolvedType(resolvedType)
1362 .setVoiceSession(session)
1363 .setVoiceInteractor(interactor)
1364 .setStartFlags(startFlags)
1365 .setProfilerInfo(profilerInfo)
1366 .setActivityOptions(bOptions)
1367 .setMayWait(userId)
1368 .execute();
1369 }
1370
1371 @Override
1372 public int startAssistantActivity(String callingPackage, int callingPid, int callingUid,
1373 Intent intent, String resolvedType, Bundle bOptions, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001374 mAmInternal.enforceCallingPermission(BIND_VOICE_INTERACTION, "startAssistantActivity()");
1375 userId = handleIncomingUser(callingPid, callingUid, userId, "startAssistantActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001376
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07001377 return getActivityStartController().obtainStarter(intent, "startAssistantActivity")
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001378 .setCallingUid(callingUid)
1379 .setCallingPackage(callingPackage)
1380 .setResolvedType(resolvedType)
1381 .setActivityOptions(bOptions)
1382 .setMayWait(userId)
1383 .execute();
1384 }
1385
1386 @Override
1387 public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
1388 IRecentsAnimationRunner recentsAnimationRunner) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001389 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "startRecentsActivity()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001390 final int callingPid = Binder.getCallingPid();
1391 final long origId = Binder.clearCallingIdentity();
1392 try {
1393 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07001394 final ComponentName recentsComponent = mRecentTasks.getRecentsComponent();
1395 final int recentsUid = mRecentTasks.getRecentsComponentUid();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001396
1397 // Start a new recents animation
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001398 final RecentsAnimation anim = new RecentsAnimation(this, mStackSupervisor,
1399 getActivityStartController(), mWindowManager, callingPid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001400 anim.startRecentsActivity(intent, recentsAnimationRunner, recentsComponent,
1401 recentsUid, assistDataReceiver);
1402 }
1403 } finally {
1404 Binder.restoreCallingIdentity(origId);
1405 }
1406 }
1407
1408 @Override
1409 public final int startActivityFromRecents(int taskId, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001410 enforceCallerIsRecentsOrHasPermission(START_TASKS_FROM_RECENTS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001411 "startActivityFromRecents()");
1412
1413 final int callingPid = Binder.getCallingPid();
1414 final int callingUid = Binder.getCallingUid();
1415 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(bOptions);
1416 final long origId = Binder.clearCallingIdentity();
1417 try {
1418 synchronized (mGlobalLock) {
1419 return mStackSupervisor.startActivityFromRecents(callingPid, callingUid, taskId,
1420 safeOptions);
1421 }
1422 } finally {
1423 Binder.restoreCallingIdentity(origId);
1424 }
1425 }
1426
1427 /**
Andrii Kulian2eb84b22018-12-13 18:18:54 -08001428 * Public API to check if the client is allowed to start an activity on specified display.
1429 *
1430 * If the target display is private or virtual, some restrictions will apply.
1431 *
1432 * @param displayId Target display id.
1433 * @param intent Intent used to launch the activity.
1434 * @param resolvedType The MIME type of the intent.
1435 * @param userId The id of the user for whom the call is made.
1436 * @return {@code true} if a call to start an activity on the target display should succeed and
1437 * no {@link SecurityException} will be thrown, {@code false} otherwise.
1438 */
1439 @Override
1440 public final boolean isActivityStartAllowedOnDisplay(int displayId, Intent intent,
1441 String resolvedType, int userId) {
1442 final int callingUid = Binder.getCallingUid();
1443 final int callingPid = Binder.getCallingPid();
1444 final long origId = Binder.clearCallingIdentity();
1445
1446 try {
1447 // Collect information about the target of the Intent.
1448 ActivityInfo aInfo = mStackSupervisor.resolveActivity(intent, resolvedType,
1449 0 /* startFlags */, null /* profilerInfo */, userId,
1450 ActivityStarter.computeResolveFilterUid(callingUid, callingUid,
1451 UserHandle.USER_NULL));
1452 aInfo = mAmInternal.getActivityInfoForUser(aInfo, userId);
1453
1454 synchronized (mGlobalLock) {
1455 return mStackSupervisor.canPlaceEntityOnDisplay(displayId, callingPid, callingUid,
1456 aInfo);
1457 }
1458 } finally {
1459 Binder.restoreCallingIdentity(origId);
1460 }
1461 }
1462
1463 /**
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001464 * This is the internal entry point for handling Activity.finish().
1465 *
1466 * @param token The Binder token referencing the Activity we want to finish.
1467 * @param resultCode Result code, if any, from this Activity.
1468 * @param resultData Result data (Intent), if any, from this Activity.
1469 * @param finishTask Whether to finish the task associated with this Activity.
1470 *
1471 * @return Returns true if the activity successfully finished, or false if it is still running.
1472 */
1473 @Override
1474 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
1475 int finishTask) {
1476 // Refuse possible leaked file descriptors
1477 if (resultData != null && resultData.hasFileDescriptors()) {
1478 throw new IllegalArgumentException("File descriptors passed in Intent");
1479 }
1480
1481 synchronized (mGlobalLock) {
1482 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1483 if (r == null) {
1484 return true;
1485 }
1486 // Keep track of the root activity of the task before we finish it
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001487 final TaskRecord tr = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001488 ActivityRecord rootR = tr.getRootActivity();
1489 if (rootR == null) {
1490 Slog.w(TAG, "Finishing task with all activities already finished");
1491 }
1492 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can
1493 // finish.
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001494 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001495 return false;
1496 }
1497
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001498 // TODO: There is a dup. of this block of code in ActivityStack.navigateUpToLocked
1499 // We should consolidate.
1500 if (mController != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001501 // Find the first activity that is not finishing.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001502 final ActivityRecord next = r.getActivityStack().topRunningActivityLocked(token, 0);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001503 if (next != null) {
1504 // ask watcher if this is allowed
1505 boolean resumeOK = true;
1506 try {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001507 resumeOK = mController.activityResuming(next.packageName);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001508 } catch (RemoteException e) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001509 mController = null;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001510 Watchdog.getInstance().setActivityController(null);
1511 }
1512
1513 if (!resumeOK) {
1514 Slog.i(TAG, "Not finishing activity because controller resumed");
1515 return false;
1516 }
1517 }
1518 }
1519 final long origId = Binder.clearCallingIdentity();
1520 try {
1521 boolean res;
1522 final boolean finishWithRootActivity =
1523 finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
1524 if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
1525 || (finishWithRootActivity && r == rootR)) {
1526 // If requested, remove the task that is associated to this activity only if it
1527 // was the root activity in the task. The result code and data is ignored
1528 // because we don't support returning them across task boundaries. Also, to
1529 // keep backwards compatibility we remove the task from recents when finishing
1530 // task with root activity.
1531 res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false,
1532 finishWithRootActivity, "finish-activity");
1533 if (!res) {
1534 Slog.i(TAG, "Removing task failed to finish activity");
1535 }
Garfield Tan2746ab52018-07-25 12:33:01 -07001536 // Explicitly dismissing the activity so reset its relaunch flag.
Wale Ogunwale64258362018-10-16 15:13:37 -07001537 r.mRelaunchReason = RELAUNCH_REASON_NONE;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001538 } else {
1539 res = tr.getStack().requestFinishActivityLocked(token, resultCode,
1540 resultData, "app-request", true);
1541 if (!res) {
1542 Slog.i(TAG, "Failed to finish by app-request");
1543 }
1544 }
1545 return res;
1546 } finally {
1547 Binder.restoreCallingIdentity(origId);
1548 }
1549 }
1550 }
1551
1552 @Override
1553 public boolean finishActivityAffinity(IBinder token) {
1554 synchronized (mGlobalLock) {
1555 final long origId = Binder.clearCallingIdentity();
1556 try {
1557 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1558 if (r == null) {
1559 return false;
1560 }
1561
1562 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps
1563 // can finish.
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001564 final TaskRecord task = r.getTaskRecord();
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07001565 if (getLockTaskController().activityBlockedFromFinish(r)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001566 return false;
1567 }
1568 return task.getStack().finishActivityAffinityLocked(r);
1569 } finally {
1570 Binder.restoreCallingIdentity(origId);
1571 }
1572 }
1573 }
1574
1575 @Override
1576 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
1577 final long origId = Binder.clearCallingIdentity();
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001578 try {
1579 WindowProcessController proc = null;
1580 synchronized (mGlobalLock) {
1581 ActivityStack stack = ActivityRecord.getStackLocked(token);
1582 if (stack == null) {
1583 return;
1584 }
1585 final ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token,
1586 false /* fromTimeout */, false /* processPausingActivities */, config);
1587 if (r != null) {
1588 proc = r.app;
1589 }
1590 if (stopProfiling && proc != null) {
1591 proc.clearProfilerIfNeeded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001592 }
1593 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07001594 } finally {
1595 Binder.restoreCallingIdentity(origId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001596 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001597 }
1598
1599 @Override
1600 public final void activityResumed(IBinder token) {
1601 final long origId = Binder.clearCallingIdentity();
1602 synchronized (mGlobalLock) {
1603 ActivityRecord.activityResumedLocked(token);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001604 mWindowManager.notifyAppResumedFinished(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001605 }
1606 Binder.restoreCallingIdentity(origId);
1607 }
1608
1609 @Override
1610 public final void activityPaused(IBinder token) {
1611 final long origId = Binder.clearCallingIdentity();
1612 synchronized (mGlobalLock) {
1613 ActivityStack stack = ActivityRecord.getStackLocked(token);
1614 if (stack != null) {
1615 stack.activityPausedLocked(token, false);
1616 }
1617 }
1618 Binder.restoreCallingIdentity(origId);
1619 }
1620
1621 @Override
1622 public final void activityStopped(IBinder token, Bundle icicle,
1623 PersistableBundle persistentState, CharSequence description) {
1624 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token);
1625
1626 // Refuse possible leaked file descriptors
1627 if (icicle != null && icicle.hasFileDescriptors()) {
1628 throw new IllegalArgumentException("File descriptors passed in Bundle");
1629 }
1630
1631 final long origId = Binder.clearCallingIdentity();
1632
1633 synchronized (mGlobalLock) {
1634 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1635 if (r != null) {
1636 r.activityStoppedLocked(icicle, persistentState, description);
1637 }
1638 }
1639
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001640 mAmInternal.trimApplications();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001641
1642 Binder.restoreCallingIdentity(origId);
1643 }
1644
1645 @Override
1646 public final void activityDestroyed(IBinder token) {
1647 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token);
1648 synchronized (mGlobalLock) {
1649 ActivityStack stack = ActivityRecord.getStackLocked(token);
1650 if (stack != null) {
1651 stack.activityDestroyedLocked(token, "activityDestroyed");
1652 }
1653 }
1654 }
1655
1656 @Override
1657 public final void activityRelaunched(IBinder token) {
1658 final long origId = Binder.clearCallingIdentity();
1659 synchronized (mGlobalLock) {
1660 mStackSupervisor.activityRelaunchedLocked(token);
1661 }
1662 Binder.restoreCallingIdentity(origId);
1663 }
1664
1665 public final void activitySlept(IBinder token) {
1666 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token);
1667
1668 final long origId = Binder.clearCallingIdentity();
1669
1670 synchronized (mGlobalLock) {
1671 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1672 if (r != null) {
1673 mStackSupervisor.activitySleptLocked(r);
1674 }
1675 }
1676
1677 Binder.restoreCallingIdentity(origId);
1678 }
1679
1680 @Override
1681 public void setRequestedOrientation(IBinder token, int requestedOrientation) {
1682 synchronized (mGlobalLock) {
1683 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1684 if (r == null) {
1685 return;
1686 }
1687 final long origId = Binder.clearCallingIdentity();
1688 try {
1689 r.setRequestedOrientation(requestedOrientation);
1690 } finally {
1691 Binder.restoreCallingIdentity(origId);
1692 }
1693 }
1694 }
1695
1696 @Override
1697 public int getRequestedOrientation(IBinder token) {
1698 synchronized (mGlobalLock) {
1699 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1700 if (r == null) {
1701 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
1702 }
1703 return r.getRequestedOrientation();
1704 }
1705 }
1706
1707 @Override
1708 public void setImmersive(IBinder token, boolean immersive) {
1709 synchronized (mGlobalLock) {
1710 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1711 if (r == null) {
1712 throw new IllegalArgumentException();
1713 }
1714 r.immersive = immersive;
1715
1716 // update associated state if we're frontmost
Andrii Kulian52d255c2018-07-13 11:32:19 -07001717 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001718 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001719 applyUpdateLockStateLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001720 }
1721 }
1722 }
1723
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001724 void applyUpdateLockStateLocked(ActivityRecord r) {
1725 // Modifications to the UpdateLock state are done on our handler, outside
1726 // the activity manager's locks. The new state is determined based on the
1727 // state *now* of the relevant activity record. The object is passed to
1728 // the handler solely for logging detail, not to be consulted/modified.
1729 final boolean nextState = r != null && r.immersive;
1730 mH.post(() -> {
1731 if (mUpdateLock.isHeld() != nextState) {
1732 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE,
1733 "Applying new update lock state '" + nextState + "' for " + r);
1734 if (nextState) {
1735 mUpdateLock.acquire();
1736 } else {
1737 mUpdateLock.release();
1738 }
1739 }
1740 });
1741 }
1742
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001743 @Override
1744 public boolean isImmersive(IBinder token) {
1745 synchronized (mGlobalLock) {
1746 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1747 if (r == null) {
1748 throw new IllegalArgumentException();
1749 }
1750 return r.immersive;
1751 }
1752 }
1753
1754 @Override
1755 public boolean isTopActivityImmersive() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001756 enforceNotIsolatedCaller("isTopActivityImmersive");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001757 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001758 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001759 return (r != null) ? r.immersive : false;
1760 }
1761 }
1762
1763 @Override
1764 public void overridePendingTransition(IBinder token, String packageName,
1765 int enterAnim, int exitAnim) {
1766 synchronized (mGlobalLock) {
1767 ActivityRecord self = ActivityRecord.isInStackLocked(token);
1768 if (self == null) {
1769 return;
1770 }
1771
1772 final long origId = Binder.clearCallingIdentity();
1773
1774 if (self.isState(
1775 ActivityStack.ActivityState.RESUMED, ActivityStack.ActivityState.PAUSING)) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08001776 self.getDisplay().mDisplayContent.mAppTransition.overridePendingAppTransition(
lumark588a3e82018-07-20 18:53:54 +08001777 packageName, enterAnim, exitAnim, null);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001778 }
1779
1780 Binder.restoreCallingIdentity(origId);
1781 }
1782 }
1783
1784 @Override
1785 public int getFrontActivityScreenCompatMode() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001786 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001787 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001788 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001789 if (r == null) {
1790 return ActivityManager.COMPAT_MODE_UNKNOWN;
1791 }
Wale Ogunwale53783742018-09-16 10:21:51 -07001792 return mCompatModePackages.computeCompatModeLocked(r.info.applicationInfo);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001793 }
1794 }
1795
1796 @Override
1797 public void setFrontActivityScreenCompatMode(int mode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001798 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001799 "setFrontActivityScreenCompatMode");
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001800 ApplicationInfo ai;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001801 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001802 final ActivityRecord r = getTopDisplayFocusedStack().topRunningActivityLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001803 if (r == null) {
1804 Slog.w(TAG, "setFrontActivityScreenCompatMode failed: no top activity");
1805 return;
1806 }
1807 ai = r.info.applicationInfo;
Wale Ogunwale53783742018-09-16 10:21:51 -07001808 mCompatModePackages.setPackageScreenCompatModeLocked(ai, mode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001809 }
1810 }
1811
1812 @Override
1813 public int getLaunchedFromUid(IBinder activityToken) {
1814 ActivityRecord srec;
1815 synchronized (mGlobalLock) {
1816 srec = ActivityRecord.forTokenLocked(activityToken);
1817 }
1818 if (srec == null) {
1819 return -1;
1820 }
1821 return srec.launchedFromUid;
1822 }
1823
1824 @Override
1825 public String getLaunchedFromPackage(IBinder activityToken) {
1826 ActivityRecord srec;
1827 synchronized (mGlobalLock) {
1828 srec = ActivityRecord.forTokenLocked(activityToken);
1829 }
1830 if (srec == null) {
1831 return null;
1832 }
1833 return srec.launchedFromPackage;
1834 }
1835
1836 @Override
1837 public boolean convertFromTranslucent(IBinder token) {
1838 final long origId = Binder.clearCallingIdentity();
1839 try {
1840 synchronized (mGlobalLock) {
1841 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1842 if (r == null) {
1843 return false;
1844 }
1845 final boolean translucentChanged = r.changeWindowTranslucency(true);
1846 if (translucentChanged) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001847 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001848 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001849 mWindowManager.setAppFullscreen(token, true);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001850 return translucentChanged;
1851 }
1852 } finally {
1853 Binder.restoreCallingIdentity(origId);
1854 }
1855 }
1856
1857 @Override
1858 public boolean convertToTranslucent(IBinder token, Bundle options) {
1859 SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(options);
1860 final long origId = Binder.clearCallingIdentity();
1861 try {
1862 synchronized (mGlobalLock) {
1863 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1864 if (r == null) {
1865 return false;
1866 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001867 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001868 int index = task.mActivities.lastIndexOf(r);
1869 if (index > 0) {
1870 ActivityRecord under = task.mActivities.get(index - 1);
1871 under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null;
1872 }
1873 final boolean translucentChanged = r.changeWindowTranslucency(false);
1874 if (translucentChanged) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001875 r.getActivityStack().convertActivityToTranslucent(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001876 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08001877 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001878 mWindowManager.setAppFullscreen(token, false);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001879 return translucentChanged;
1880 }
1881 } finally {
1882 Binder.restoreCallingIdentity(origId);
1883 }
1884 }
1885
1886 @Override
1887 public void notifyActivityDrawn(IBinder token) {
1888 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token);
1889 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001890 ActivityRecord r = mRootActivityContainer.isInAnyStack(token);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001891 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08001892 r.getActivityStack().notifyActivityDrawnLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001893 }
1894 }
1895 }
1896
1897 @Override
1898 public void reportActivityFullyDrawn(IBinder token, boolean restoredFromBundle) {
1899 synchronized (mGlobalLock) {
1900 ActivityRecord r = ActivityRecord.isInStackLocked(token);
1901 if (r == null) {
1902 return;
1903 }
1904 r.reportFullyDrawnLocked(restoredFromBundle);
1905 }
1906 }
1907
1908 @Override
1909 public int getActivityDisplayId(IBinder activityToken) throws RemoteException {
1910 synchronized (mGlobalLock) {
1911 final ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
1912 if (stack != null && stack.mDisplayId != INVALID_DISPLAY) {
1913 return stack.mDisplayId;
1914 }
1915 return DEFAULT_DISPLAY;
1916 }
1917 }
1918
1919 @Override
1920 public ActivityManager.StackInfo getFocusedStackInfo() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001921 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001922 long ident = Binder.clearCallingIdentity();
1923 try {
1924 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07001925 ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001926 if (focusedStack != null) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001927 return mRootActivityContainer.getStackInfo(focusedStack.mStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001928 }
1929 return null;
1930 }
1931 } finally {
1932 Binder.restoreCallingIdentity(ident);
1933 }
1934 }
1935
1936 @Override
1937 public void setFocusedStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001938 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001939 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId);
1940 final long callingId = Binder.clearCallingIdentity();
1941 try {
1942 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001943 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001944 if (stack == null) {
1945 Slog.w(TAG, "setFocusedStack: No stack with id=" + stackId);
1946 return;
1947 }
1948 final ActivityRecord r = stack.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001949 if (r != null && r.moveFocusableActivityToTop("setFocusedStack")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001950 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001951 }
1952 }
1953 } finally {
1954 Binder.restoreCallingIdentity(callingId);
1955 }
1956 }
1957
1958 @Override
1959 public void setFocusedTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001960 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "setFocusedTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001961 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedTask: taskId=" + taskId);
1962 final long callingId = Binder.clearCallingIdentity();
1963 try {
1964 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001965 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08001966 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001967 if (task == null) {
1968 return;
1969 }
1970 final ActivityRecord r = task.topRunningActivityLocked();
Louis Chang19443452018-10-09 12:10:21 +08001971 if (r != null && r.moveFocusableActivityToTop("setFocusedTask")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08001972 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001973 }
1974 }
1975 } finally {
1976 Binder.restoreCallingIdentity(callingId);
1977 }
1978 }
1979
1980 @Override
1981 public boolean removeTask(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07001982 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001983 synchronized (mGlobalLock) {
1984 final long ident = Binder.clearCallingIdentity();
1985 try {
1986 return mStackSupervisor.removeTaskByIdLocked(taskId, true, REMOVE_FROM_RECENTS,
1987 "remove-task");
1988 } finally {
1989 Binder.restoreCallingIdentity(ident);
1990 }
1991 }
1992 }
1993
1994 @Override
Winson Chunge6439102018-07-30 15:48:01 -07001995 public void removeAllVisibleRecentTasks() {
1996 enforceCallerIsRecentsOrHasPermission(REMOVE_TASKS, "removeAllVisibleRecentTasks()");
1997 synchronized (mGlobalLock) {
1998 final long ident = Binder.clearCallingIdentity();
1999 try {
2000 getRecentTasks().removeAllVisibleTasks();
2001 } finally {
2002 Binder.restoreCallingIdentity(ident);
2003 }
2004 }
2005 }
2006
2007 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002008 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) {
2009 synchronized (mGlobalLock) {
2010 final ActivityRecord srec = ActivityRecord.forTokenLocked(token);
2011 if (srec != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002012 return srec.getActivityStack().shouldUpRecreateTaskLocked(srec, destAffinity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002013 }
2014 }
2015 return false;
2016 }
2017
2018 @Override
2019 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
2020 Intent resultData) {
2021
2022 synchronized (mGlobalLock) {
2023 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2024 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002025 return r.getActivityStack().navigateUpToLocked(
2026 r, destIntent, resultCode, resultData);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002027 }
2028 return false;
2029 }
2030 }
2031
2032 /**
2033 * Attempts to move a task backwards in z-order (the order of activities within the task is
2034 * unchanged).
2035 *
2036 * There are several possible results of this call:
2037 * - if the task is locked, then we will show the lock toast
2038 * - if there is a task behind the provided task, then that task is made visible and resumed as
2039 * this task is moved to the back
2040 * - otherwise, if there are no other tasks in the stack:
2041 * - if this task is in the pinned stack, then we remove the stack completely, which will
2042 * have the effect of moving the task to the top or bottom of the fullscreen stack
2043 * (depending on whether it is visible)
2044 * - otherwise, we simply return home and hide this task
2045 *
2046 * @param token A reference to the activity we wish to move
2047 * @param nonRoot If false then this only works if the activity is the root
2048 * of a task; if true it will work for any activity in a task.
2049 * @return Returns true if the move completed, false if not.
2050 */
2051 @Override
2052 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002053 enforceNotIsolatedCaller("moveActivityTaskToBack");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002054 synchronized (mGlobalLock) {
2055 final long origId = Binder.clearCallingIdentity();
2056 try {
2057 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002058 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002059 if (task != null) {
2060 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId);
2061 }
2062 } finally {
2063 Binder.restoreCallingIdentity(origId);
2064 }
2065 }
2066 return false;
2067 }
2068
2069 @Override
2070 public Rect getTaskBounds(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002071 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "getTaskBounds()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002072 long ident = Binder.clearCallingIdentity();
2073 Rect rect = new Rect();
2074 try {
2075 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002076 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002077 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2078 if (task == null) {
2079 Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found");
2080 return rect;
2081 }
2082 if (task.getStack() != null) {
2083 // Return the bounds from window manager since it will be adjusted for various
2084 // things like the presense of a docked stack for tasks that aren't resizeable.
2085 task.getWindowContainerBounds(rect);
2086 } else {
2087 // Task isn't in window manager yet since it isn't associated with a stack.
2088 // Return the persist value from activity manager
2089 if (!task.matchParentBounds()) {
2090 rect.set(task.getBounds());
2091 } else if (task.mLastNonFullscreenBounds != null) {
2092 rect.set(task.mLastNonFullscreenBounds);
2093 }
2094 }
2095 }
2096 } finally {
2097 Binder.restoreCallingIdentity(ident);
2098 }
2099 return rect;
2100 }
2101
2102 @Override
2103 public ActivityManager.TaskDescription getTaskDescription(int id) {
2104 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002105 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002106 MANAGE_ACTIVITY_STACKS, "getTaskDescription()");
Wale Ogunwaled32da472018-11-16 07:19:28 -08002107 final TaskRecord tr = mRootActivityContainer.anyTaskForId(id,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002108 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2109 if (tr != null) {
2110 return tr.lastTaskDescription;
2111 }
2112 }
2113 return null;
2114 }
2115
2116 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002117 public void setTaskWindowingMode(int taskId, int windowingMode, boolean toTop) {
2118 if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
2119 setTaskWindowingModeSplitScreenPrimary(taskId, SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
2120 toTop, ANIMATE, null /* initialBounds */, true /* showRecents */);
2121 return;
2122 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002123 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setTaskWindowingMode()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002124 synchronized (mGlobalLock) {
2125 final long ident = Binder.clearCallingIdentity();
2126 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002127 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002128 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002129 if (task == null) {
2130 Slog.w(TAG, "setTaskWindowingMode: No task for id=" + taskId);
2131 return;
2132 }
2133
2134 if (DEBUG_STACK) Slog.d(TAG_STACK, "setTaskWindowingMode: moving task=" + taskId
2135 + " to windowingMode=" + windowingMode + " toTop=" + toTop);
2136
2137 if (!task.isActivityTypeStandardOrUndefined()) {
2138 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2139 + " non-standard task " + taskId + " to windowing mode="
2140 + windowingMode);
2141 }
2142
2143 final ActivityStack stack = task.getStack();
2144 if (toTop) {
2145 stack.moveToFront("setTaskWindowingMode", task);
2146 }
2147 stack.setWindowingMode(windowingMode);
2148 } finally {
2149 Binder.restoreCallingIdentity(ident);
2150 }
2151 }
2152 }
2153
2154 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002155 public String getCallingPackage(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002156 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002157 ActivityRecord r = getCallingRecordLocked(token);
2158 return r != null ? r.info.packageName : null;
2159 }
2160 }
2161
2162 @Override
2163 public ComponentName getCallingActivity(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002164 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002165 ActivityRecord r = getCallingRecordLocked(token);
2166 return r != null ? r.intent.getComponent() : null;
2167 }
2168 }
2169
2170 private ActivityRecord getCallingRecordLocked(IBinder token) {
2171 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2172 if (r == null) {
2173 return null;
2174 }
2175 return r.resultTo;
2176 }
2177
2178 @Override
2179 public void unhandledBack() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002180 mAmInternal.enforceCallingPermission(android.Manifest.permission.FORCE_BACK, "unhandledBack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002181
2182 synchronized (mGlobalLock) {
2183 final long origId = Binder.clearCallingIdentity();
2184 try {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07002185 getTopDisplayFocusedStack().unhandledBackLocked();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002186 } finally {
2187 Binder.restoreCallingIdentity(origId);
2188 }
2189 }
2190 }
2191
2192 /**
2193 * TODO: Add mController hook
2194 */
2195 @Override
2196 public void moveTaskToFront(int taskId, int flags, Bundle bOptions) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002197 mAmInternal.enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002198
2199 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId);
2200 synchronized (mGlobalLock) {
2201 moveTaskToFrontLocked(taskId, flags, SafeActivityOptions.fromBundle(bOptions),
2202 false /* fromRecents */);
2203 }
2204 }
2205
2206 void moveTaskToFrontLocked(int taskId, int flags, SafeActivityOptions options,
2207 boolean fromRecents) {
2208
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002209 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002210 Binder.getCallingUid(), -1, -1, "Task to front")) {
2211 SafeActivityOptions.abort(options);
2212 return;
2213 }
2214 final long origId = Binder.clearCallingIdentity();
2215 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002216 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002217 if (task == null) {
2218 Slog.d(TAG, "Could not find task for id: "+ taskId);
Winson Chungd0243682018-09-25 18:11:54 -07002219 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002220 return;
2221 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002222 if (getLockTaskController().isLockTaskModeViolation(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002223 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
Winson Chungd0243682018-09-25 18:11:54 -07002224 SafeActivityOptions.abort(options);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002225 return;
2226 }
2227 ActivityOptions realOptions = options != null
2228 ? options.getOptions(mStackSupervisor)
2229 : null;
2230 mStackSupervisor.findTaskToMoveToFront(task, flags, realOptions, "moveTaskToFront",
2231 false /* forceNonResizable */);
2232
2233 final ActivityRecord topActivity = task.getTopActivity();
2234 if (topActivity != null) {
2235
2236 // We are reshowing a task, use a starting window to hide the initial draw delay
2237 // so the transition can start earlier.
2238 topActivity.showStartingWindow(null /* prev */, false /* newTask */,
2239 true /* taskSwitch */, fromRecents);
2240 }
2241 } finally {
2242 Binder.restoreCallingIdentity(origId);
2243 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002244 }
2245
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002246 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid,
2247 int callingPid, int callingUid, String name) {
2248 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
2249 return true;
2250 }
2251
2252 if (getRecentTasks().isCallerRecents(sourceUid)) {
2253 return true;
2254 }
2255
2256 int perm = checkComponentPermission(STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true);
2257 if (perm == PackageManager.PERMISSION_GRANTED) {
2258 return true;
2259 }
2260 if (checkAllowAppSwitchUid(sourceUid)) {
2261 return true;
2262 }
2263
2264 // If the actual IPC caller is different from the logical source, then
2265 // also see if they are allowed to control app switches.
2266 if (callingUid != -1 && callingUid != sourceUid) {
2267 perm = checkComponentPermission(STOP_APP_SWITCHES, callingPid, callingUid, -1, true);
2268 if (perm == PackageManager.PERMISSION_GRANTED) {
2269 return true;
2270 }
2271 if (checkAllowAppSwitchUid(callingUid)) {
2272 return true;
2273 }
2274 }
2275
2276 Slog.w(TAG, name + " request from " + sourceUid + " stopped");
2277 return false;
2278 }
2279
2280 private boolean checkAllowAppSwitchUid(int uid) {
2281 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(UserHandle.getUserId(uid));
2282 if (types != null) {
2283 for (int i = types.size() - 1; i >= 0; i--) {
2284 if (types.valueAt(i).intValue() == uid) {
2285 return true;
2286 }
2287 }
2288 }
2289 return false;
2290 }
2291
2292 @Override
2293 public void setActivityController(IActivityController controller, boolean imAMonkey) {
2294 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
2295 "setActivityController()");
2296 synchronized (mGlobalLock) {
2297 mController = controller;
2298 mControllerIsAMonkey = imAMonkey;
2299 Watchdog.getInstance().setActivityController(controller);
2300 }
2301 }
2302
Wale Ogunwale387b34c2018-10-25 19:59:40 -07002303 public boolean isControllerAMonkey() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002304 synchronized (mGlobalLock) {
2305 return mController != null && mControllerIsAMonkey;
2306 }
2307 }
2308
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002309 @Override
2310 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
2311 synchronized (mGlobalLock) {
2312 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
2313 }
2314 }
2315
2316 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002317 public List<ActivityManager.RunningTaskInfo> getTasks(int maxNum) {
2318 return getFilteredTasks(maxNum, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED);
2319 }
2320
2321 @Override
2322 public List<ActivityManager.RunningTaskInfo> getFilteredTasks(int maxNum,
2323 @WindowConfiguration.ActivityType int ignoreActivityType,
2324 @WindowConfiguration.WindowingMode int ignoreWindowingMode) {
2325 final int callingUid = Binder.getCallingUid();
2326 ArrayList<ActivityManager.RunningTaskInfo> list = new ArrayList<>();
2327
2328 synchronized (mGlobalLock) {
2329 if (DEBUG_ALL) Slog.v(TAG, "getTasks: max=" + maxNum);
2330
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002331 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(),
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002332 callingUid);
Wale Ogunwaled32da472018-11-16 07:19:28 -08002333 mRootActivityContainer.getRunningTasks(maxNum, list, ignoreActivityType,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002334 ignoreWindowingMode, callingUid, allowed);
2335 }
2336
2337 return list;
2338 }
2339
2340 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002341 public final void finishSubActivity(IBinder token, String resultWho, int requestCode) {
2342 synchronized (mGlobalLock) {
2343 final long origId = Binder.clearCallingIdentity();
2344 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2345 if (r != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002346 r.getActivityStack().finishSubActivityLocked(r, resultWho, requestCode);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002347 }
2348 Binder.restoreCallingIdentity(origId);
2349 }
2350 }
2351
2352 @Override
2353 public boolean willActivityBeVisible(IBinder token) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002354 synchronized (mGlobalLock) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002355 ActivityStack stack = ActivityRecord.getStackLocked(token);
2356 if (stack != null) {
2357 return stack.willActivityBeVisibleLocked(token);
2358 }
2359 return false;
2360 }
2361 }
2362
2363 @Override
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002364 public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002365 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "moveTaskToStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002366 synchronized (mGlobalLock) {
2367 final long ident = Binder.clearCallingIdentity();
2368 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002369 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002370 if (task == null) {
2371 Slog.w(TAG, "moveTaskToStack: No task for id=" + taskId);
2372 return;
2373 }
2374
2375 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId
2376 + " to stackId=" + stackId + " toTop=" + toTop);
2377
Wale Ogunwaled32da472018-11-16 07:19:28 -08002378 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002379 if (stack == null) {
2380 throw new IllegalStateException(
2381 "moveTaskToStack: No stack for stackId=" + stackId);
2382 }
2383 if (!stack.isActivityTypeStandardOrUndefined()) {
2384 throw new IllegalArgumentException("moveTaskToStack: Attempt to move task "
2385 + taskId + " to stack " + stackId);
2386 }
2387 if (stack.inSplitScreenPrimaryWindowingMode()) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002388 mWindowManager.setDockedStackCreateState(
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002389 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, null /* initialBounds */);
2390 }
2391 task.reparent(stack, toTop, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE, !DEFER_RESUME,
2392 "moveTaskToStack");
2393 } finally {
2394 Binder.restoreCallingIdentity(ident);
2395 }
2396 }
2397 }
2398
2399 @Override
2400 public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
2401 boolean preserveWindows, boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002402 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeStack()");
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002403
2404 final long ident = Binder.clearCallingIdentity();
2405 try {
2406 synchronized (mGlobalLock) {
2407 if (animate) {
Yunfan Chen279f5582018-12-12 15:24:50 -08002408 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002409 if (stack == null) {
2410 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2411 return;
2412 }
2413 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
2414 throw new IllegalArgumentException("Stack: " + stackId
2415 + " doesn't support animated resize.");
2416 }
2417 stack.animateResizePinnedStack(null /* sourceHintBounds */, destBounds,
2418 animationDuration, false /* fromFullscreen */);
2419 } else {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002420 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002421 if (stack == null) {
2422 Slog.w(TAG, "resizeStack: stackId " + stackId + " not found.");
2423 return;
2424 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08002425 mRootActivityContainer.resizeStack(stack, destBounds,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002426 null /* tempTaskBounds */, null /* tempTaskInsetBounds */,
2427 preserveWindows, allowResizeInDockedMode, !DEFER_RESUME);
2428 }
2429 }
2430 } finally {
2431 Binder.restoreCallingIdentity(ident);
2432 }
2433 }
2434
2435 /**
2436 * Moves the specified task to the primary-split-screen stack.
2437 *
2438 * @param taskId Id of task to move.
2439 * @param createMode The mode the primary split screen stack should be created in if it doesn't
2440 * exist already. See
2441 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT}
2442 * and
2443 * {@link android.app.ActivityTaskManager#SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT}
2444 * @param toTop If the task and stack should be moved to the top.
2445 * @param animate Whether we should play an animation for the moving the task.
2446 * @param initialBounds If the primary stack gets created, it will use these bounds for the
2447 * stack. Pass {@code null} to use default bounds.
2448 * @param showRecents If the recents activity should be shown on the other side of the task
2449 * going into split-screen mode.
2450 */
2451 @Override
2452 public boolean setTaskWindowingModeSplitScreenPrimary(int taskId, int createMode,
2453 boolean toTop, boolean animate, Rect initialBounds, boolean showRecents) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002454 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002455 "setTaskWindowingModeSplitScreenPrimary()");
2456 synchronized (mGlobalLock) {
2457 final long ident = Binder.clearCallingIdentity();
2458 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002459 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002460 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002461 if (task == null) {
2462 Slog.w(TAG, "setTaskWindowingModeSplitScreenPrimary: No task for id=" + taskId);
2463 return false;
2464 }
2465 if (DEBUG_STACK) Slog.d(TAG_STACK,
2466 "setTaskWindowingModeSplitScreenPrimary: moving task=" + taskId
2467 + " to createMode=" + createMode + " toTop=" + toTop);
2468 if (!task.isActivityTypeStandardOrUndefined()) {
2469 throw new IllegalArgumentException("setTaskWindowingMode: Attempt to move"
2470 + " non-standard task " + taskId + " to split-screen windowing mode");
2471 }
2472
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002473 mWindowManager.setDockedStackCreateState(createMode, initialBounds);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002474 final int windowingMode = task.getWindowingMode();
2475 final ActivityStack stack = task.getStack();
2476 if (toTop) {
2477 stack.moveToFront("setTaskWindowingModeSplitScreenPrimary", task);
2478 }
2479 stack.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, animate, showRecents,
Evan Roskyc5abbd82018-10-05 16:02:19 -07002480 false /* enteringSplitScreenMode */, false /* deferEnsuringVisibility */,
2481 false /* creating */);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002482 return windowingMode != task.getWindowingMode();
2483 } finally {
2484 Binder.restoreCallingIdentity(ident);
2485 }
2486 }
2487 }
2488
2489 /**
2490 * Removes stacks in the input windowing modes from the system if they are of activity type
2491 * ACTIVITY_TYPE_STANDARD or ACTIVITY_TYPE_UNDEFINED
2492 */
2493 @Override
2494 public void removeStacksInWindowingModes(int[] windowingModes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002495 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002496 "removeStacksInWindowingModes()");
2497
2498 synchronized (mGlobalLock) {
2499 final long ident = Binder.clearCallingIdentity();
2500 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002501 mRootActivityContainer.removeStacksInWindowingModes(windowingModes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002502 } finally {
2503 Binder.restoreCallingIdentity(ident);
2504 }
2505 }
2506 }
2507
2508 @Override
2509 public void removeStacksWithActivityTypes(int[] activityTypes) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002510 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002511 "removeStacksWithActivityTypes()");
2512
2513 synchronized (mGlobalLock) {
2514 final long ident = Binder.clearCallingIdentity();
2515 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002516 mRootActivityContainer.removeStacksWithActivityTypes(activityTypes);
Wale Ogunwale65ebd952018-04-25 15:41:44 -07002517 } finally {
2518 Binder.restoreCallingIdentity(ident);
2519 }
2520 }
2521 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002522
2523 @Override
2524 public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
2525 int userId) {
2526 final int callingUid = Binder.getCallingUid();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002527 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, "getRecentTasks");
2528 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(),
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002529 callingUid);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002530 final boolean detailed = checkGetTasksPermission(
2531 android.Manifest.permission.GET_DETAILED_TASKS, Binder.getCallingPid(),
2532 UserHandle.getAppId(callingUid))
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002533 == PackageManager.PERMISSION_GRANTED;
2534
2535 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002536 return mRecentTasks.getRecentTasks(maxNum, flags, allowed, detailed, userId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002537 callingUid);
2538 }
2539 }
2540
2541 @Override
2542 public List<ActivityManager.StackInfo> getAllStackInfos() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002543 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getAllStackInfos()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002544 long ident = Binder.clearCallingIdentity();
2545 try {
2546 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002547 return mRootActivityContainer.getAllStackInfos();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002548 }
2549 } finally {
2550 Binder.restoreCallingIdentity(ident);
2551 }
2552 }
2553
2554 @Override
2555 public ActivityManager.StackInfo getStackInfo(int windowingMode, int activityType) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002556 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "getStackInfo()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002557 long ident = Binder.clearCallingIdentity();
2558 try {
2559 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002560 return mRootActivityContainer.getStackInfo(windowingMode, activityType);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002561 }
2562 } finally {
2563 Binder.restoreCallingIdentity(ident);
2564 }
2565 }
2566
2567 @Override
2568 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002569 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "cancelRecentsAnimation()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002570 final long callingUid = Binder.getCallingUid();
2571 final long origId = Binder.clearCallingIdentity();
2572 try {
2573 synchronized (mGlobalLock) {
2574 // Cancel the recents animation synchronously (do not hold the WM lock)
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002575 mWindowManager.cancelRecentsAnimationSynchronously(restoreHomeStackPosition
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002576 ? REORDER_MOVE_TO_ORIGINAL_POSITION
2577 : REORDER_KEEP_IN_PLACE, "cancelRecentsAnimation/uid=" + callingUid);
2578 }
2579 } finally {
2580 Binder.restoreCallingIdentity(origId);
2581 }
2582 }
2583
2584 @Override
2585 public void startLockTaskModeByToken(IBinder token) {
2586 synchronized (mGlobalLock) {
2587 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2588 if (r == null) {
2589 return;
2590 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002591 startLockTaskModeLocked(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002592 }
2593 }
2594
2595 @Override
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002596 public void startSystemLockTaskMode(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002597 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "startSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002598 // This makes inner call to look as if it was initiated by system.
2599 long ident = Binder.clearCallingIdentity();
2600 try {
2601 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002602 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002603 MATCH_TASK_IN_STACKS_ONLY);
2604 if (task == null) {
2605 return;
2606 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002607
2608 // When starting lock task mode the stack must be in front and focused
2609 task.getStack().moveToFront("startSystemLockTaskMode");
2610 startLockTaskModeLocked(task, true /* isSystemCaller */);
2611 }
2612 } finally {
2613 Binder.restoreCallingIdentity(ident);
2614 }
2615 }
2616
2617 @Override
2618 public void stopLockTaskModeByToken(IBinder token) {
2619 synchronized (mGlobalLock) {
2620 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
2621 if (r == null) {
2622 return;
2623 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002624 stopLockTaskModeInternal(r.getTaskRecord(), false /* isSystemCaller */);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002625 }
2626 }
2627
2628 /**
2629 * This API should be called by SystemUI only when user perform certain action to dismiss
2630 * lock task mode. We should only dismiss pinned lock task mode in this case.
2631 */
2632 @Override
2633 public void stopSystemLockTaskMode() throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002634 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "stopSystemLockTaskMode");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002635 stopLockTaskModeInternal(null, true /* isSystemCaller */);
2636 }
2637
2638 private void startLockTaskModeLocked(@Nullable TaskRecord task, boolean isSystemCaller) {
2639 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task);
2640 if (task == null || task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
2641 return;
2642 }
2643
Wale Ogunwaled32da472018-11-16 07:19:28 -08002644 final ActivityStack stack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002645 if (stack == null || task != stack.topTask()) {
2646 throw new IllegalArgumentException("Invalid task, not in foreground");
2647 }
2648
2649 // {@code isSystemCaller} is used to distinguish whether this request is initiated by the
2650 // system or a specific app.
2651 // * System-initiated requests will only start the pinned mode (screen pinning)
2652 // * App-initiated requests
2653 // - will put the device in fully locked mode (LockTask), if the app is whitelisted
2654 // - will start the pinned mode, otherwise
2655 final int callingUid = Binder.getCallingUid();
2656 long ident = Binder.clearCallingIdentity();
2657 try {
2658 // When a task is locked, dismiss the pinned stack if it exists
Wale Ogunwaled32da472018-11-16 07:19:28 -08002659 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002660
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002661 getLockTaskController().startLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002662 } finally {
2663 Binder.restoreCallingIdentity(ident);
2664 }
2665 }
2666
2667 private void stopLockTaskModeInternal(@Nullable TaskRecord task, boolean isSystemCaller) {
2668 final int callingUid = Binder.getCallingUid();
2669 long ident = Binder.clearCallingIdentity();
2670 try {
2671 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002672 getLockTaskController().stopLockTaskMode(task, isSystemCaller, callingUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002673 }
2674 // Launch in-call UI if a call is ongoing. This is necessary to allow stopping the lock
2675 // task and jumping straight into a call in the case of emergency call back.
2676 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2677 if (tm != null) {
2678 tm.showInCallScreen(false);
2679 }
2680 } finally {
2681 Binder.restoreCallingIdentity(ident);
2682 }
2683 }
2684
2685 @Override
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07002686 public void updateLockTaskPackages(int userId, String[] packages) {
2687 final int callingUid = Binder.getCallingUid();
2688 if (callingUid != 0 && callingUid != SYSTEM_UID) {
2689 mAmInternal.enforceCallingPermission(Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
2690 "updateLockTaskPackages()");
2691 }
2692 synchronized (this) {
2693 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":"
2694 + Arrays.toString(packages));
2695 getLockTaskController().updateLockTaskPackages(userId, packages);
2696 }
2697 }
2698
2699 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002700 public boolean isInLockTaskMode() {
2701 return getLockTaskModeState() != LOCK_TASK_MODE_NONE;
2702 }
2703
2704 @Override
2705 public int getLockTaskModeState() {
2706 synchronized (mGlobalLock) {
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07002707 return getLockTaskController().getLockTaskModeState();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002708 }
2709 }
2710
2711 @Override
2712 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
2713 synchronized (mGlobalLock) {
2714 ActivityRecord r = ActivityRecord.isInStackLocked(token);
2715 if (r != null) {
2716 r.setTaskDescription(td);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002717 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002718 task.updateTaskDescription();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002719 mTaskChangeNotificationController.notifyTaskDescriptionChanged(task.taskId, td);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002720 }
2721 }
2722 }
2723
2724 @Override
2725 public Bundle getActivityOptions(IBinder token) {
2726 final long origId = Binder.clearCallingIdentity();
2727 try {
2728 synchronized (mGlobalLock) {
2729 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
2730 if (r != null) {
2731 final ActivityOptions activityOptions = r.takeOptionsLocked();
2732 return activityOptions == null ? null : activityOptions.toBundle();
2733 }
2734 return null;
2735 }
2736 } finally {
2737 Binder.restoreCallingIdentity(origId);
2738 }
2739 }
2740
2741 @Override
2742 public List<IBinder> getAppTasks(String callingPackage) {
2743 int callingUid = Binder.getCallingUid();
2744 long ident = Binder.clearCallingIdentity();
2745 try {
2746 synchronized (mGlobalLock) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002747 return mRecentTasks.getAppTasksList(callingUid, callingPackage);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002748 }
2749 } finally {
2750 Binder.restoreCallingIdentity(ident);
2751 }
2752 }
2753
2754 @Override
2755 public void finishVoiceTask(IVoiceInteractionSession session) {
2756 synchronized (mGlobalLock) {
2757 final long origId = Binder.clearCallingIdentity();
2758 try {
2759 // TODO: VI Consider treating local voice interactions and voice tasks
2760 // differently here
Wale Ogunwaled32da472018-11-16 07:19:28 -08002761 mRootActivityContainer.finishVoiceTask(session);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002762 } finally {
2763 Binder.restoreCallingIdentity(origId);
2764 }
2765 }
2766
2767 }
2768
2769 @Override
2770 public boolean isTopOfTask(IBinder token) {
2771 synchronized (mGlobalLock) {
2772 ActivityRecord r = ActivityRecord.isInStackLocked(token);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002773 return r != null && r.getTaskRecord().getTopActivity() == r;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002774 }
2775 }
2776
2777 @Override
2778 public void notifyLaunchTaskBehindComplete(IBinder token) {
2779 mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
2780 }
2781
2782 @Override
2783 public void notifyEnterAnimationComplete(IBinder token) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002784 mH.post(() -> {
2785 synchronized (mGlobalLock) {
2786 ActivityRecord r = ActivityRecord.forTokenLocked(token);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002787 if (r != null && r.attachedToProcess()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002788 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07002789 r.app.getThread().scheduleEnterAnimationComplete(r.appToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07002790 } catch (RemoteException e) {
2791 }
2792 }
2793 }
2794
2795 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002796 }
2797
2798 /** Called from an app when assist data is ready. */
2799 @Override
2800 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
2801 AssistContent content, Uri referrer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002802 PendingAssistExtras pae = (PendingAssistExtras) token;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002803 synchronized (pae) {
2804 pae.result = extras;
2805 pae.structure = structure;
2806 pae.content = content;
2807 if (referrer != null) {
2808 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer);
2809 }
2810 if (structure != null) {
Winson Chung48b25652018-10-22 14:04:30 -07002811 // Pre-fill the task/activity component for all assist data receivers
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002812 structure.setTaskId(pae.activity.getTaskRecord().taskId);
2813 structure.setActivityComponent(pae.activity.mActivityComponent);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002814 structure.setHomeActivity(pae.isHome);
2815 }
2816 pae.haveResult = true;
2817 pae.notifyAll();
2818 if (pae.intent == null && pae.receiver == null) {
2819 // Caller is just waiting for the result.
2820 return;
2821 }
2822 }
2823 // We are now ready to launch the assist activity.
2824 IAssistDataReceiver sendReceiver = null;
2825 Bundle sendBundle = null;
2826 synchronized (mGlobalLock) {
2827 buildAssistBundleLocked(pae, extras);
2828 boolean exists = mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002829 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002830 if (!exists) {
2831 // Timed out.
2832 return;
2833 }
2834
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002835 if ((sendReceiver = pae.receiver) != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002836 // Caller wants result sent back to them.
2837 sendBundle = new Bundle();
2838 sendBundle.putBundle(ASSIST_KEY_DATA, pae.extras);
2839 sendBundle.putParcelable(ASSIST_KEY_STRUCTURE, pae.structure);
2840 sendBundle.putParcelable(ASSIST_KEY_CONTENT, pae.content);
2841 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
2842 }
2843 }
2844 if (sendReceiver != null) {
2845 try {
2846 sendReceiver.onHandleAssistData(sendBundle);
2847 } catch (RemoteException e) {
2848 }
2849 return;
2850 }
2851
2852 final long ident = Binder.clearCallingIdentity();
2853 try {
2854 if (TextUtils.equals(pae.intent.getAction(),
2855 android.service.voice.VoiceInteractionService.SERVICE_INTERFACE)) {
2856 pae.intent.putExtras(pae.extras);
2857 mContext.startServiceAsUser(pae.intent, new UserHandle(pae.userHandle));
2858 } else {
2859 pae.intent.replaceExtras(pae.extras);
2860 pae.intent.setFlags(FLAG_ACTIVITY_NEW_TASK
2861 | Intent.FLAG_ACTIVITY_SINGLE_TOP
2862 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Wale Ogunwale31913b52018-10-13 08:29:31 -07002863 mInternal.closeSystemDialogs("assist");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002864
2865 try {
2866 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle));
2867 } catch (ActivityNotFoundException e) {
2868 Slog.w(TAG, "No activity to handle assist action.", e);
2869 }
2870 }
2871 } finally {
2872 Binder.restoreCallingIdentity(ident);
2873 }
2874 }
2875
2876 @Override
2877 public int addAppTask(IBinder activityToken, Intent intent,
2878 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException {
2879 final int callingUid = Binder.getCallingUid();
2880 final long callingIdent = Binder.clearCallingIdentity();
2881
2882 try {
2883 synchronized (mGlobalLock) {
2884 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
2885 if (r == null) {
2886 throw new IllegalArgumentException("Activity does not exist; token="
2887 + activityToken);
2888 }
2889 ComponentName comp = intent.getComponent();
2890 if (comp == null) {
2891 throw new IllegalArgumentException("Intent " + intent
2892 + " must specify explicit component");
2893 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002894 if (thumbnail.getWidth() != mThumbnailWidth
2895 || thumbnail.getHeight() != mThumbnailHeight) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002896 throw new IllegalArgumentException("Bad thumbnail size: got "
2897 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require "
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002898 + mThumbnailWidth + "x" + mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002899 }
2900 if (intent.getSelector() != null) {
2901 intent.setSelector(null);
2902 }
2903 if (intent.getSourceBounds() != null) {
2904 intent.setSourceBounds(null);
2905 }
2906 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) {
2907 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) {
2908 // The caller has added this as an auto-remove task... that makes no
2909 // sense, so turn off auto-remove.
2910 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
2911 }
2912 }
2913 final ActivityInfo ainfo = AppGlobals.getPackageManager().getActivityInfo(comp,
2914 STOCK_PM_FLAGS, UserHandle.getUserId(callingUid));
2915 if (ainfo.applicationInfo.uid != callingUid) {
2916 throw new SecurityException(
2917 "Can't add task for another application: target uid="
2918 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid);
2919 }
2920
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002921 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002922 final TaskRecord task = stack.createTaskRecord(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08002923 mStackSupervisor.getNextTaskIdForUserLocked(r.mUserId), ainfo, intent,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002924 null /* voiceSession */, null /* voiceInteractor */, !ON_TOP);
Wale Ogunwale16e505a2018-05-07 15:00:49 -07002925 if (!mRecentTasks.addToBottom(task)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002926 // The app has too many tasks already and we can't add any more
2927 stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING);
2928 return INVALID_TASK_ID;
2929 }
2930 task.lastTaskDescription.copyFrom(description);
2931
2932 // TODO: Send the thumbnail to WM to store it.
2933
2934 return task.taskId;
2935 }
2936 } finally {
2937 Binder.restoreCallingIdentity(callingIdent);
2938 }
2939 }
2940
2941 @Override
2942 public Point getAppTaskThumbnailSize() {
2943 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002944 return new Point(mThumbnailWidth, mThumbnailHeight);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002945 }
2946 }
2947
2948 @Override
2949 public void setTaskResizeable(int taskId, int resizeableMode) {
2950 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002951 final TaskRecord task = mRootActivityContainer.anyTaskForId(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002952 taskId, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
2953 if (task == null) {
2954 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found");
2955 return;
2956 }
2957 task.setResizeMode(resizeableMode);
2958 }
2959 }
2960
2961 @Override
2962 public void resizeTask(int taskId, Rect bounds, int resizeMode) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07002963 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "resizeTask()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002964 long ident = Binder.clearCallingIdentity();
2965 try {
2966 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08002967 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Riddle Hsu090ac6f2018-10-31 12:55:29 +08002968 MATCH_TASK_IN_STACKS_ONLY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07002969 if (task == null) {
2970 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found");
2971 return;
2972 }
2973 // Place the task in the right stack if it isn't there already based on
2974 // the requested bounds.
2975 // The stack transition logic is:
2976 // - a null bounds on a freeform task moves that task to fullscreen
2977 // - a non-null bounds on a non-freeform (fullscreen OR docked) task moves
2978 // that task to freeform
2979 // - otherwise the task is not moved
2980 ActivityStack stack = task.getStack();
2981 if (!task.getWindowConfiguration().canResizeTask()) {
2982 throw new IllegalArgumentException("resizeTask not allowed on task=" + task);
2983 }
2984 if (bounds == null && stack.getWindowingMode() == WINDOWING_MODE_FREEFORM) {
2985 stack = stack.getDisplay().getOrCreateStack(
2986 WINDOWING_MODE_FULLSCREEN, stack.getActivityType(), ON_TOP);
2987 } else if (bounds != null && stack.getWindowingMode() != WINDOWING_MODE_FREEFORM) {
2988 stack = stack.getDisplay().getOrCreateStack(
2989 WINDOWING_MODE_FREEFORM, stack.getActivityType(), ON_TOP);
2990 }
2991
2992 // Reparent the task to the right stack if necessary
2993 boolean preserveWindow = (resizeMode & RESIZE_MODE_PRESERVE_WINDOW) != 0;
2994 if (stack != task.getStack()) {
2995 // Defer resume until the task is resized below
2996 task.reparent(stack, ON_TOP, REPARENT_KEEP_STACK_AT_FRONT, ANIMATE,
2997 DEFER_RESUME, "resizeTask");
2998 preserveWindow = false;
2999 }
3000
3001 // After reparenting (which only resizes the task to the stack bounds), resize the
3002 // task to the actual bounds provided
3003 task.resize(bounds, resizeMode, preserveWindow, !DEFER_RESUME);
3004 }
3005 } finally {
3006 Binder.restoreCallingIdentity(ident);
3007 }
3008 }
3009
3010 @Override
3011 public boolean releaseActivityInstance(IBinder token) {
3012 synchronized (mGlobalLock) {
3013 final long origId = Binder.clearCallingIdentity();
3014 try {
3015 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3016 if (r == null) {
3017 return false;
3018 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003019 return r.getActivityStack().safelyDestroyActivityLocked(r, "app-req");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003020 } finally {
3021 Binder.restoreCallingIdentity(origId);
3022 }
3023 }
3024 }
3025
3026 @Override
3027 public void releaseSomeActivities(IApplicationThread appInt) {
3028 synchronized (mGlobalLock) {
3029 final long origId = Binder.clearCallingIdentity();
3030 try {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003031 final WindowProcessController app = getProcessController(appInt);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003032 mRootActivityContainer.releaseSomeActivitiesLocked(app, "low-mem");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003033 } finally {
3034 Binder.restoreCallingIdentity(origId);
3035 }
3036 }
3037 }
3038
3039 @Override
3040 public void setLockScreenShown(boolean keyguardShowing, boolean aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003041 int[] secondaryDisplaysShowing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003042 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003043 != PackageManager.PERMISSION_GRANTED) {
3044 throw new SecurityException("Requires permission "
3045 + android.Manifest.permission.DEVICE_POWER);
3046 }
3047
3048 synchronized (mGlobalLock) {
3049 long ident = Binder.clearCallingIdentity();
3050 if (mKeyguardShown != keyguardShowing) {
3051 mKeyguardShown = keyguardShowing;
Wale Ogunwale342fbe92018-10-09 08:44:10 -07003052 final Message msg = PooledLambda.obtainMessage(
3053 ActivityManagerInternal::reportCurKeyguardUsageEvent, mAmInternal,
3054 keyguardShowing);
3055 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003056 }
3057 try {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003058 mKeyguardController.setKeyguardShown(keyguardShowing, aodShowing,
wilsonshihe7903ea2018-09-26 16:17:59 +08003059 secondaryDisplaysShowing);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003060 } finally {
3061 Binder.restoreCallingIdentity(ident);
3062 }
3063 }
3064
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003065 mH.post(() -> {
3066 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3067 mScreenObservers.get(i).onKeyguardStateChanged(keyguardShowing);
3068 }
3069 });
3070 }
3071
Wale Ogunwale387b34c2018-10-25 19:59:40 -07003072 public void onScreenAwakeChanged(boolean isAwake) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003073 mH.post(() -> {
3074 for (int i = mScreenObservers.size() - 1; i >= 0; i--) {
3075 mScreenObservers.get(i).onAwakeStateChanged(isAwake);
3076 }
3077 });
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003078 }
3079
3080 @Override
3081 public Bitmap getTaskDescriptionIcon(String filePath, int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003082 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3083 userId, "getTaskDescriptionIcon");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003084
3085 final File passedIconFile = new File(filePath);
3086 final File legitIconFile = new File(TaskPersister.getUserImagesDir(userId),
3087 passedIconFile.getName());
3088 if (!legitIconFile.getPath().equals(filePath)
3089 || !filePath.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) {
3090 throw new IllegalArgumentException("Bad file path: " + filePath
3091 + " passed for userId " + userId);
3092 }
Wale Ogunwale16e505a2018-05-07 15:00:49 -07003093 return mRecentTasks.getTaskDescriptionIcon(filePath);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003094 }
3095
3096 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003097 public void startInPlaceAnimationOnFrontMostApplication(Bundle opts) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003098 final SafeActivityOptions safeOptions = SafeActivityOptions.fromBundle(opts);
3099 final ActivityOptions activityOptions = safeOptions != null
3100 ? safeOptions.getOptions(mStackSupervisor)
3101 : null;
3102 if (activityOptions == null
3103 || activityOptions.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE
3104 || activityOptions.getCustomInPlaceResId() == 0) {
3105 throw new IllegalArgumentException("Expected in-place ActivityOption " +
3106 "with valid animation");
3107 }
lumark588a3e82018-07-20 18:53:54 +08003108 // Get top display of front most application.
3109 final ActivityStack focusedStack = getTopDisplayFocusedStack();
3110 if (focusedStack != null) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003111 final DisplayContent dc = focusedStack.getDisplay().mDisplayContent;
3112 dc.prepareAppTransition(TRANSIT_TASK_IN_PLACE, false);
3113 dc.mAppTransition.overrideInPlaceAppTransition(activityOptions.getPackageName(),
lumark588a3e82018-07-20 18:53:54 +08003114 activityOptions.getCustomInPlaceResId());
Wale Ogunwale3a256e62018-12-06 14:41:18 -08003115 dc.executeAppTransition();
lumark588a3e82018-07-20 18:53:54 +08003116 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003117 }
3118
3119 @Override
3120 public void removeStack(int stackId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003121 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "removeStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003122 synchronized (mGlobalLock) {
3123 final long ident = Binder.clearCallingIdentity();
3124 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003125 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003126 if (stack == null) {
3127 Slog.w(TAG, "removeStack: No stack with id=" + stackId);
3128 return;
3129 }
3130 if (!stack.isActivityTypeStandardOrUndefined()) {
3131 throw new IllegalArgumentException(
3132 "Removing non-standard stack is not allowed.");
3133 }
3134 mStackSupervisor.removeStack(stack);
3135 } finally {
3136 Binder.restoreCallingIdentity(ident);
3137 }
3138 }
3139 }
3140
3141 @Override
3142 public void moveStackToDisplay(int stackId, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003143 mAmInternal.enforceCallingPermission(INTERNAL_SYSTEM_WINDOW, "moveStackToDisplay()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003144
3145 synchronized (mGlobalLock) {
3146 final long ident = Binder.clearCallingIdentity();
3147 try {
3148 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveStackToDisplay: moving stackId=" + stackId
3149 + " to displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003150 mRootActivityContainer.moveStackToDisplay(stackId, displayId, ON_TOP);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003151 } finally {
3152 Binder.restoreCallingIdentity(ident);
3153 }
3154 }
3155 }
3156
3157 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003158 public void exitFreeformMode(IBinder token) {
3159 synchronized (mGlobalLock) {
3160 long ident = Binder.clearCallingIdentity();
3161 try {
3162 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3163 if (r == null) {
3164 throw new IllegalArgumentException(
3165 "exitFreeformMode: No activity record matching token=" + token);
3166 }
3167
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003168 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003169 if (stack == null || !stack.inFreeformWindowingMode()) {
3170 throw new IllegalStateException(
3171 "exitFreeformMode: You can only go fullscreen from freeform.");
3172 }
3173
3174 stack.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
3175 } finally {
3176 Binder.restoreCallingIdentity(ident);
3177 }
3178 }
3179 }
3180
3181 /** Sets the task stack listener that gets callbacks when a task stack changes. */
3182 @Override
3183 public void registerTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003184 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003185 "registerTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003186 mTaskChangeNotificationController.registerTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003187 }
3188
3189 /** Unregister a task stack listener so that it stops receiving callbacks. */
3190 @Override
3191 public void unregisterTaskStackListener(ITaskStackListener listener) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003192 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003193 "unregisterTaskStackListener()");
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003194 mTaskChangeNotificationController.unregisterTaskStackListener(listener);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003195 }
3196
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003197 @Override
3198 public boolean requestAssistContextExtras(int requestType, IAssistDataReceiver receiver,
3199 Bundle receiverExtras, IBinder activityToken, boolean focused, boolean newSessionId) {
3200 return enqueueAssistContext(requestType, null, null, receiver, receiverExtras,
3201 activityToken, focused, newSessionId, UserHandle.getCallingUserId(), null,
3202 PENDING_ASSIST_EXTRAS_LONG_TIMEOUT, 0) != null;
3203 }
3204
3205 @Override
3206 public boolean requestAutofillData(IAssistDataReceiver receiver, Bundle receiverExtras,
3207 IBinder activityToken, int flags) {
3208 return enqueueAssistContext(ActivityManager.ASSIST_CONTEXT_AUTOFILL, null, null,
3209 receiver, receiverExtras, activityToken, true, true, UserHandle.getCallingUserId(),
3210 null, PENDING_AUTOFILL_ASSIST_STRUCTURE_TIMEOUT, flags) != null;
3211 }
3212
3213 @Override
3214 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
3215 Bundle args) {
3216 return enqueueAssistContext(requestType, intent, hint, null, null, null,
3217 true /* focused */, true /* newSessionId */, userHandle, args,
3218 PENDING_ASSIST_EXTRAS_TIMEOUT, 0) != null;
3219 }
3220
3221 @Override
3222 public Bundle getAssistContextExtras(int requestType) {
3223 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
3224 null, null, true /* focused */, true /* newSessionId */,
3225 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT, 0);
3226 if (pae == null) {
3227 return null;
3228 }
3229 synchronized (pae) {
3230 while (!pae.haveResult) {
3231 try {
3232 pae.wait();
3233 } catch (InterruptedException e) {
3234 }
3235 }
3236 }
3237 synchronized (mGlobalLock) {
3238 buildAssistBundleLocked(pae, pae.result);
3239 mPendingAssistExtras.remove(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003240 mUiHandler.removeCallbacks(pae);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003241 }
3242 return pae.extras;
3243 }
3244
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003245 /**
3246 * Binder IPC calls go through the public entry point.
3247 * This can be called with or without the global lock held.
3248 */
3249 private static int checkCallingPermission(String permission) {
3250 return checkPermission(
3251 permission, Binder.getCallingPid(), UserHandle.getAppId(Binder.getCallingUid()));
3252 }
3253
3254 /** This can be called with or without the global lock held. */
Wale Ogunwale214f3482018-10-04 11:00:47 -07003255 private void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003256 if (!getRecentTasks().isCallerRecents(Binder.getCallingUid())) {
3257 mAmInternal.enforceCallingPermission(permission, func);
3258 }
3259 }
3260
3261 @VisibleForTesting
3262 int checkGetTasksPermission(String permission, int pid, int uid) {
3263 return checkPermission(permission, pid, uid);
3264 }
3265
3266 static int checkPermission(String permission, int pid, int uid) {
3267 if (permission == null) {
3268 return PackageManager.PERMISSION_DENIED;
3269 }
3270 return checkComponentPermission(permission, pid, uid, -1, true);
3271 }
3272
Wale Ogunwale214f3482018-10-04 11:00:47 -07003273 public static int checkComponentPermission(String permission, int pid, int uid,
3274 int owningUid, boolean exported) {
3275 return ActivityManagerService.checkComponentPermission(
3276 permission, pid, uid, owningUid, exported);
3277 }
3278
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003279 boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
3280 if (getRecentTasks().isCallerRecents(callingUid)) {
3281 // Always allow the recents component to get tasks
3282 return true;
3283 }
3284
3285 boolean allowed = checkGetTasksPermission(android.Manifest.permission.REAL_GET_TASKS,
3286 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED;
3287 if (!allowed) {
3288 if (checkGetTasksPermission(android.Manifest.permission.GET_TASKS,
3289 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) {
3290 // Temporary compatibility: some existing apps on the system image may
3291 // still be requesting the old permission and not switched to the new
3292 // one; if so, we'll still allow them full access. This means we need
3293 // to see if they are holding the old permission and are a system app.
3294 try {
3295 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) {
3296 allowed = true;
3297 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3298 + " is using old GET_TASKS but privileged; allowing");
3299 }
3300 } catch (RemoteException e) {
3301 }
3302 }
3303 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid
3304 + " does not hold REAL_GET_TASKS; limiting output");
3305 }
3306 return allowed;
3307 }
3308
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003309 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
3310 IAssistDataReceiver receiver, Bundle receiverExtras, IBinder activityToken,
3311 boolean focused, boolean newSessionId, int userHandle, Bundle args, long timeout,
3312 int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003313 mAmInternal.enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003314 "enqueueAssistContext()");
3315
3316 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003317 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003318 if (activity == null) {
3319 Slog.w(TAG, "getAssistContextExtras failed: no top activity");
3320 return null;
3321 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003322 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003323 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
3324 return null;
3325 }
3326 if (focused) {
3327 if (activityToken != null) {
3328 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
3329 if (activity != caller) {
3330 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
3331 + " is not current top " + activity);
3332 return null;
3333 }
3334 }
3335 } else {
3336 activity = ActivityRecord.forTokenLocked(activityToken);
3337 if (activity == null) {
3338 Slog.w(TAG, "enqueueAssistContext failed: activity for token=" + activityToken
3339 + " couldn't be found");
3340 return null;
3341 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003342 if (!activity.attachedToProcess()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003343 Slog.w(TAG, "enqueueAssistContext failed: no process for " + activity);
3344 return null;
3345 }
3346 }
3347
3348 PendingAssistExtras pae;
3349 Bundle extras = new Bundle();
3350 if (args != null) {
3351 extras.putAll(args);
3352 }
3353 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003354 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.mUid);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003355
3356 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, receiverExtras,
3357 userHandle);
3358 pae.isHome = activity.isActivityTypeHome();
3359
3360 // Increment the sessionId if necessary
3361 if (newSessionId) {
3362 mViSessionId++;
3363 }
3364 try {
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07003365 activity.app.getThread().requestAssistContextExtras(activity.appToken, pae,
3366 requestType, mViSessionId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003367 mPendingAssistExtras.add(pae);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003368 mUiHandler.postDelayed(pae, timeout);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003369 } catch (RemoteException e) {
3370 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
3371 return null;
3372 }
3373 return pae;
3374 }
3375 }
3376
3377 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) {
3378 if (result != null) {
3379 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result);
3380 }
3381 if (pae.hint != null) {
3382 pae.extras.putBoolean(pae.hint, true);
3383 }
3384 }
3385
3386 private void pendingAssistExtrasTimedOut(PendingAssistExtras pae) {
3387 IAssistDataReceiver receiver;
3388 synchronized (mGlobalLock) {
3389 mPendingAssistExtras.remove(pae);
3390 receiver = pae.receiver;
3391 }
3392 if (receiver != null) {
3393 // Caller wants result sent back to them.
3394 Bundle sendBundle = new Bundle();
3395 // At least return the receiver extras
3396 sendBundle.putBundle(ASSIST_KEY_RECEIVER_EXTRAS, pae.receiverExtras);
3397 try {
3398 pae.receiver.onHandleAssistData(sendBundle);
3399 } catch (RemoteException e) {
3400 }
3401 }
3402 }
3403
3404 public class PendingAssistExtras extends Binder implements Runnable {
3405 public final ActivityRecord activity;
3406 public boolean isHome;
3407 public final Bundle extras;
3408 public final Intent intent;
3409 public final String hint;
3410 public final IAssistDataReceiver receiver;
3411 public final int userHandle;
3412 public boolean haveResult = false;
3413 public Bundle result = null;
3414 public AssistStructure structure = null;
3415 public AssistContent content = null;
3416 public Bundle receiverExtras;
3417
3418 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent,
3419 String _hint, IAssistDataReceiver _receiver, Bundle _receiverExtras,
3420 int _userHandle) {
3421 activity = _activity;
3422 extras = _extras;
3423 intent = _intent;
3424 hint = _hint;
3425 receiver = _receiver;
3426 receiverExtras = _receiverExtras;
3427 userHandle = _userHandle;
3428 }
3429
3430 @Override
3431 public void run() {
3432 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
3433 synchronized (this) {
3434 haveResult = true;
3435 notifyAll();
3436 }
3437 pendingAssistExtrasTimedOut(this);
3438 }
3439 }
3440
3441 @Override
3442 public boolean isAssistDataAllowedOnCurrentActivity() {
3443 int userId;
3444 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003445 final ActivityStack focusedStack = getTopDisplayFocusedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003446 if (focusedStack == null || focusedStack.isActivityTypeAssistant()) {
3447 return false;
3448 }
3449
3450 final ActivityRecord activity = focusedStack.getTopActivity();
3451 if (activity == null) {
3452 return false;
3453 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003454 userId = activity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003455 }
3456 return !DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId);
3457 }
3458
3459 @Override
3460 public boolean showAssistFromActivity(IBinder token, Bundle args) {
3461 long ident = Binder.clearCallingIdentity();
3462 try {
3463 synchronized (mGlobalLock) {
3464 ActivityRecord caller = ActivityRecord.forTokenLocked(token);
Andrii Kulian5f750bc2018-07-17 08:57:23 -07003465 ActivityRecord top = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003466 if (top != caller) {
3467 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3468 + " is not current top " + top);
3469 return false;
3470 }
3471 if (!top.nowVisible) {
3472 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
3473 + " is not visible");
3474 return false;
3475 }
3476 }
3477 return mAssistUtils.showSessionForActiveService(args, SHOW_SOURCE_APPLICATION, null,
3478 token);
3479 } finally {
3480 Binder.restoreCallingIdentity(ident);
3481 }
3482 }
3483
3484 @Override
3485 public boolean isRootVoiceInteraction(IBinder token) {
3486 synchronized (mGlobalLock) {
3487 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3488 if (r == null) {
3489 return false;
3490 }
3491 return r.rootVoiceInteraction;
3492 }
3493 }
3494
Wale Ogunwalef6733932018-06-27 05:14:34 -07003495 private void onLocalVoiceInteractionStartedLocked(IBinder activity,
3496 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
3497 ActivityRecord activityToCallback = ActivityRecord.forTokenLocked(activity);
3498 if (activityToCallback == null) return;
3499 activityToCallback.setVoiceSessionLocked(voiceSession);
3500
3501 // Inform the activity
3502 try {
3503 activityToCallback.app.getThread().scheduleLocalVoiceInteractionStarted(activity,
3504 voiceInteractor);
3505 long token = Binder.clearCallingIdentity();
3506 try {
3507 startRunningVoiceLocked(voiceSession, activityToCallback.appInfo.uid);
3508 } finally {
3509 Binder.restoreCallingIdentity(token);
3510 }
3511 // TODO: VI Should we cache the activity so that it's easier to find later
3512 // rather than scan through all the stacks and activities?
3513 } catch (RemoteException re) {
3514 activityToCallback.clearVoiceSessionLocked();
3515 // TODO: VI Should this terminate the voice session?
3516 }
3517 }
3518
3519 private void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) {
3520 Slog.d(TAG, "<<< startRunningVoiceLocked()");
3521 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid));
3522 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) {
3523 boolean wasRunningVoice = mRunningVoice != null;
3524 mRunningVoice = session;
3525 if (!wasRunningVoice) {
3526 mVoiceWakeLock.acquire();
3527 updateSleepIfNeededLocked();
3528 }
3529 }
3530 }
3531
3532 void finishRunningVoiceLocked() {
3533 if (mRunningVoice != null) {
3534 mRunningVoice = null;
3535 mVoiceWakeLock.release();
3536 updateSleepIfNeededLocked();
3537 }
3538 }
3539
3540 @Override
3541 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) {
3542 synchronized (mGlobalLock) {
3543 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) {
3544 if (keepAwake) {
3545 mVoiceWakeLock.acquire();
3546 } else {
3547 mVoiceWakeLock.release();
3548 }
3549 }
3550 }
3551 }
3552
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003553 @Override
3554 public ComponentName getActivityClassForToken(IBinder token) {
3555 synchronized (mGlobalLock) {
3556 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3557 if (r == null) {
3558 return null;
3559 }
3560 return r.intent.getComponent();
3561 }
3562 }
3563
3564 @Override
3565 public String getPackageForToken(IBinder token) {
3566 synchronized (mGlobalLock) {
3567 ActivityRecord r = ActivityRecord.isInStackLocked(token);
3568 if (r == null) {
3569 return null;
3570 }
3571 return r.packageName;
3572 }
3573 }
3574
3575 @Override
3576 public void showLockTaskEscapeMessage(IBinder token) {
3577 synchronized (mGlobalLock) {
3578 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3579 if (r == null) {
3580 return;
3581 }
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07003582 getLockTaskController().showLockTaskToast();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003583 }
3584 }
3585
3586 @Override
3587 public void keyguardGoingAway(int flags) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003588 enforceNotIsolatedCaller("keyguardGoingAway");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003589 final long token = Binder.clearCallingIdentity();
3590 try {
3591 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003592 mKeyguardController.keyguardGoingAway(flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003593 }
3594 } finally {
3595 Binder.restoreCallingIdentity(token);
3596 }
3597 }
3598
3599 /**
3600 * Try to place task to provided position. The final position might be different depending on
3601 * current user and stacks state. The task will be moved to target stack if it's currently in
3602 * different stack.
3603 */
3604 @Override
3605 public void positionTaskInStack(int taskId, int stackId, int position) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003606 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "positionTaskInStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003607 synchronized (mGlobalLock) {
3608 long ident = Binder.clearCallingIdentity();
3609 try {
3610 if (DEBUG_STACK) Slog.d(TAG_STACK, "positionTaskInStack: positioning task="
3611 + taskId + " in stackId=" + stackId + " at position=" + position);
Wale Ogunwaled32da472018-11-16 07:19:28 -08003612 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003613 if (task == null) {
3614 throw new IllegalArgumentException("positionTaskInStack: no task for id="
3615 + taskId);
3616 }
3617
Wale Ogunwaled32da472018-11-16 07:19:28 -08003618 final ActivityStack stack = mRootActivityContainer.getStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003619
3620 if (stack == null) {
3621 throw new IllegalArgumentException("positionTaskInStack: no stack for id="
3622 + stackId);
3623 }
3624 if (!stack.isActivityTypeStandardOrUndefined()) {
3625 throw new IllegalArgumentException("positionTaskInStack: Attempt to change"
3626 + " the position of task " + taskId + " in/to non-standard stack");
3627 }
3628
3629 // TODO: Have the callers of this API call a separate reparent method if that is
3630 // what they intended to do vs. having this method also do reparenting.
3631 if (task.getStack() == stack) {
3632 // Change position in current stack.
3633 stack.positionChildAt(task, position);
3634 } else {
3635 // Reparent to new stack.
3636 task.reparent(stack, position, REPARENT_LEAVE_STACK_IN_PLACE, !ANIMATE,
3637 !DEFER_RESUME, "positionTaskInStack");
3638 }
3639 } finally {
3640 Binder.restoreCallingIdentity(ident);
3641 }
3642 }
3643 }
3644
3645 @Override
3646 public void reportSizeConfigurations(IBinder token, int[] horizontalSizeConfiguration,
3647 int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
3648 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Report configuration: " + token + " "
3649 + horizontalSizeConfiguration + " " + verticalSizeConfigurations);
3650 synchronized (mGlobalLock) {
3651 ActivityRecord record = ActivityRecord.isInStackLocked(token);
3652 if (record == null) {
3653 throw new IllegalArgumentException("reportSizeConfigurations: ActivityRecord not "
3654 + "found for: " + token);
3655 }
3656 record.setSizeConfigurations(horizontalSizeConfiguration,
3657 verticalSizeConfigurations, smallestSizeConfigurations);
3658 }
3659 }
3660
3661 /**
3662 * Dismisses split-screen multi-window mode.
3663 * @param toTop If true the current primary split-screen stack will be placed or left on top.
3664 */
3665 @Override
3666 public void dismissSplitScreenMode(boolean toTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003667 enforceCallerIsRecentsOrHasPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003668 MANAGE_ACTIVITY_STACKS, "dismissSplitScreenMode()");
3669 final long ident = Binder.clearCallingIdentity();
3670 try {
3671 synchronized (mGlobalLock) {
3672 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003673 mRootActivityContainer.getDefaultDisplay().getSplitScreenPrimaryStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003674 if (stack == null) {
3675 Slog.w(TAG, "dismissSplitScreenMode: primary split-screen stack not found.");
3676 return;
3677 }
3678
3679 if (toTop) {
3680 // Caller wants the current split-screen primary stack to be the top stack after
3681 // it goes fullscreen, so move it to the front.
3682 stack.moveToFront("dismissSplitScreenMode");
Wale Ogunwaled32da472018-11-16 07:19:28 -08003683 } else if (mRootActivityContainer.isTopDisplayFocusedStack(stack)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003684 // In this case the current split-screen primary stack shouldn't be the top
3685 // stack after it goes fullscreen, but it current has focus, so we move the
3686 // focus to the top-most split-screen secondary stack next to it.
3687 final ActivityStack otherStack = stack.getDisplay().getTopStackInWindowingMode(
3688 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
3689 if (otherStack != null) {
3690 otherStack.moveToFront("dismissSplitScreenMode_other");
3691 }
3692 }
3693
Evan Rosky10475742018-09-05 19:02:48 -07003694 stack.setWindowingMode(WINDOWING_MODE_UNDEFINED);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003695 }
3696 } finally {
3697 Binder.restoreCallingIdentity(ident);
3698 }
3699 }
3700
3701 /**
3702 * Dismisses Pip
3703 * @param animate True if the dismissal should be animated.
3704 * @param animationDuration The duration of the resize animation in milliseconds or -1 if the
3705 * default animation duration should be used.
3706 */
3707 @Override
3708 public void dismissPip(boolean animate, int animationDuration) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003709 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "dismissPip()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003710 final long ident = Binder.clearCallingIdentity();
3711 try {
3712 synchronized (mGlobalLock) {
Yunfan Chen279f5582018-12-12 15:24:50 -08003713 final ActivityStack stack =
Wale Ogunwaled32da472018-11-16 07:19:28 -08003714 mRootActivityContainer.getDefaultDisplay().getPinnedStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003715 if (stack == null) {
3716 Slog.w(TAG, "dismissPip: pinned stack not found.");
3717 return;
3718 }
3719 if (stack.getWindowingMode() != WINDOWING_MODE_PINNED) {
3720 throw new IllegalArgumentException("Stack: " + stack
3721 + " doesn't support animated resize.");
3722 }
3723 if (animate) {
3724 stack.animateResizePinnedStack(null /* sourceHintBounds */,
3725 null /* destBounds */, animationDuration, false /* fromFullscreen */);
3726 } else {
3727 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, true /* onTop */);
3728 }
3729 }
3730 } finally {
3731 Binder.restoreCallingIdentity(ident);
3732 }
3733 }
3734
3735 @Override
3736 public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003737 mAmInternal.enforceCallingPermission(MANAGE_ACTIVITY_STACKS, "suppressResizeConfigChanges()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003738 synchronized (mGlobalLock) {
3739 mSuppressResizeConfigChanges = suppress;
3740 }
3741 }
3742
3743 /**
3744 * NOTE: For the pinned stack, this method is usually called after the bounds animation has
3745 * animated the stack to the fullscreen, but can also be called if we are relaunching an
3746 * activity and clearing the task at the same time.
3747 */
3748 @Override
3749 // TODO: API should just be about changing windowing modes...
3750 public void moveTasksToFullscreenStack(int fromStackId, boolean onTop) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003751 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003752 "moveTasksToFullscreenStack()");
3753 synchronized (mGlobalLock) {
3754 final long origId = Binder.clearCallingIdentity();
3755 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003756 final ActivityStack stack = mRootActivityContainer.getStack(fromStackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003757 if (stack != null){
3758 if (!stack.isActivityTypeStandardOrUndefined()) {
3759 throw new IllegalArgumentException(
3760 "You can't move tasks from non-standard stacks.");
3761 }
3762 mStackSupervisor.moveTasksToFullscreenStackLocked(stack, onTop);
3763 }
3764 } finally {
3765 Binder.restoreCallingIdentity(origId);
3766 }
3767 }
3768 }
3769
3770 /**
3771 * Moves the top activity in the input stackId to the pinned stack.
3772 *
3773 * @param stackId Id of stack to move the top activity to pinned stack.
3774 * @param bounds Bounds to use for pinned stack.
3775 *
3776 * @return True if the top activity of the input stack was successfully moved to the pinned
3777 * stack.
3778 */
3779 @Override
3780 public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003781 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003782 "moveTopActivityToPinnedStack()");
3783 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003784 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003785 throw new IllegalStateException("moveTopActivityToPinnedStack:"
3786 + "Device doesn't support picture-in-picture mode");
3787 }
3788
3789 long ident = Binder.clearCallingIdentity();
3790 try {
Wale Ogunwaled32da472018-11-16 07:19:28 -08003791 return mRootActivityContainer.moveTopStackActivityToPinnedStack(stackId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003792 } finally {
3793 Binder.restoreCallingIdentity(ident);
3794 }
3795 }
3796 }
3797
3798 @Override
3799 public boolean isInMultiWindowMode(IBinder token) {
3800 final long origId = Binder.clearCallingIdentity();
3801 try {
3802 synchronized (mGlobalLock) {
3803 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
3804 if (r == null) {
3805 return false;
3806 }
3807 // An activity is consider to be in multi-window mode if its task isn't fullscreen.
3808 return r.inMultiWindowMode();
3809 }
3810 } finally {
3811 Binder.restoreCallingIdentity(origId);
3812 }
3813 }
3814
3815 @Override
3816 public boolean isInPictureInPictureMode(IBinder token) {
3817 final long origId = Binder.clearCallingIdentity();
3818 try {
3819 synchronized (mGlobalLock) {
3820 return isInPictureInPictureMode(ActivityRecord.forTokenLocked(token));
3821 }
3822 } finally {
3823 Binder.restoreCallingIdentity(origId);
3824 }
3825 }
3826
3827 private boolean isInPictureInPictureMode(ActivityRecord r) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003828 if (r == null || r.getActivityStack() == null || !r.inPinnedWindowingMode()
3829 || r.getActivityStack().isInStackLocked(r) == null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003830 return false;
3831 }
3832
3833 // If we are animating to fullscreen then we have already dispatched the PIP mode
3834 // changed, so we should reflect that check here as well.
Yunfan Chen279f5582018-12-12 15:24:50 -08003835 final TaskStack taskStack = r.getActivityStack().getTaskStack();
3836 return !taskStack.isAnimatingBoundsToFullscreen();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003837 }
3838
3839 @Override
3840 public boolean enterPictureInPictureMode(IBinder token, final PictureInPictureParams params) {
3841 final long origId = Binder.clearCallingIdentity();
3842 try {
3843 synchronized (mGlobalLock) {
3844 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3845 "enterPictureInPictureMode", token, params);
3846
3847 // If the activity is already in picture in picture mode, then just return early
3848 if (isInPictureInPictureMode(r)) {
3849 return true;
3850 }
3851
3852 // Activity supports picture-in-picture, now check that we can enter PiP at this
3853 // point, if it is
3854 if (!r.checkEnterPictureInPictureState("enterPictureInPictureMode",
3855 false /* beforeStopping */)) {
3856 return false;
3857 }
3858
3859 final Runnable enterPipRunnable = () -> {
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003860 synchronized (mGlobalLock) {
3861 // Only update the saved args from the args that are set
3862 r.pictureInPictureArgs.copyOnlySet(params);
3863 final float aspectRatio = r.pictureInPictureArgs.getAspectRatio();
3864 final List<RemoteAction> actions = r.pictureInPictureArgs.getActions();
3865 // Adjust the source bounds by the insets for the transition down
3866 final Rect sourceBounds = new Rect(
3867 r.pictureInPictureArgs.getSourceRectHint());
Wale Ogunwaled32da472018-11-16 07:19:28 -08003868 mRootActivityContainer.moveActivityToPinnedStack(
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003869 r, sourceBounds, aspectRatio, "enterPictureInPictureMode");
Yunfan Chen279f5582018-12-12 15:24:50 -08003870 final ActivityStack stack = r.getActivityStack();
Wale Ogunwalef276a6f2018-06-15 08:26:07 -07003871 stack.setPictureInPictureAspectRatio(aspectRatio);
3872 stack.setPictureInPictureActions(actions);
3873 MetricsLoggerWrapper.logPictureInPictureEnter(mContext, r.appInfo.uid,
3874 r.shortComponentName, r.supportsEnterPipOnTaskSwitch);
3875 logPictureInPictureArgs(params);
3876 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003877 };
3878
Wale Ogunwaled0412b32018-05-08 09:25:50 -07003879 if (isKeyguardLocked()) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003880 // If the keyguard is showing or occluded, then try and dismiss it before
3881 // entering picture-in-picture (this will prompt the user to authenticate if the
3882 // device is currently locked).
3883 dismissKeyguard(token, new KeyguardDismissCallback() {
3884 @Override
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003885 public void onDismissSucceeded() {
3886 mH.post(enterPipRunnable);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003887 }
3888 }, null /* message */);
3889 } else {
3890 // Enter picture in picture immediately otherwise
3891 enterPipRunnable.run();
3892 }
3893 return true;
3894 }
3895 } finally {
3896 Binder.restoreCallingIdentity(origId);
3897 }
3898 }
3899
3900 @Override
3901 public void setPictureInPictureParams(IBinder token, final PictureInPictureParams params) {
3902 final long origId = Binder.clearCallingIdentity();
3903 try {
3904 synchronized (mGlobalLock) {
3905 final ActivityRecord r = ensureValidPictureInPictureActivityParamsLocked(
3906 "setPictureInPictureParams", token, params);
3907
3908 // Only update the saved args from the args that are set
3909 r.pictureInPictureArgs.copyOnlySet(params);
3910 if (r.inPinnedWindowingMode()) {
3911 // If the activity is already in picture-in-picture, update the pinned stack now
3912 // if it is not already expanding to fullscreen. Otherwise, the arguments will
3913 // be used the next time the activity enters PiP
Yunfan Chen279f5582018-12-12 15:24:50 -08003914 final ActivityStack stack = r.getActivityStack();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003915 if (!stack.isAnimatingBoundsToFullscreen()) {
3916 stack.setPictureInPictureAspectRatio(
3917 r.pictureInPictureArgs.getAspectRatio());
3918 stack.setPictureInPictureActions(r.pictureInPictureArgs.getActions());
3919 }
3920 }
3921 logPictureInPictureArgs(params);
3922 }
3923 } finally {
3924 Binder.restoreCallingIdentity(origId);
3925 }
3926 }
3927
3928 @Override
3929 public int getMaxNumPictureInPictureActions(IBinder token) {
3930 // Currently, this is a static constant, but later, we may change this to be dependent on
3931 // the context of the activity
3932 return 3;
3933 }
3934
3935 private void logPictureInPictureArgs(PictureInPictureParams params) {
3936 if (params.hasSetActions()) {
3937 MetricsLogger.histogram(mContext, "tron_varz_picture_in_picture_actions_count",
3938 params.getActions().size());
3939 }
3940 if (params.hasSetAspectRatio()) {
3941 LogMaker lm = new LogMaker(MetricsEvent.ACTION_PICTURE_IN_PICTURE_ASPECT_RATIO_CHANGED);
3942 lm.addTaggedData(MetricsEvent.PICTURE_IN_PICTURE_ASPECT_RATIO, params.getAspectRatio());
3943 MetricsLogger.action(lm);
3944 }
3945 }
3946
3947 /**
3948 * Checks the state of the system and the activity associated with the given {@param token} to
3949 * verify that picture-in-picture is supported for that activity.
3950 *
3951 * @return the activity record for the given {@param token} if all the checks pass.
3952 */
3953 private ActivityRecord ensureValidPictureInPictureActivityParamsLocked(String caller,
3954 IBinder token, PictureInPictureParams params) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003955 if (!mSupportsPictureInPicture) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003956 throw new IllegalStateException(caller
3957 + ": Device doesn't support picture-in-picture mode.");
3958 }
3959
3960 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
3961 if (r == null) {
3962 throw new IllegalStateException(caller
3963 + ": Can't find activity for token=" + token);
3964 }
3965
3966 if (!r.supportsPictureInPicture()) {
3967 throw new IllegalStateException(caller
3968 + ": Current activity does not support picture-in-picture.");
3969 }
3970
3971 if (params.hasSetAspectRatio()
Wale Ogunwale8b19de92018-11-29 19:58:26 -08003972 && !mWindowManager.isValidPictureInPictureAspectRatio(
3973 r.getActivityStack().mDisplayId, params.getAspectRatio())) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003974 final float minAspectRatio = mContext.getResources().getFloat(
3975 com.android.internal.R.dimen.config_pictureInPictureMinAspectRatio);
3976 final float maxAspectRatio = mContext.getResources().getFloat(
3977 com.android.internal.R.dimen.config_pictureInPictureMaxAspectRatio);
3978 throw new IllegalArgumentException(String.format(caller
3979 + ": Aspect ratio is too extreme (must be between %f and %f).",
3980 minAspectRatio, maxAspectRatio));
3981 }
3982
3983 // Truncate the number of actions if necessary
3984 params.truncateActions(getMaxNumPictureInPictureActions(token));
3985
3986 return r;
3987 }
3988
3989 @Override
3990 public IBinder getUriPermissionOwnerForActivity(IBinder activityToken) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07003991 enforceNotIsolatedCaller("getUriPermissionOwnerForActivity");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003992 synchronized (mGlobalLock) {
3993 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
3994 if (r == null) {
3995 throw new IllegalArgumentException("Activity does not exist; token="
3996 + activityToken);
3997 }
Wale Ogunwale6d50dcc2018-07-21 23:00:40 -07003998 return r.getUriPermissionsLocked().getExternalToken();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003999 }
4000 }
4001
4002 @Override
4003 public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
4004 Rect tempDockedTaskInsetBounds,
4005 Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004006 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizeDockedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004007 long ident = Binder.clearCallingIdentity();
4008 try {
4009 synchronized (mGlobalLock) {
4010 mStackSupervisor.resizeDockedStackLocked(dockedBounds, tempDockedTaskBounds,
4011 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds,
4012 PRESERVE_WINDOWS);
4013 }
4014 } finally {
4015 Binder.restoreCallingIdentity(ident);
4016 }
4017 }
4018
4019 @Override
4020 public void setSplitScreenResizing(boolean resizing) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004021 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "setSplitScreenResizing()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004022 final long ident = Binder.clearCallingIdentity();
4023 try {
4024 synchronized (mGlobalLock) {
4025 mStackSupervisor.setSplitScreenResizing(resizing);
4026 }
4027 } finally {
4028 Binder.restoreCallingIdentity(ident);
4029 }
4030 }
4031
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004032 /**
4033 * Check that we have the features required for VR-related API calls, and throw an exception if
4034 * not.
4035 */
Wale Ogunwale59507092018-10-29 09:00:30 -07004036 public void enforceSystemHasVrFeature() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004037 if (!mContext.getPackageManager().hasSystemFeature(
4038 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
4039 throw new UnsupportedOperationException("VR mode not supported on this device!");
4040 }
4041 }
4042
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004043 @Override
4044 public int setVrMode(IBinder token, boolean enabled, ComponentName packageName) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004045 enforceSystemHasVrFeature();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004046
4047 final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
4048
4049 ActivityRecord r;
4050 synchronized (mGlobalLock) {
4051 r = ActivityRecord.isInStackLocked(token);
4052 }
4053
4054 if (r == null) {
4055 throw new IllegalArgumentException();
4056 }
4057
4058 int err;
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004059 if ((err = vrService.hasVrPackage(packageName, r.mUserId)) !=
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004060 VrManagerInternal.NO_ERROR) {
4061 return err;
4062 }
4063
4064 // Clear the binder calling uid since this path may call moveToTask().
4065 final long callingId = Binder.clearCallingIdentity();
4066 try {
4067 synchronized (mGlobalLock) {
4068 r.requestedVrComponent = (enabled) ? packageName : null;
4069
4070 // Update associated state if this activity is currently focused
Andrii Kulian52d255c2018-07-13 11:32:19 -07004071 if (r.isResumedActivityOnDisplay()) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004072 applyUpdateVrModeLocked(r);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004073 }
4074 return 0;
4075 }
4076 } finally {
4077 Binder.restoreCallingIdentity(callingId);
4078 }
4079 }
4080
4081 @Override
4082 public void startLocalVoiceInteraction(IBinder callingActivity, Bundle options) {
4083 Slog.i(TAG, "Activity tried to startLocalVoiceInteraction");
4084 synchronized (mGlobalLock) {
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004085 ActivityRecord activity = getTopDisplayFocusedStack().getTopActivity();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004086 if (ActivityRecord.forTokenLocked(callingActivity) != activity) {
4087 throw new SecurityException("Only focused activity can call startVoiceInteraction");
4088 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004089 if (mRunningVoice != null || activity.getTaskRecord().voiceSession != null
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004090 || activity.voiceSession != null) {
4091 Slog.w(TAG, "Already in a voice interaction, cannot start new voice interaction");
4092 return;
4093 }
4094 if (activity.pendingVoiceInteractionStart) {
4095 Slog.w(TAG, "Pending start of voice interaction already.");
4096 return;
4097 }
4098 activity.pendingVoiceInteractionStart = true;
4099 }
4100 LocalServices.getService(VoiceInteractionManagerInternal.class)
4101 .startLocalVoiceInteraction(callingActivity, options);
4102 }
4103
4104 @Override
4105 public void stopLocalVoiceInteraction(IBinder callingActivity) {
4106 LocalServices.getService(VoiceInteractionManagerInternal.class)
4107 .stopLocalVoiceInteraction(callingActivity);
4108 }
4109
4110 @Override
4111 public boolean supportsLocalVoiceInteraction() {
4112 return LocalServices.getService(VoiceInteractionManagerInternal.class)
4113 .supportsLocalVoiceInteraction();
4114 }
4115
4116 /** Notifies all listeners when the pinned stack animation starts. */
4117 @Override
4118 public void notifyPinnedStackAnimationStarted() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004119 mTaskChangeNotificationController.notifyPinnedStackAnimationStarted();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004120 }
4121
4122 /** Notifies all listeners when the pinned stack animation ends. */
4123 @Override
4124 public void notifyPinnedStackAnimationEnded() {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004125 mTaskChangeNotificationController.notifyPinnedStackAnimationEnded();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004126 }
4127
4128 @Override
4129 public void resizePinnedStack(Rect pinnedBounds, Rect tempPinnedTaskBounds) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004130 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS, "resizePinnedStack()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004131 final long ident = Binder.clearCallingIdentity();
4132 try {
4133 synchronized (mGlobalLock) {
4134 mStackSupervisor.resizePinnedStackLocked(pinnedBounds, tempPinnedTaskBounds);
4135 }
4136 } finally {
4137 Binder.restoreCallingIdentity(ident);
4138 }
4139 }
4140
4141 @Override
4142 public boolean updateDisplayOverrideConfiguration(Configuration values, int displayId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004143 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateDisplayOverrideConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004144
4145 synchronized (mGlobalLock) {
4146 // Check if display is initialized in AM.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004147 if (!mRootActivityContainer.isDisplayAdded(displayId)) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004148 // Call might come when display is not yet added or has already been removed.
4149 if (DEBUG_CONFIGURATION) {
4150 Slog.w(TAG, "Trying to update display configuration for non-existing displayId="
4151 + displayId);
4152 }
4153 return false;
4154 }
4155
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004156 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004157 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004158 values = mWindowManager.computeNewConfiguration(displayId);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004159 }
4160
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004161 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004162 final Message msg = PooledLambda.obtainMessage(
4163 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal, displayId);
4164 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004165 }
4166
4167 final long origId = Binder.clearCallingIdentity();
4168 try {
4169 if (values != null) {
4170 Settings.System.clearConfiguration(values);
4171 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004172 updateDisplayOverrideConfigurationLocked(values, null /* starting */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004173 false /* deferResume */, displayId, mTmpUpdateConfigurationResult);
4174 return mTmpUpdateConfigurationResult.changes != 0;
4175 } finally {
4176 Binder.restoreCallingIdentity(origId);
4177 }
4178 }
4179 }
4180
4181 @Override
4182 public boolean updateConfiguration(Configuration values) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004183 mAmInternal.enforceCallingPermission(CHANGE_CONFIGURATION, "updateConfiguration()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004184
4185 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004186 if (values == null && mWindowManager != null) {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004187 // sentinel: fetch the current configuration from the window manager
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004188 values = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004189 }
4190
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004191 if (mWindowManager != null) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004192 final Message msg = PooledLambda.obtainMessage(
4193 ActivityManagerInternal::updateOomLevelsForDisplay, mAmInternal,
4194 DEFAULT_DISPLAY);
4195 mH.sendMessage(msg);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004196 }
4197
4198 final long origId = Binder.clearCallingIdentity();
4199 try {
4200 if (values != null) {
4201 Settings.System.clearConfiguration(values);
4202 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004203 updateConfigurationLocked(values, null, false, false /* persistent */,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004204 UserHandle.USER_NULL, false /* deferResume */,
4205 mTmpUpdateConfigurationResult);
4206 return mTmpUpdateConfigurationResult.changes != 0;
4207 } finally {
4208 Binder.restoreCallingIdentity(origId);
4209 }
4210 }
4211 }
4212
4213 @Override
4214 public void dismissKeyguard(IBinder token, IKeyguardDismissCallback callback,
4215 CharSequence message) {
4216 if (message != null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004217 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004218 Manifest.permission.SHOW_KEYGUARD_MESSAGE, "dismissKeyguard()");
4219 }
4220 final long callingId = Binder.clearCallingIdentity();
4221 try {
4222 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004223 mKeyguardController.dismissKeyguard(token, callback, message);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004224 }
4225 } finally {
4226 Binder.restoreCallingIdentity(callingId);
4227 }
4228 }
4229
4230 @Override
4231 public void cancelTaskWindowTransition(int taskId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004232 enforceCallerIsRecentsOrHasPermission(MANAGE_ACTIVITY_STACKS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004233 "cancelTaskWindowTransition()");
4234 final long ident = Binder.clearCallingIdentity();
4235 try {
4236 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004237 final TaskRecord task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004238 MATCH_TASK_IN_STACKS_ONLY);
4239 if (task == null) {
4240 Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found");
4241 return;
4242 }
4243 task.cancelWindowTransition();
4244 }
4245 } finally {
4246 Binder.restoreCallingIdentity(ident);
4247 }
4248 }
4249
4250 @Override
4251 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004252 enforceCallerIsRecentsOrHasPermission(READ_FRAME_BUFFER, "getTaskSnapshot()");
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004253 final long ident = Binder.clearCallingIdentity();
4254 try {
4255 final TaskRecord task;
4256 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004257 task = mRootActivityContainer.anyTaskForId(taskId,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004258 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS);
4259 if (task == null) {
4260 Slog.w(TAG, "getTaskSnapshot: taskId=" + taskId + " not found");
4261 return null;
4262 }
4263 }
4264 // Don't call this while holding the lock as this operation might hit the disk.
4265 return task.getSnapshot(reducedResolution);
4266 } finally {
4267 Binder.restoreCallingIdentity(ident);
4268 }
4269 }
4270
4271 @Override
4272 public void setDisablePreviewScreenshots(IBinder token, boolean disable) {
4273 synchronized (mGlobalLock) {
4274 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4275 if (r == null) {
4276 Slog.w(TAG, "setDisablePreviewScreenshots: Unable to find activity for token="
4277 + token);
4278 return;
4279 }
4280 final long origId = Binder.clearCallingIdentity();
4281 try {
4282 r.setDisablePreviewScreenshots(disable);
4283 } finally {
4284 Binder.restoreCallingIdentity(origId);
4285 }
4286 }
4287 }
4288
4289 /** Return the user id of the last resumed activity. */
4290 @Override
4291 public @UserIdInt
4292 int getLastResumedActivityUserId() {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004293 mAmInternal.enforceCallingPermission(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004294 Manifest.permission.INTERACT_ACROSS_USERS_FULL, "getLastResumedActivityUserId()");
4295 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004296 if (mLastResumedActivity == null) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004297 return getCurrentUserId();
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004298 }
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004299 return mLastResumedActivity.mUserId;
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004300 }
4301 }
4302
4303 @Override
4304 public void updateLockTaskFeatures(int userId, int flags) {
4305 final int callingUid = Binder.getCallingUid();
4306 if (callingUid != 0 && callingUid != SYSTEM_UID) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004307 mAmInternal.enforceCallingPermission(android.Manifest.permission.UPDATE_LOCK_TASK_PACKAGES,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004308 "updateLockTaskFeatures()");
4309 }
4310 synchronized (mGlobalLock) {
4311 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Allowing features " + userId + ":0x" +
4312 Integer.toHexString(flags));
Wale Ogunwaled95c06b2018-05-08 10:35:38 -07004313 getLockTaskController().updateLockTaskFeatures(userId, flags);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004314 }
4315 }
4316
4317 @Override
4318 public void setShowWhenLocked(IBinder token, boolean showWhenLocked) {
4319 synchronized (mGlobalLock) {
4320 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4321 if (r == null) {
4322 return;
4323 }
4324 final long origId = Binder.clearCallingIdentity();
4325 try {
4326 r.setShowWhenLocked(showWhenLocked);
4327 } finally {
4328 Binder.restoreCallingIdentity(origId);
4329 }
4330 }
4331 }
4332
4333 @Override
Issei Suzuki74e1eb22018-12-20 17:42:52 +01004334 public void setInheritShowWhenLocked(IBinder token, boolean inheritShowWhenLocked) {
4335 synchronized (mGlobalLock) {
4336 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4337 if (r == null) {
4338 return;
4339 }
4340 final long origId = Binder.clearCallingIdentity();
4341 try {
4342 r.setInheritShowWhenLocked(inheritShowWhenLocked);
4343 } finally {
4344 Binder.restoreCallingIdentity(origId);
4345 }
4346 }
4347 }
4348
4349 @Override
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004350 public void setTurnScreenOn(IBinder token, boolean turnScreenOn) {
4351 synchronized (mGlobalLock) {
4352 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4353 if (r == null) {
4354 return;
4355 }
4356 final long origId = Binder.clearCallingIdentity();
4357 try {
4358 r.setTurnScreenOn(turnScreenOn);
4359 } finally {
4360 Binder.restoreCallingIdentity(origId);
4361 }
4362 }
4363 }
4364
4365 @Override
4366 public void registerRemoteAnimations(IBinder token, RemoteAnimationDefinition definition) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004367 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004368 "registerRemoteAnimations");
4369 definition.setCallingPid(Binder.getCallingPid());
4370 synchronized (mGlobalLock) {
4371 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
4372 if (r == null) {
4373 return;
4374 }
4375 final long origId = Binder.clearCallingIdentity();
4376 try {
4377 r.registerRemoteAnimations(definition);
4378 } finally {
4379 Binder.restoreCallingIdentity(origId);
4380 }
4381 }
4382 }
4383
4384 @Override
4385 public void registerRemoteAnimationForNextActivityStart(String packageName,
4386 RemoteAnimationAdapter adapter) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004387 mAmInternal.enforceCallingPermission(CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS,
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004388 "registerRemoteAnimationForNextActivityStart");
4389 adapter.setCallingPid(Binder.getCallingPid());
4390 synchronized (mGlobalLock) {
4391 final long origId = Binder.clearCallingIdentity();
4392 try {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07004393 getActivityStartController().registerRemoteAnimationForNextActivityStart(
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004394 packageName, adapter);
4395 } finally {
4396 Binder.restoreCallingIdentity(origId);
4397 }
4398 }
4399 }
4400
4401 /** @see android.app.ActivityManager#alwaysShowUnsupportedCompileSdkWarning */
4402 @Override
4403 public void alwaysShowUnsupportedCompileSdkWarning(ComponentName activity) {
4404 synchronized (mGlobalLock) {
4405 final long origId = Binder.clearCallingIdentity();
4406 try {
Wale Ogunwale008163e2018-07-23 23:11:08 -07004407 mAppWarnings.alwaysShowUnsupportedCompileSdkWarning(activity);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004408 } finally {
4409 Binder.restoreCallingIdentity(origId);
4410 }
4411 }
4412 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07004413
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004414 @Override
4415 public void setVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004416 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004417 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004418 final int pid = Binder.getCallingPid();
4419 final WindowProcessController wpc = mPidMap.get(pid);
4420 mVrController.setVrThreadLocked(tid, pid, wpc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004421 }
4422 }
4423
4424 @Override
4425 public void setPersistentVrThread(int tid) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004426 if (checkCallingPermission(Manifest.permission.RESTRICTED_VR_ACCESS)
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004427 != PERMISSION_GRANTED) {
4428 final String msg = "Permission Denial: setPersistentVrThread() from pid="
4429 + Binder.getCallingPid()
4430 + ", uid=" + Binder.getCallingUid()
4431 + " requires " + Manifest.permission.RESTRICTED_VR_ACCESS;
4432 Slog.w(TAG, msg);
4433 throw new SecurityException(msg);
4434 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004435 enforceSystemHasVrFeature();
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004436 synchronized (mGlobalLock) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004437 final int pid = Binder.getCallingPid();
4438 final WindowProcessController proc = mPidMap.get(pid);
4439 mVrController.setPersistentVrThreadLocked(tid, pid, proc);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004440 }
4441 }
4442
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004443 @Override
4444 public void stopAppSwitches() {
4445 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "stopAppSwitches");
4446 synchronized (mGlobalLock) {
4447 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME;
4448 mDidAppSwitch = false;
4449 getActivityStartController().schedulePendingActivityLaunches(APP_SWITCH_DELAY_TIME);
4450 }
4451 }
4452
4453 @Override
4454 public void resumeAppSwitches() {
4455 enforceCallerIsRecentsOrHasPermission(STOP_APP_SWITCHES, "resumeAppSwitches");
4456 synchronized (mGlobalLock) {
4457 // Note that we don't execute any pending app switches... we will
4458 // let those wait until either the timeout, or the next start
4459 // activity request.
4460 mAppSwitchesAllowedTime = 0;
4461 }
4462 }
4463
4464 void onStartActivitySetDidAppSwitch() {
4465 if (mDidAppSwitch) {
4466 // This is the second allowed switch since we stopped switches, so now just generally
4467 // allow switches. Use case:
4468 // - user presses home (switches disabled, switch to home, mDidAppSwitch now true);
4469 // - user taps a home icon (coming from home so allowed, we hit here and now allow
4470 // anyone to switch again).
4471 mAppSwitchesAllowedTime = 0;
4472 } else {
4473 mDidAppSwitch = true;
4474 }
4475 }
4476
4477 /** @return whether the system should disable UI modes incompatible with VR mode. */
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004478 boolean shouldDisableNonVrUiLocked() {
4479 return mVrController.shouldDisableNonVrUiLocked();
4480 }
4481
Wale Ogunwale53783742018-09-16 10:21:51 -07004482 private void applyUpdateVrModeLocked(ActivityRecord r) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004483 // VR apps are expected to run in a main display. If an app is turning on VR for
4484 // itself, but lives in a dynamic stack, then make sure that it is moved to the main
4485 // fullscreen stack before enabling VR Mode.
4486 // TODO: The goal of this code is to keep the VR app on the main display. When the
4487 // stack implementation changes in the future, keep in mind that the use of the fullscreen
4488 // stack is a means to move the activity to the main display and a moveActivityToDisplay()
4489 // option would be a better choice here.
4490 if (r.requestedVrComponent != null && r.getDisplayId() != DEFAULT_DISPLAY) {
4491 Slog.i(TAG, "Moving " + r.shortComponentName + " from stack " + r.getStackId()
4492 + " to main stack for VR");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004493 final ActivityStack stack = mRootActivityContainer.getDefaultDisplay().getOrCreateStack(
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004494 WINDOWING_MODE_FULLSCREEN, r.getActivityType(), true /* toTop */);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004495 moveTaskToStack(r.getTaskRecord().taskId, stack.mStackId, true /* toTop */);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004496 }
4497 mH.post(() -> {
4498 if (!mVrController.onVrModeChanged(r)) {
4499 return;
4500 }
4501 synchronized (mGlobalLock) {
4502 final boolean disableNonVrUi = mVrController.shouldDisableNonVrUiLocked();
4503 mWindowManager.disableNonVrUi(disableNonVrUi);
4504 if (disableNonVrUi) {
4505 // If we are in a VR mode where Picture-in-Picture mode is unsupported,
4506 // then remove the pinned stack.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004507 mRootActivityContainer.removeStacksInWindowingModes(WINDOWING_MODE_PINNED);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004508 }
4509 }
4510 });
4511 }
4512
Wale Ogunwale53783742018-09-16 10:21:51 -07004513 @Override
4514 public int getPackageScreenCompatMode(String packageName) {
4515 enforceNotIsolatedCaller("getPackageScreenCompatMode");
4516 synchronized (mGlobalLock) {
4517 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
4518 }
4519 }
4520
4521 @Override
4522 public void setPackageScreenCompatMode(String packageName, int mode) {
4523 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4524 "setPackageScreenCompatMode");
4525 synchronized (mGlobalLock) {
4526 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
4527 }
4528 }
4529
4530 @Override
4531 public boolean getPackageAskScreenCompat(String packageName) {
4532 enforceNotIsolatedCaller("getPackageAskScreenCompat");
4533 synchronized (mGlobalLock) {
4534 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
4535 }
4536 }
4537
4538 @Override
4539 public void setPackageAskScreenCompat(String packageName, boolean ask) {
4540 mAmInternal.enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
4541 "setPackageAskScreenCompat");
4542 synchronized (mGlobalLock) {
4543 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
4544 }
4545 }
4546
Wale Ogunwale64258362018-10-16 15:13:37 -07004547 public static String relaunchReasonToString(int relaunchReason) {
4548 switch (relaunchReason) {
4549 case RELAUNCH_REASON_WINDOWING_MODE_RESIZE:
4550 return "window_resize";
4551 case RELAUNCH_REASON_FREE_RESIZE:
4552 return "free_resize";
4553 default:
4554 return null;
4555 }
4556 }
4557
Andrii Kulian5f750bc2018-07-17 08:57:23 -07004558 ActivityStack getTopDisplayFocusedStack() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004559 return mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004560 }
4561
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004562 /** Pokes the task persister. */
4563 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
4564 mRecentTasks.notifyTaskPersisterLocked(task, flush);
4565 }
4566
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004567 boolean isKeyguardLocked() {
4568 return mKeyguardController.isKeyguardLocked();
4569 }
4570
Garfield Tan01548632018-11-27 10:15:48 -08004571 /**
4572 * Clears launch params for the given package.
4573 * @param packageNames the names of the packages of which the launch params are to be cleared
4574 */
4575 @Override
4576 public void clearLaunchParamsForPackages(List<String> packageNames) {
4577 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4578 "clearLaunchParamsForPackages");
4579 synchronized (mGlobalLock) {
4580 for (int i = 0; i < packageNames.size(); ++i) {
4581 mStackSupervisor.mLaunchParamsPersister.removeRecordForPackage(packageNames.get(i));
4582 }
4583 }
4584 }
4585
Wale Ogunwale9e737db2018-12-17 15:42:37 -08004586 /**
4587 * Makes the display with the given id a single task instance display. I.e the display can only
4588 * contain one task.
4589 */
4590 @Override
4591 public void setDisplayToSingleTaskInstance(int displayId) {
4592 mAmInternal.enforceCallingPermission(Manifest.permission.MANAGE_ACTIVITY_STACKS,
4593 "setDisplayToSingleTaskInstance");
4594 final long origId = Binder.clearCallingIdentity();
4595 try {
4596 final ActivityDisplay display =
4597 mRootActivityContainer.getActivityDisplayOrCreate(displayId);
4598 if (display != null) {
4599 display.setDisplayToSingleTaskInstance();
4600 }
4601 } finally {
4602 Binder.restoreCallingIdentity(origId);
4603 }
4604 }
4605
Wale Ogunwale31913b52018-10-13 08:29:31 -07004606 void dumpLastANRLocked(PrintWriter pw) {
4607 pw.println("ACTIVITY MANAGER LAST ANR (dumpsys activity lastanr)");
4608 if (mLastANRState == null) {
4609 pw.println(" <no ANR has occurred since boot>");
4610 } else {
4611 pw.println(mLastANRState);
4612 }
4613 }
4614
4615 void dumpLastANRTracesLocked(PrintWriter pw) {
4616 pw.println("ACTIVITY MANAGER LAST ANR TRACES (dumpsys activity lastanr-traces)");
4617
4618 final File[] files = new File(ANR_TRACE_DIR).listFiles();
4619 if (ArrayUtils.isEmpty(files)) {
4620 pw.println(" <no ANR has occurred since boot>");
4621 return;
4622 }
4623 // Find the latest file.
4624 File latest = null;
4625 for (File f : files) {
4626 if ((latest == null) || (latest.lastModified() < f.lastModified())) {
4627 latest = f;
Wale Ogunwalef6733932018-06-27 05:14:34 -07004628 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07004629 }
4630 pw.print("File: ");
4631 pw.print(latest.getName());
4632 pw.println();
4633 try (BufferedReader in = new BufferedReader(new FileReader(latest))) {
4634 String line;
4635 while ((line = in.readLine()) != null) {
4636 pw.println(line);
4637 }
4638 } catch (IOException e) {
4639 pw.print("Unable to read: ");
4640 pw.print(e);
4641 pw.println();
4642 }
4643 }
4644
4645 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4646 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
4647 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage,
4648 "ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
4649 }
4650
4651 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
4652 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage, String header) {
4653 pw.println(header);
4654
Wale Ogunwaled32da472018-11-16 07:19:28 -08004655 boolean printedAnything = mRootActivityContainer.dumpActivities(fd, pw, dumpAll, dumpClient,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004656 dumpPackage);
4657 boolean needSep = printedAnything;
4658
4659 boolean printed = ActivityStackSupervisor.printThisActivity(pw,
Wale Ogunwaled32da472018-11-16 07:19:28 -08004660 mRootActivityContainer.getTopResumedActivity(), dumpPackage, needSep,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004661 " ResumedActivity: ");
4662 if (printed) {
4663 printedAnything = true;
4664 needSep = false;
4665 }
4666
4667 if (dumpPackage == null) {
4668 if (needSep) {
4669 pw.println();
4670 }
4671 printedAnything = true;
4672 mStackSupervisor.dump(pw, " ");
4673 }
4674
4675 if (!printedAnything) {
4676 pw.println(" (nothing)");
4677 }
4678 }
4679
4680 void dumpActivityContainersLocked(PrintWriter pw) {
4681 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity containers)");
Wale Ogunwaled32da472018-11-16 07:19:28 -08004682 mRootActivityContainer.dumpChildrenNames(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07004683 pw.println(" ");
4684 }
4685
4686 void dumpActivityStarterLocked(PrintWriter pw, String dumpPackage) {
4687 pw.println("ACTIVITY MANAGER STARTER (dumpsys activity starter)");
4688 getActivityStartController().dump(pw, "", dumpPackage);
4689 }
4690
4691 /**
4692 * There are three things that cmd can be:
4693 * - a flattened component name that matches an existing activity
4694 * - the cmd arg isn't the flattened component name of an existing activity:
4695 * dump all activity whose component contains the cmd as a substring
4696 * - A hex number of the ActivityRecord object instance.
4697 *
4698 * @param dumpVisibleStacksOnly dump activity with {@param name} only if in a visible stack
4699 * @param dumpFocusedStackOnly dump activity with {@param name} only if in the focused stack
4700 */
4701 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
4702 int opti, boolean dumpAll, boolean dumpVisibleStacksOnly, boolean dumpFocusedStackOnly) {
4703 ArrayList<ActivityRecord> activities;
4704
4705 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004706 activities = mRootActivityContainer.getDumpActivities(name, dumpVisibleStacksOnly,
Wale Ogunwale31913b52018-10-13 08:29:31 -07004707 dumpFocusedStackOnly);
4708 }
4709
4710 if (activities.size() <= 0) {
4711 return false;
4712 }
4713
4714 String[] newArgs = new String[args.length - opti];
4715 System.arraycopy(args, opti, newArgs, 0, args.length - opti);
4716
4717 TaskRecord lastTask = null;
4718 boolean needSep = false;
4719 for (int i = activities.size() - 1; i >= 0; i--) {
4720 ActivityRecord r = activities.get(i);
4721 if (needSep) {
4722 pw.println();
4723 }
4724 needSep = true;
4725 synchronized (mGlobalLock) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08004726 final TaskRecord task = r.getTaskRecord();
Wale Ogunwale31913b52018-10-13 08:29:31 -07004727 if (lastTask != task) {
4728 lastTask = task;
4729 pw.print("TASK "); pw.print(lastTask.affinity);
4730 pw.print(" id="); pw.print(lastTask.taskId);
4731 pw.print(" userId="); pw.println(lastTask.userId);
4732 if (dumpAll) {
4733 lastTask.dump(pw, " ");
4734 }
4735 }
4736 }
4737 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
4738 }
4739 return true;
4740 }
4741
4742 /**
4743 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
4744 * there is a thread associated with the activity.
4745 */
4746 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
4747 final ActivityRecord r, String[] args, boolean dumpAll) {
4748 String innerPrefix = prefix + " ";
4749 synchronized (mGlobalLock) {
4750 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
4751 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
4752 pw.print(" pid=");
4753 if (r.hasProcess()) pw.println(r.app.getPid());
4754 else pw.println("(not running)");
4755 if (dumpAll) {
4756 r.dump(pw, innerPrefix);
4757 }
4758 }
4759 if (r.attachedToProcess()) {
4760 // flush anything that is already in the PrintWriter since the thread is going
4761 // to write to the file descriptor directly
4762 pw.flush();
4763 try {
4764 TransferPipe tp = new TransferPipe();
4765 try {
4766 r.app.getThread().dumpActivity(tp.getWriteFd(),
4767 r.appToken, innerPrefix, args);
4768 tp.go(fd);
4769 } finally {
4770 tp.kill();
4771 }
4772 } catch (IOException e) {
4773 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
4774 } catch (RemoteException e) {
4775 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
4776 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004777 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004778 }
4779
sanryhuang498e77e2018-12-06 14:57:01 +08004780 private void writeSleepStateToProto(ProtoOutputStream proto, int wakeFullness,
4781 boolean testPssMode) {
4782 final long sleepToken = proto.start(ActivityManagerServiceDumpProcessesProto.SLEEP_STATUS);
4783 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.WAKEFULNESS,
4784 PowerManagerInternal.wakefulnessToProtoEnum(wakeFullness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08004785 for (ActivityTaskManagerInternal.SleepToken st : mRootActivityContainer.mSleepTokens) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07004786 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEP_TOKENS,
4787 st.toString());
4788 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07004789 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SLEEPING, mSleeping);
4790 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.SHUTTING_DOWN,
4791 mShuttingDown);
sanryhuang498e77e2018-12-06 14:57:01 +08004792 proto.write(ActivityManagerServiceDumpProcessesProto.SleepStatus.TEST_PSS_MODE,
4793 testPssMode);
4794 proto.end(sleepToken);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07004795 }
4796
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004797 int getCurrentUserId() {
4798 return mAmInternal.getCurrentUserId();
4799 }
4800
4801 private void enforceNotIsolatedCaller(String caller) {
4802 if (UserHandle.isIsolated(Binder.getCallingUid())) {
4803 throw new SecurityException("Isolated process not allowed to call " + caller);
4804 }
4805 }
4806
Wale Ogunwalef6733932018-06-27 05:14:34 -07004807 public Configuration getConfiguration() {
4808 Configuration ci;
4809 synchronized(mGlobalLock) {
Yunfan Chen75157d72018-07-27 14:47:21 +09004810 ci = new Configuration(getGlobalConfigurationForCallingPid());
Wale Ogunwalef6733932018-06-27 05:14:34 -07004811 ci.userSetLocale = false;
4812 }
4813 return ci;
4814 }
4815
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004816 /**
4817 * Current global configuration information. Contains general settings for the entire system,
4818 * also corresponds to the merged configuration of the default display.
4819 */
4820 Configuration getGlobalConfiguration() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08004821 return mRootActivityContainer.getConfiguration();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004822 }
4823
4824 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4825 boolean initLocale) {
4826 return updateConfigurationLocked(values, starting, initLocale, false /* deferResume */);
4827 }
4828
4829 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4830 boolean initLocale, boolean deferResume) {
4831 // pass UserHandle.USER_NULL as userId because we don't persist configuration for any user
4832 return updateConfigurationLocked(values, starting, initLocale, false /* persistent */,
4833 UserHandle.USER_NULL, deferResume);
4834 }
4835
Wale Ogunwale59507092018-10-29 09:00:30 -07004836 public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004837 final long origId = Binder.clearCallingIdentity();
4838 try {
4839 synchronized (mGlobalLock) {
4840 updateConfigurationLocked(values, null, false, true, userId,
4841 false /* deferResume */);
4842 }
4843 } finally {
4844 Binder.restoreCallingIdentity(origId);
4845 }
4846 }
4847
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004848 private boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4849 boolean initLocale, boolean persistent, int userId, boolean deferResume) {
4850 return updateConfigurationLocked(values, starting, initLocale, persistent, userId,
4851 deferResume, null /* result */);
4852 }
4853
4854 /**
4855 * Do either or both things: (1) change the current configuration, and (2)
4856 * make sure the given activity is running with the (now) current
4857 * configuration. Returns true if the activity has been left running, or
4858 * false if <var>starting</var> is being destroyed to match the new
4859 * configuration.
4860 *
4861 * @param userId is only used when persistent parameter is set to true to persist configuration
4862 * for that particular user
4863 */
4864 boolean updateConfigurationLocked(Configuration values, ActivityRecord starting,
4865 boolean initLocale, boolean persistent, int userId, boolean deferResume,
4866 ActivityTaskManagerService.UpdateConfigurationResult result) {
4867 int changes = 0;
4868 boolean kept = true;
4869
4870 if (mWindowManager != null) {
4871 mWindowManager.deferSurfaceLayout();
4872 }
4873 try {
4874 if (values != null) {
4875 changes = updateGlobalConfigurationLocked(values, initLocale, persistent, userId,
4876 deferResume);
4877 }
4878
4879 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
4880 } finally {
4881 if (mWindowManager != null) {
4882 mWindowManager.continueSurfaceLayout();
4883 }
4884 }
4885
4886 if (result != null) {
4887 result.changes = changes;
4888 result.activityRelaunched = !kept;
4889 }
4890 return kept;
4891 }
4892
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004893 /** Update default (global) configuration and notify listeners about changes. */
4894 private int updateGlobalConfigurationLocked(@NonNull Configuration values, boolean initLocale,
4895 boolean persistent, int userId, boolean deferResume) {
4896 mTempConfig.setTo(getGlobalConfiguration());
4897 final int changes = mTempConfig.updateFrom(values);
4898 if (changes == 0) {
4899 // Since calling to Activity.setRequestedOrientation leads to freezing the window with
4900 // setting WindowManagerService.mWaitingForConfig to true, it is important that we call
4901 // performDisplayOverrideConfigUpdate in order to send the new display configuration
4902 // (even if there are no actual changes) to unfreeze the window.
4903 performDisplayOverrideConfigUpdate(values, deferResume, DEFAULT_DISPLAY);
4904 return 0;
4905 }
4906
4907 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION,
4908 "Updating global configuration to: " + values);
4909
4910 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
4911 StatsLog.write(StatsLog.RESOURCE_CONFIGURATION_CHANGED,
4912 values.colorMode,
4913 values.densityDpi,
4914 values.fontScale,
4915 values.hardKeyboardHidden,
4916 values.keyboard,
4917 values.keyboardHidden,
4918 values.mcc,
4919 values.mnc,
4920 values.navigation,
4921 values.navigationHidden,
4922 values.orientation,
4923 values.screenHeightDp,
4924 values.screenLayout,
4925 values.screenWidthDp,
4926 values.smallestScreenWidthDp,
4927 values.touchscreen,
4928 values.uiMode);
4929
4930
4931 if (!initLocale && !values.getLocales().isEmpty() && values.userSetLocale) {
4932 final LocaleList locales = values.getLocales();
4933 int bestLocaleIndex = 0;
4934 if (locales.size() > 1) {
4935 if (mSupportedSystemLocales == null) {
4936 mSupportedSystemLocales = Resources.getSystem().getAssets().getLocales();
4937 }
4938 bestLocaleIndex = Math.max(0, locales.getFirstMatchIndex(mSupportedSystemLocales));
4939 }
4940 SystemProperties.set("persist.sys.locale",
4941 locales.get(bestLocaleIndex).toLanguageTag());
4942 LocaleList.setDefault(locales, bestLocaleIndex);
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004943
4944 final Message m = PooledLambda.obtainMessage(
4945 ActivityTaskManagerService::sendLocaleToMountDaemonMsg, this,
4946 locales.get(bestLocaleIndex));
4947 mH.sendMessage(m);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004948 }
4949
Yunfan Chen75157d72018-07-27 14:47:21 +09004950 mTempConfig.seq = increaseConfigurationSeqLocked();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004951
4952 // Update stored global config and notify everyone about the change.
Wale Ogunwaled32da472018-11-16 07:19:28 -08004953 mRootActivityContainer.onConfigurationChanged(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004954
4955 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + mTempConfig);
4956 // TODO(multi-display): Update UsageEvents#Event to include displayId.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004957 mUsageStatsInternal.reportConfigurationChange(mTempConfig, mAmInternal.getCurrentUserId());
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004958
4959 // TODO: If our config changes, should we auto dismiss any currently showing dialogs?
Wale Ogunwalef6733932018-06-27 05:14:34 -07004960 updateShouldShowDialogsLocked(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004961
4962 AttributeCache ac = AttributeCache.instance();
4963 if (ac != null) {
4964 ac.updateConfiguration(mTempConfig);
4965 }
4966
4967 // Make sure all resources in our process are updated right now, so that anyone who is going
4968 // to retrieve resource values after we return will be sure to get the new ones. This is
4969 // especially important during boot, where the first config change needs to guarantee all
4970 // resources have that config before following boot code is executed.
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004971 mSystemThread.applyConfigurationToResources(mTempConfig);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004972
4973 // We need another copy of global config because we're scheduling some calls instead of
4974 // running them in place. We need to be sure that object we send will be handled unchanged.
4975 final Configuration configCopy = new Configuration(mTempConfig);
4976 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Wale Ogunwale342fbe92018-10-09 08:44:10 -07004977 final Message msg = PooledLambda.obtainMessage(
4978 ActivityTaskManagerService::sendPutConfigurationForUserMsg,
4979 this, userId, configCopy);
4980 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004981 }
4982
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004983 for (int i = mPidMap.size() - 1; i >= 0; i--) {
Yunfan Chen79b96062018-10-17 12:45:23 -07004984 final int pid = mPidMap.keyAt(i);
4985 final WindowProcessController app = mPidMap.get(pid);
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004986 if (DEBUG_CONFIGURATION) {
4987 Slog.v(TAG_CONFIGURATION, "Update process config of "
4988 + app.mName + " to new config " + configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004989 }
Yunfan Chen34fcc7a2018-10-11 16:26:09 -07004990 app.onConfigurationChanged(configCopy);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004991 }
4992
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07004993 final Message msg = PooledLambda.obtainMessage(
4994 ActivityManagerInternal::broadcastGlobalConfigurationChanged,
4995 mAmInternal, changes, initLocale);
4996 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07004997
4998 // Override configuration of the default display duplicates global config, so we need to
4999 // update it also. This will also notify WindowManager about changes.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005000 performDisplayOverrideConfigUpdate(mRootActivityContainer.getConfiguration(), deferResume,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005001 DEFAULT_DISPLAY);
5002
5003 return changes;
5004 }
5005
5006 boolean updateDisplayOverrideConfigurationLocked(Configuration values, ActivityRecord starting,
5007 boolean deferResume, int displayId) {
5008 return updateDisplayOverrideConfigurationLocked(values, starting, deferResume /* deferResume */,
5009 displayId, null /* result */);
5010 }
5011
5012 /**
5013 * Updates override configuration specific for the selected display. If no config is provided,
5014 * new one will be computed in WM based on current display info.
5015 */
5016 boolean updateDisplayOverrideConfigurationLocked(Configuration values,
5017 ActivityRecord starting, boolean deferResume, int displayId,
5018 ActivityTaskManagerService.UpdateConfigurationResult result) {
5019 int changes = 0;
5020 boolean kept = true;
5021
5022 if (mWindowManager != null) {
5023 mWindowManager.deferSurfaceLayout();
5024 }
5025 try {
5026 if (values != null) {
5027 if (displayId == DEFAULT_DISPLAY) {
5028 // Override configuration of the default display duplicates global config, so
5029 // we're calling global config update instead for default display. It will also
5030 // apply the correct override config.
5031 changes = updateGlobalConfigurationLocked(values, false /* initLocale */,
5032 false /* persistent */, UserHandle.USER_NULL /* userId */, deferResume);
5033 } else {
5034 changes = performDisplayOverrideConfigUpdate(values, deferResume, displayId);
5035 }
5036 }
5037
5038 kept = ensureConfigAndVisibilityAfterUpdate(starting, changes);
5039 } finally {
5040 if (mWindowManager != null) {
5041 mWindowManager.continueSurfaceLayout();
5042 }
5043 }
5044
5045 if (result != null) {
5046 result.changes = changes;
5047 result.activityRelaunched = !kept;
5048 }
5049 return kept;
5050 }
5051
5052 private int performDisplayOverrideConfigUpdate(Configuration values, boolean deferResume,
5053 int displayId) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005054 mTempConfig.setTo(mRootActivityContainer.getDisplayOverrideConfiguration(displayId));
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005055 final int changes = mTempConfig.updateFrom(values);
5056 if (changes != 0) {
5057 Slog.i(TAG, "Override config changes=" + Integer.toHexString(changes) + " "
5058 + mTempConfig + " for displayId=" + displayId);
Wale Ogunwaled32da472018-11-16 07:19:28 -08005059 mRootActivityContainer.setDisplayOverrideConfiguration(mTempConfig, displayId);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005060
5061 final boolean isDensityChange = (changes & ActivityInfo.CONFIG_DENSITY) != 0;
5062 if (isDensityChange && displayId == DEFAULT_DISPLAY) {
Wale Ogunwale008163e2018-07-23 23:11:08 -07005063 mAppWarnings.onDensityChanged();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005064
Wale Ogunwale5c918702018-10-18 11:06:33 -07005065 // Post message to start process to avoid possible deadlock of calling into AMS with
5066 // the ATMS lock held.
5067 final Message msg = PooledLambda.obtainMessage(
5068 ActivityManagerInternal::killAllBackgroundProcessesExcept, mAmInternal,
5069 N, ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
5070 mH.sendMessage(msg);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005071 }
5072 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005073 return changes;
5074 }
5075
Wale Ogunwalef6733932018-06-27 05:14:34 -07005076 private void updateEventDispatchingLocked(boolean booted) {
5077 mWindowManager.setEventDispatching(booted && !mShuttingDown);
5078 }
5079
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005080 private void sendPutConfigurationForUserMsg(int userId, Configuration config) {
5081 final ContentResolver resolver = mContext.getContentResolver();
5082 Settings.System.putConfigurationForUser(resolver, config, userId);
5083 }
5084
5085 private void sendLocaleToMountDaemonMsg(Locale l) {
5086 try {
5087 IBinder service = ServiceManager.getService("mount");
5088 IStorageManager storageManager = IStorageManager.Stub.asInterface(service);
5089 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI");
5090 storageManager.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag());
5091 } catch (RemoteException e) {
5092 Log.e(TAG, "Error storing locale for decryption UI", e);
5093 }
5094 }
5095
Alison Cichowlas3e340502018-08-07 17:15:01 -04005096 private void expireStartAsCallerTokenMsg(IBinder permissionToken) {
5097 mStartActivitySources.remove(permissionToken);
5098 mExpiredStartAsCallerTokens.add(permissionToken);
5099 }
5100
5101 private void forgetStartAsCallerTokenMsg(IBinder permissionToken) {
5102 mExpiredStartAsCallerTokens.remove(permissionToken);
5103 }
5104
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005105 boolean isActivityStartsLoggingEnabled() {
5106 return mAmInternal.isActivityStartsLoggingEnabled();
5107 }
5108
Michal Karpinski8596ded2018-11-14 14:43:48 +00005109 boolean isBackgroundActivityStartsEnabled() {
5110 return mAmInternal.isBackgroundActivityStartsEnabled();
5111 }
5112
Wale Ogunwalef6733932018-06-27 05:14:34 -07005113 void enableScreenAfterBoot(boolean booted) {
5114 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5115 SystemClock.uptimeMillis());
5116 mWindowManager.enableScreenAfterBoot();
5117
5118 synchronized (mGlobalLock) {
5119 updateEventDispatchingLocked(booted);
5120 }
5121 }
5122
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005123 static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
5124 if (r == null || !r.hasProcess()) {
5125 return KEY_DISPATCHING_TIMEOUT_MS;
5126 }
5127 return getInputDispatchingTimeoutLocked(r.app);
5128 }
5129
5130 private static long getInputDispatchingTimeoutLocked(WindowProcessController r) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07005131 return r != null ? r.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005132 }
5133
Wale Ogunwalef6733932018-06-27 05:14:34 -07005134 /**
5135 * Decide based on the configuration whether we should show the ANR,
5136 * crash, etc dialogs. The idea is that if there is no affordance to
5137 * press the on-screen buttons, or the user experience would be more
5138 * greatly impacted than the crash itself, we shouldn't show the dialog.
5139 *
5140 * A thought: SystemUI might also want to get told about this, the Power
5141 * dialog / global actions also might want different behaviors.
5142 */
5143 private void updateShouldShowDialogsLocked(Configuration config) {
5144 final boolean inputMethodExists = !(config.keyboard == Configuration.KEYBOARD_NOKEYS
5145 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
5146 && config.navigation == Configuration.NAVIGATION_NONAV);
5147 int modeType = config.uiMode & Configuration.UI_MODE_TYPE_MASK;
5148 final boolean uiModeSupportsDialogs = (modeType != Configuration.UI_MODE_TYPE_CAR
5149 && !(modeType == Configuration.UI_MODE_TYPE_WATCH && Build.IS_USER)
5150 && modeType != Configuration.UI_MODE_TYPE_TELEVISION
5151 && modeType != Configuration.UI_MODE_TYPE_VR_HEADSET);
5152 final boolean hideDialogsSet = Settings.Global.getInt(mContext.getContentResolver(),
5153 HIDE_ERROR_DIALOGS, 0) != 0;
5154 mShowDialogs = inputMethodExists && uiModeSupportsDialogs && !hideDialogsSet;
5155 }
5156
5157 private void updateFontScaleIfNeeded(@UserIdInt int userId) {
5158 final float scaleFactor = Settings.System.getFloatForUser(mContext.getContentResolver(),
5159 FONT_SCALE, 1.0f, userId);
5160
5161 synchronized (this) {
5162 if (getGlobalConfiguration().fontScale == scaleFactor) {
5163 return;
5164 }
5165
5166 final Configuration configuration
5167 = mWindowManager.computeNewConfiguration(DEFAULT_DISPLAY);
5168 configuration.fontScale = scaleFactor;
5169 updatePersistentConfiguration(configuration, userId);
5170 }
5171 }
5172
5173 // Actually is sleeping or shutting down or whatever else in the future
5174 // is an inactive state.
5175 boolean isSleepingOrShuttingDownLocked() {
5176 return isSleepingLocked() || mShuttingDown;
5177 }
5178
5179 boolean isSleepingLocked() {
5180 return mSleeping;
5181 }
5182
Riddle Hsu16567132018-08-16 21:37:47 +08005183 /** Update AMS states when an activity is resumed. */
Wale Ogunwalef6733932018-06-27 05:14:34 -07005184 void setResumedActivityUncheckLocked(ActivityRecord r, String reason) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005185 final TaskRecord task = r.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005186 if (task.isActivityTypeStandard()) {
5187 if (mCurAppTimeTracker != r.appTimeTracker) {
5188 // We are switching app tracking. Complete the current one.
5189 if (mCurAppTimeTracker != null) {
5190 mCurAppTimeTracker.stop();
5191 mH.obtainMessage(
5192 REPORT_TIME_TRACKER_MSG, mCurAppTimeTracker).sendToTarget();
Wale Ogunwaled32da472018-11-16 07:19:28 -08005193 mRootActivityContainer.clearOtherAppTimeTrackers(r.appTimeTracker);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005194 mCurAppTimeTracker = null;
5195 }
5196 if (r.appTimeTracker != null) {
5197 mCurAppTimeTracker = r.appTimeTracker;
5198 startTimeTrackingFocusedActivityLocked();
5199 }
5200 } else {
5201 startTimeTrackingFocusedActivityLocked();
5202 }
5203 } else {
5204 r.appTimeTracker = null;
5205 }
5206 // TODO: VI Maybe r.task.voiceInteractor || r.voiceInteractor != null
5207 // TODO: Probably not, because we don't want to resume voice on switching
5208 // back to this activity
5209 if (task.voiceInteractor != null) {
5210 startRunningVoiceLocked(task.voiceSession, r.info.applicationInfo.uid);
5211 } else {
5212 finishRunningVoiceLocked();
5213
5214 if (mLastResumedActivity != null) {
5215 final IVoiceInteractionSession session;
5216
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005217 final TaskRecord lastResumedActivityTask = mLastResumedActivity.getTaskRecord();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005218 if (lastResumedActivityTask != null
5219 && lastResumedActivityTask.voiceSession != null) {
5220 session = lastResumedActivityTask.voiceSession;
5221 } else {
5222 session = mLastResumedActivity.voiceSession;
5223 }
5224
5225 if (session != null) {
5226 // We had been in a voice interaction session, but now focused has
5227 // move to something different. Just finish the session, we can't
5228 // return to it and retain the proper state and synchronization with
5229 // the voice interaction service.
5230 finishVoiceTask(session);
5231 }
5232 }
5233 }
5234
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005235 if (mLastResumedActivity != null && r.mUserId != mLastResumedActivity.mUserId) {
5236 mAmInternal.sendForegroundProfileChanged(r.mUserId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005237 }
5238 updateResumedAppTrace(r);
5239 mLastResumedActivity = r;
5240
Tiger Huang1e5b10a2018-07-30 20:19:51 +08005241 r.getDisplay().setFocusedApp(r, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005242
5243 applyUpdateLockStateLocked(r);
5244 applyUpdateVrModeLocked(r);
5245
5246 EventLogTags.writeAmSetResumedActivity(
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005247 r == null ? -1 : r.mUserId,
Wale Ogunwalef6733932018-06-27 05:14:34 -07005248 r == null ? "NULL" : r.shortComponentName,
5249 reason);
5250 }
5251
5252 ActivityTaskManagerInternal.SleepToken acquireSleepToken(String tag, int displayId) {
5253 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005254 final ActivityTaskManagerInternal.SleepToken token =
5255 mRootActivityContainer.createSleepToken(tag, displayId);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005256 updateSleepIfNeededLocked();
5257 return token;
5258 }
5259 }
5260
5261 void updateSleepIfNeededLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005262 final boolean shouldSleep = !mRootActivityContainer.hasAwakeDisplay();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005263 final boolean wasSleeping = mSleeping;
5264 boolean updateOomAdj = false;
5265
5266 if (!shouldSleep) {
5267 // If wasSleeping is true, we need to wake up activity manager state from when
5268 // we started sleeping. In either case, we need to apply the sleep tokens, which
5269 // will wake up stacks or put them to sleep as appropriate.
5270 if (wasSleeping) {
5271 mSleeping = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005272 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5273 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__AWAKE);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005274 startTimeTrackingFocusedActivityLocked();
5275 mTopProcessState = ActivityManager.PROCESS_STATE_TOP;
5276 mStackSupervisor.comeOutOfSleepIfNeededLocked();
5277 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005278 mRootActivityContainer.applySleepTokens(true /* applyToStacks */);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005279 if (wasSleeping) {
5280 updateOomAdj = true;
5281 }
5282 } else if (!mSleeping && shouldSleep) {
5283 mSleeping = true;
Chenjie Yubd1a28f2018-07-17 14:55:19 -07005284 StatsLog.write(StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED,
5285 StatsLog.ACTIVITY_MANAGER_SLEEP_STATE_CHANGED__STATE__ASLEEP);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005286 if (mCurAppTimeTracker != null) {
5287 mCurAppTimeTracker.stop();
5288 }
5289 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING;
5290 mStackSupervisor.goingToSleepLocked();
5291 updateResumedAppTrace(null /* resumed */);
5292 updateOomAdj = true;
5293 }
5294 if (updateOomAdj) {
5295 mH.post(mAmInternal::updateOomAdj);
5296 }
5297 }
5298
5299 void updateOomAdj() {
5300 mH.post(mAmInternal::updateOomAdj);
5301 }
5302
Wale Ogunwale53783742018-09-16 10:21:51 -07005303 void updateCpuStats() {
5304 mH.post(mAmInternal::updateCpuStats);
5305 }
5306
Hui Yu03d12402018-12-06 18:00:37 -08005307 void updateBatteryStats(ActivityRecord component, boolean resumed) {
5308 final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::updateBatteryStats,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005309 mAmInternal, component.mActivityComponent, component.app.mUid, component.mUserId,
5310 resumed);
Wale Ogunwale53783742018-09-16 10:21:51 -07005311 mH.sendMessage(m);
5312 }
5313
Hui Yu03d12402018-12-06 18:00:37 -08005314 void updateActivityUsageStats(ActivityRecord activity, int event) {
5315 final Message m = PooledLambda.obtainMessage(
5316 ActivityManagerInternal::updateActivityUsageStats, mAmInternal,
5317 activity.mActivityComponent, activity.mUserId, event, activity.appToken);
5318 mH.sendMessage(m);
5319 }
5320
Wale Ogunwale53783742018-09-16 10:21:51 -07005321 void setBooting(boolean booting) {
5322 mAmInternal.setBooting(booting);
5323 }
5324
5325 boolean isBooting() {
5326 return mAmInternal.isBooting();
5327 }
5328
5329 void setBooted(boolean booted) {
5330 mAmInternal.setBooted(booted);
5331 }
5332
5333 boolean isBooted() {
5334 return mAmInternal.isBooted();
5335 }
5336
5337 void postFinishBooting(boolean finishBooting, boolean enableScreen) {
5338 mH.post(() -> {
5339 if (finishBooting) {
5340 mAmInternal.finishBooting();
5341 }
5342 if (enableScreen) {
5343 mInternal.enableScreenAfterBoot(isBooted());
5344 }
5345 });
5346 }
5347
5348 void setHeavyWeightProcess(ActivityRecord root) {
5349 mHeavyWeightProcess = root.app;
5350 final Message m = PooledLambda.obtainMessage(
5351 ActivityTaskManagerService::postHeavyWeightProcessNotification, this,
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005352 root.app, root.intent, root.mUserId);
Wale Ogunwale53783742018-09-16 10:21:51 -07005353 mH.sendMessage(m);
5354 }
5355
5356 void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
5357 if (mHeavyWeightProcess == null || mHeavyWeightProcess != proc) {
5358 return;
5359 }
5360
5361 mHeavyWeightProcess = null;
5362 final Message m = PooledLambda.obtainMessage(
5363 ActivityTaskManagerService::cancelHeavyWeightProcessNotification, this,
5364 proc.mUserId);
5365 mH.sendMessage(m);
5366 }
5367
5368 private void cancelHeavyWeightProcessNotification(int userId) {
5369 final INotificationManager inm = NotificationManager.getService();
5370 if (inm == null) {
5371 return;
5372 }
5373 try {
5374 inm.cancelNotificationWithTag("android", null,
5375 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, userId);
5376 } catch (RuntimeException e) {
5377 Slog.w(TAG, "Error canceling notification for service", e);
5378 } catch (RemoteException e) {
5379 }
5380
5381 }
5382
5383 private void postHeavyWeightProcessNotification(
5384 WindowProcessController proc, Intent intent, int userId) {
5385 if (proc == null) {
5386 return;
5387 }
5388
5389 final INotificationManager inm = NotificationManager.getService();
5390 if (inm == null) {
5391 return;
5392 }
5393
5394 try {
5395 Context context = mContext.createPackageContext(proc.mInfo.packageName, 0);
5396 String text = mContext.getString(R.string.heavy_weight_notification,
5397 context.getApplicationInfo().loadLabel(context.getPackageManager()));
5398 Notification notification =
5399 new Notification.Builder(context,
5400 SystemNotificationChannels.HEAVY_WEIGHT_APP)
5401 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5402 .setWhen(0)
5403 .setOngoing(true)
5404 .setTicker(text)
5405 .setColor(mContext.getColor(
5406 com.android.internal.R.color.system_notification_accent_color))
5407 .setContentTitle(text)
5408 .setContentText(
5409 mContext.getText(R.string.heavy_weight_notification_detail))
5410 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
5411 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
5412 new UserHandle(userId)))
5413 .build();
5414 try {
5415 inm.enqueueNotificationWithTag("android", "android", null,
5416 SystemMessage.NOTE_HEAVY_WEIGHT_NOTIFICATION, notification, userId);
5417 } catch (RuntimeException e) {
5418 Slog.w(TAG, "Error showing notification for heavy-weight app", e);
5419 } catch (RemoteException e) {
5420 }
5421 } catch (PackageManager.NameNotFoundException e) {
5422 Slog.w(TAG, "Unable to create context for heavy notification", e);
5423 }
5424
5425 }
5426
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005427 IIntentSender getIntentSenderLocked(int type, String packageName, int callingUid, int userId,
5428 IBinder token, String resultWho, int requestCode, Intent[] intents,
5429 String[] resolvedTypes, int flags, Bundle bOptions) {
5430
5431 ActivityRecord activity = null;
5432 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5433 activity = ActivityRecord.isInStackLocked(token);
5434 if (activity == null) {
5435 Slog.w(TAG, "Failed createPendingResult: activity " + token + " not in any stack");
5436 return null;
5437 }
5438 if (activity.finishing) {
5439 Slog.w(TAG, "Failed createPendingResult: activity " + activity + " is finishing");
5440 return null;
5441 }
5442 }
5443
5444 final PendingIntentRecord rec = mPendingIntentController.getIntentSender(type, packageName,
5445 callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5446 bOptions);
5447 final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
5448 if (noCreate) {
5449 return rec;
5450 }
5451 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5452 if (activity.pendingResults == null) {
5453 activity.pendingResults = new HashSet<>();
5454 }
5455 activity.pendingResults.add(rec.ref);
5456 }
5457 return rec;
5458 }
5459
Andrii Kulian52d255c2018-07-13 11:32:19 -07005460 // TODO(b/111541062): Update app time tracking to make it aware of multiple resumed activities
Wale Ogunwalef6733932018-06-27 05:14:34 -07005461 private void startTimeTrackingFocusedActivityLocked() {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005462 final ActivityRecord resumedActivity = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwalef6733932018-06-27 05:14:34 -07005463 if (!mSleeping && mCurAppTimeTracker != null && resumedActivity != null) {
5464 mCurAppTimeTracker.start(resumedActivity.packageName);
5465 }
5466 }
5467
5468 private void updateResumedAppTrace(@Nullable ActivityRecord resumed) {
5469 if (mTracedResumedActivity != null) {
5470 Trace.asyncTraceEnd(TRACE_TAG_ACTIVITY_MANAGER,
5471 constructResumedTraceName(mTracedResumedActivity.packageName), 0);
5472 }
5473 if (resumed != null) {
5474 Trace.asyncTraceBegin(TRACE_TAG_ACTIVITY_MANAGER,
5475 constructResumedTraceName(resumed.packageName), 0);
5476 }
5477 mTracedResumedActivity = resumed;
5478 }
5479
5480 private String constructResumedTraceName(String packageName) {
5481 return "focused app: " + packageName;
5482 }
5483
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005484 /** Applies latest configuration and/or visibility updates if needed. */
5485 private boolean ensureConfigAndVisibilityAfterUpdate(ActivityRecord starting, int changes) {
5486 boolean kept = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08005487 final ActivityStack mainStack = mRootActivityContainer.getTopDisplayFocusedStack();
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005488 // mainStack is null during startup.
5489 if (mainStack != null) {
5490 if (changes != 0 && starting == null) {
5491 // If the configuration changed, and the caller is not already
5492 // in the process of starting an activity, then find the top
5493 // activity to check if its configuration needs to change.
5494 starting = mainStack.topRunningActivityLocked();
5495 }
5496
5497 if (starting != null) {
5498 kept = starting.ensureActivityConfiguration(changes,
5499 false /* preserveWindow */);
5500 // And we need to make sure at this point that all other activities
5501 // are made visible with the correct configuration.
Wale Ogunwaled32da472018-11-16 07:19:28 -08005502 mRootActivityContainer.ensureActivitiesVisible(starting, changes,
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005503 !PRESERVE_WINDOWS);
5504 }
5505 }
5506
5507 return kept;
5508 }
5509
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005510 void scheduleAppGcsLocked() {
5511 mH.post(() -> mAmInternal.scheduleAppGcs());
5512 }
5513
Wale Ogunwale53783742018-09-16 10:21:51 -07005514 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
5515 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
5516 }
5517
Wale Ogunwale906f9c62018-07-23 11:23:44 -07005518 /**
5519 * Returns the PackageManager. Used by classes hosted by {@link ActivityTaskManagerService}. The
5520 * PackageManager could be unavailable at construction time and therefore needs to be accessed
5521 * on demand.
5522 */
5523 IPackageManager getPackageManager() {
5524 return AppGlobals.getPackageManager();
5525 }
5526
5527 PackageManagerInternal getPackageManagerInternalLocked() {
5528 if (mPmInternal == null) {
5529 mPmInternal = LocalServices.getService(PackageManagerInternal.class);
5530 }
5531 return mPmInternal;
5532 }
5533
Wale Ogunwale008163e2018-07-23 23:11:08 -07005534 AppWarnings getAppWarningsLocked() {
5535 return mAppWarnings;
5536 }
5537
Wale Ogunwale214f3482018-10-04 11:00:47 -07005538 Intent getHomeIntent() {
5539 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5540 intent.setComponent(mTopComponent);
5541 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5542 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5543 intent.addCategory(Intent.CATEGORY_HOME);
5544 }
5545 return intent;
5546 }
5547
Chilun2ef71f72018-11-16 17:57:15 +08005548 /**
5549 * Return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME} to resolve secondary home
5550 * activities.
5551 *
5552 * @param preferredPackage Specify a preferred package name, otherwise use secondary home
5553 * component defined in config_secondaryHomeComponent.
5554 * @return the intent set with {@link Intent#CATEGORY_SECONDARY_HOME}
5555 */
5556 Intent getSecondaryHomeIntent(String preferredPackage) {
5557 final Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
5558 if (preferredPackage == null) {
5559 // Using the component stored in config if no package name.
5560 final String secondaryHomeComponent = mContext.getResources().getString(
5561 com.android.internal.R.string.config_secondaryHomeComponent);
5562 intent.setComponent(ComponentName.unflattenFromString(secondaryHomeComponent));
5563 } else {
5564 intent.setPackage(preferredPackage);
5565 }
5566 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
5567 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5568 intent.addCategory(Intent.CATEGORY_SECONDARY_HOME);
5569 }
5570 return intent;
5571 }
5572
Wale Ogunwale214f3482018-10-04 11:00:47 -07005573 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
5574 if (info == null) return null;
5575 ApplicationInfo newInfo = new ApplicationInfo(info);
5576 newInfo.initForUser(userId);
5577 return newInfo;
5578 }
5579
Wale Ogunwale9c103022018-10-18 07:44:54 -07005580 WindowProcessController getProcessController(String processName, int uid) {
Wale Ogunwale214f3482018-10-04 11:00:47 -07005581 if (uid == SYSTEM_UID) {
5582 // The system gets to run in any process. If there are multiple processes with the same
5583 // uid, just pick the first (this should never happen).
5584 final SparseArray<WindowProcessController> procs =
5585 mProcessNames.getMap().get(processName);
5586 if (procs == null) return null;
5587 final int procCount = procs.size();
5588 for (int i = 0; i < procCount; i++) {
5589 final int procUid = procs.keyAt(i);
5590 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) {
5591 // Don't use an app process or different user process for system component.
5592 continue;
5593 }
5594 return procs.valueAt(i);
5595 }
5596 }
5597
5598 return mProcessNames.get(processName, uid);
5599 }
5600
Wale Ogunwale342fbe92018-10-09 08:44:10 -07005601 WindowProcessController getProcessController(IApplicationThread thread) {
5602 if (thread == null) {
5603 return null;
5604 }
5605
5606 final IBinder threadBinder = thread.asBinder();
5607 final ArrayMap<String, SparseArray<WindowProcessController>> pmap = mProcessNames.getMap();
5608 for (int i = pmap.size()-1; i >= 0; i--) {
5609 final SparseArray<WindowProcessController> procs = pmap.valueAt(i);
5610 for (int j = procs.size() - 1; j >= 0; j--) {
5611 final WindowProcessController proc = procs.valueAt(j);
5612 if (proc.hasThread() && proc.getThread().asBinder() == threadBinder) {
5613 return proc;
5614 }
5615 }
5616 }
5617
5618 return null;
5619 }
5620
Wale Ogunwalebff2df42018-10-18 17:09:19 -07005621 int getUidStateLocked(int uid) {
5622 return mActiveUids.get(uid, PROCESS_STATE_NONEXISTENT);
5623 }
5624
Wale Ogunwale9de19442018-10-18 19:05:03 -07005625 /**
5626 * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
5627 * the whitelist
5628 */
5629 String getPendingTempWhitelistTagForUidLocked(int uid) {
5630 return mPendingTempWhitelist.get(uid);
5631 }
5632
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07005633 void logAppTooSlow(WindowProcessController app, long startTime, String msg) {
5634 if (true || Build.IS_USER) {
5635 return;
5636 }
5637
5638 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
5639 StrictMode.allowThreadDiskWrites();
5640 try {
5641 File tracesDir = new File("/data/anr");
5642 File tracesFile = null;
5643 try {
5644 tracesFile = File.createTempFile("app_slow", null, tracesDir);
5645
5646 StringBuilder sb = new StringBuilder();
5647 Time tobj = new Time();
5648 tobj.set(System.currentTimeMillis());
5649 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
5650 sb.append(": ");
5651 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
5652 sb.append(" since ");
5653 sb.append(msg);
5654 FileOutputStream fos = new FileOutputStream(tracesFile);
5655 fos.write(sb.toString().getBytes());
5656 if (app == null) {
5657 fos.write("\n*** No application process!".getBytes());
5658 }
5659 fos.close();
5660 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
5661 } catch (IOException e) {
5662 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesFile, e);
5663 return;
5664 }
5665
5666 if (app != null && app.getPid() > 0) {
5667 ArrayList<Integer> firstPids = new ArrayList<Integer>();
5668 firstPids.add(app.getPid());
5669 dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, null, null);
5670 }
5671
5672 File lastTracesFile = null;
5673 File curTracesFile = null;
5674 for (int i=9; i>=0; i--) {
5675 String name = String.format(Locale.US, "slow%02d.txt", i);
5676 curTracesFile = new File(tracesDir, name);
5677 if (curTracesFile.exists()) {
5678 if (lastTracesFile != null) {
5679 curTracesFile.renameTo(lastTracesFile);
5680 } else {
5681 curTracesFile.delete();
5682 }
5683 }
5684 lastTracesFile = curTracesFile;
5685 }
5686 tracesFile.renameTo(curTracesFile);
5687 } finally {
5688 StrictMode.setThreadPolicy(oldPolicy);
5689 }
5690 }
5691
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005692 final class H extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005693 static final int REPORT_TIME_TRACKER_MSG = 1;
Alison Cichowlas3e340502018-08-07 17:15:01 -04005694
5695
Wale Ogunwale98875612018-10-12 07:53:02 -07005696 static final int FIRST_ACTIVITY_STACK_MSG = 100;
5697 static final int FIRST_SUPERVISOR_STACK_MSG = 200;
Wale Ogunwalef6733932018-06-27 05:14:34 -07005698
Riddle Hsud93a6c42018-11-29 21:50:06 +08005699 H(Looper looper) {
5700 super(looper);
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005701 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005702
5703 @Override
5704 public void handleMessage(Message msg) {
5705 switch (msg.what) {
5706 case REPORT_TIME_TRACKER_MSG: {
5707 AppTimeTracker tracker = (AppTimeTracker) msg.obj;
5708 tracker.deliverResult(mContext);
5709 } break;
5710 }
5711 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005712 }
5713
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005714 final class UiHandler extends Handler {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005715 static final int DISMISS_DIALOG_UI_MSG = 1;
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005716
5717 public UiHandler() {
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08005718 super(UiThread.get().getLooper(), null, true);
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005719 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07005720
5721 @Override
5722 public void handleMessage(Message msg) {
5723 switch (msg.what) {
5724 case DISMISS_DIALOG_UI_MSG: {
5725 final Dialog d = (Dialog) msg.obj;
5726 d.dismiss();
5727 break;
5728 }
5729 }
5730 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005731 }
5732
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005733 final class LocalService extends ActivityTaskManagerInternal {
5734 @Override
5735 public SleepToken acquireSleepToken(String tag, int displayId) {
5736 Preconditions.checkNotNull(tag);
Wale Ogunwalef6733932018-06-27 05:14:34 -07005737 return ActivityTaskManagerService.this.acquireSleepToken(tag, displayId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005738 }
5739
5740 @Override
5741 public ComponentName getHomeActivityForUser(int userId) {
5742 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005743 final ActivityRecord homeActivity =
5744 mRootActivityContainer.getDefaultDisplayHomeActivityForUser(userId);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08005745 return homeActivity == null ? null : homeActivity.mActivityComponent;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005746 }
5747 }
5748
5749 @Override
5750 public void onLocalVoiceInteractionStarted(IBinder activity,
5751 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
5752 synchronized (mGlobalLock) {
Wale Ogunwalef6733932018-06-27 05:14:34 -07005753 onLocalVoiceInteractionStartedLocked(activity, voiceSession, voiceInteractor);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005754 }
5755 }
5756
5757 @Override
5758 public void notifyAppTransitionStarting(SparseIntArray reasons, long timestamp) {
5759 synchronized (mGlobalLock) {
5760 mStackSupervisor.getActivityMetricsLogger().notifyTransitionStarting(
5761 reasons, timestamp);
5762 }
5763 }
5764
5765 @Override
5766 public void notifyAppTransitionFinished() {
5767 synchronized (mGlobalLock) {
5768 mStackSupervisor.notifyAppTransitionDone();
5769 }
5770 }
5771
5772 @Override
5773 public void notifyAppTransitionCancelled() {
5774 synchronized (mGlobalLock) {
5775 mStackSupervisor.notifyAppTransitionDone();
5776 }
5777 }
5778
5779 @Override
5780 public List<IBinder> getTopVisibleActivities() {
5781 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005782 return mRootActivityContainer.getTopVisibleActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005783 }
5784 }
5785
5786 @Override
5787 public void notifyDockedStackMinimizedChanged(boolean minimized) {
5788 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005789 mRootActivityContainer.setDockedStackMinimized(minimized);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005790 }
5791 }
5792
5793 @Override
5794 public int startActivitiesAsPackage(String packageName, int userId, Intent[] intents,
5795 Bundle bOptions) {
5796 Preconditions.checkNotNull(intents, "intents");
5797 final String[] resolvedTypes = new String[intents.length];
5798
5799 // UID of the package on user userId.
5800 // "= 0" is needed because otherwise catch(RemoteException) would make it look like
5801 // packageUid may not be initialized.
5802 int packageUid = 0;
5803 final long ident = Binder.clearCallingIdentity();
5804
5805 try {
5806 for (int i = 0; i < intents.length; i++) {
5807 resolvedTypes[i] =
5808 intents[i].resolveTypeIfNeeded(mContext.getContentResolver());
5809 }
5810
5811 packageUid = AppGlobals.getPackageManager().getPackageUid(
5812 packageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING, userId);
5813 } catch (RemoteException e) {
5814 // Shouldn't happen.
5815 } finally {
5816 Binder.restoreCallingIdentity(ident);
5817 }
5818
5819 synchronized (mGlobalLock) {
Wale Ogunwale5fa8a8c2018-05-08 13:43:21 -07005820 return getActivityStartController().startActivitiesInPackage(
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005821 packageUid, packageName,
5822 intents, resolvedTypes, null /* resultTo */,
5823 SafeActivityOptions.fromBundle(bOptions), userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005824 false /* validateIncomingUser */, null /* originatingPendingIntent */,
5825 false /* allowBackgroundActivityStart */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005826 }
5827 }
5828
5829 @Override
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005830 public int startActivitiesInPackage(int uid, String callingPackage, Intent[] intents,
5831 String[] resolvedTypes, IBinder resultTo, SafeActivityOptions options, int userId,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005832 boolean validateIncomingUser, PendingIntentRecord originatingPendingIntent,
5833 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005834 synchronized (mGlobalLock) {
5835 return getActivityStartController().startActivitiesInPackage(uid, callingPackage,
5836 intents, resolvedTypes, resultTo, options, userId, validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005837 originatingPendingIntent, allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005838 }
5839 }
5840
5841 @Override
5842 public int startActivityInPackage(int uid, int realCallingPid, int realCallingUid,
5843 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
5844 String resultWho, int requestCode, int startFlags, SafeActivityOptions options,
5845 int userId, TaskRecord inTask, String reason, boolean validateIncomingUser,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005846 PendingIntentRecord originatingPendingIntent,
5847 boolean allowBackgroundActivityStart) {
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005848 synchronized (mGlobalLock) {
5849 return getActivityStartController().startActivityInPackage(uid, realCallingPid,
5850 realCallingUid, callingPackage, intent, resolvedType, resultTo, resultWho,
5851 requestCode, startFlags, options, userId, inTask, reason,
Michal Karpinskiac116df2018-12-10 17:51:42 +00005852 validateIncomingUser, originatingPendingIntent,
5853 allowBackgroundActivityStart);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07005854 }
5855 }
5856
5857 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005858 public int startActivityAsUser(IApplicationThread caller, String callerPacakge,
5859 Intent intent, Bundle options, int userId) {
5860 return ActivityTaskManagerService.this.startActivityAsUser(
5861 caller, callerPacakge, intent,
5862 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
5863 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, userId,
5864 false /*validateIncomingUser*/);
5865 }
5866
5867 @Override
lumark588a3e82018-07-20 18:53:54 +08005868 public void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005869 synchronized (mGlobalLock) {
5870
5871 // We might change the visibilities here, so prepare an empty app transition which
5872 // might be overridden later if we actually change visibilities.
lumark52ea28e2018-11-09 17:30:47 +08005873 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08005874 mRootActivityContainer.getActivityDisplay(displayId);
lumark52ea28e2018-11-09 17:30:47 +08005875 if (activityDisplay == null) {
5876 return;
5877 }
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005878 final DisplayContent dc = activityDisplay.mDisplayContent;
5879 final boolean wasTransitionSet =
5880 dc.mAppTransition.getAppTransition() != TRANSIT_NONE;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005881 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005882 dc.prepareAppTransition(TRANSIT_NONE, false /* alwaysKeepCurrent */);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005883 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08005884 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005885
5886 // If there was a transition set already we don't want to interfere with it as we
5887 // might be starting it too early.
5888 if (!wasTransitionSet) {
Wale Ogunwale3a256e62018-12-06 14:41:18 -08005889 dc.executeAppTransition();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005890 }
5891 }
5892 if (callback != null) {
5893 callback.run();
5894 }
5895 }
5896
5897 @Override
5898 public void notifyKeyguardTrustedChanged() {
5899 synchronized (mGlobalLock) {
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005900 if (mKeyguardController.isKeyguardShowing(DEFAULT_DISPLAY)) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005901 mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005902 }
5903 }
5904 }
5905
5906 /**
5907 * Called after virtual display Id is updated by
5908 * {@link com.android.server.vr.Vr2dDisplay} with a specific
5909 * {@param vrVr2dDisplayId}.
5910 */
5911 @Override
5912 public void setVr2dDisplayId(int vr2dDisplayId) {
5913 if (DEBUG_STACK) Slog.d(TAG, "setVr2dDisplayId called for: " + vr2dDisplayId);
5914 synchronized (mGlobalLock) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005915 mVr2dDisplayId = vr2dDisplayId;
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005916 }
5917 }
5918
5919 @Override
5920 public void setFocusedActivity(IBinder token) {
5921 synchronized (mGlobalLock) {
5922 final ActivityRecord r = ActivityRecord.forTokenLocked(token);
5923 if (r == null) {
5924 throw new IllegalArgumentException(
5925 "setFocusedActivity: No activity record matching token=" + token);
5926 }
Louis Chang19443452018-10-09 12:10:21 +08005927 if (r.moveFocusableActivityToTop("setFocusedActivity")) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08005928 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005929 }
5930 }
5931 }
5932
5933 @Override
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005934 public void registerScreenObserver(ScreenObserver observer) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005935 mScreenObservers.add(observer);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005936 }
5937
5938 @Override
5939 public boolean isCallerRecents(int callingUid) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005940 return getRecentTasks().isCallerRecents(callingUid);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005941 }
5942
5943 @Override
5944 public boolean isRecentsComponentHomeActivity(int userId) {
Wale Ogunwale16e505a2018-05-07 15:00:49 -07005945 return getRecentTasks().isRecentsComponentHomeActivity(userId);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005946 }
5947
5948 @Override
5949 public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
5950 ActivityTaskManagerService.this.cancelRecentsAnimation(restoreHomeStackPosition);
5951 }
5952
5953 @Override
5954 public void enforceCallerIsRecentsOrHasPermission(String permission, String func) {
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005955 ActivityTaskManagerService.this.enforceCallerIsRecentsOrHasPermission(permission, func);
Wale Ogunwale6767eae2018-05-03 15:52:51 -07005956 }
Wale Ogunwaled0412b32018-05-08 09:25:50 -07005957
5958 @Override
5959 public void notifyActiveVoiceInteractionServiceChanged(ComponentName component) {
5960 synchronized (mGlobalLock) {
5961 mActiveVoiceInteractionServiceComponent = component;
5962 }
5963 }
Wale Ogunwalea6191b42018-05-09 07:41:32 -07005964
5965 @Override
5966 public void setAllowAppSwitches(@NonNull String type, int uid, int userId) {
5967 if (!mAmInternal.isUserRunning(userId, ActivityManager.FLAG_OR_STOPPED)) {
5968 return;
5969 }
5970 synchronized (mGlobalLock) {
5971 ArrayMap<String, Integer> types = mAllowAppSwitchUids.get(userId);
5972 if (types == null) {
5973 if (uid < 0) {
5974 return;
5975 }
5976 types = new ArrayMap<>();
5977 mAllowAppSwitchUids.put(userId, types);
5978 }
5979 if (uid < 0) {
5980 types.remove(type);
5981 } else {
5982 types.put(type, uid);
5983 }
5984 }
5985 }
5986
5987 @Override
5988 public void onUserStopped(int userId) {
5989 synchronized (mGlobalLock) {
5990 getRecentTasks().unloadUserDataFromMemoryLocked(userId);
5991 mAllowAppSwitchUids.remove(userId);
5992 }
5993 }
5994
5995 @Override
5996 public boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) {
5997 synchronized (mGlobalLock) {
5998 return ActivityTaskManagerService.this.isGetTasksAllowed(
5999 caller, callingPid, callingUid);
6000 }
6001 }
Wale Ogunwale9e4f3e02018-05-17 09:35:39 -07006002
6003 @Override
6004 public void onProcessAdded(WindowProcessController proc) {
6005 synchronized (mGlobalLock) {
6006 mProcessNames.put(proc.mName, proc.mUid, proc);
6007 }
6008 }
6009
6010 @Override
6011 public void onProcessRemoved(String name, int uid) {
6012 synchronized (mGlobalLock) {
6013 mProcessNames.remove(name, uid);
6014 }
6015 }
6016
6017 @Override
6018 public void onCleanUpApplicationRecord(WindowProcessController proc) {
6019 synchronized (mGlobalLock) {
6020 if (proc == mHomeProcess) {
6021 mHomeProcess = null;
6022 }
6023 if (proc == mPreviousProcess) {
6024 mPreviousProcess = null;
6025 }
6026 }
6027 }
Wale Ogunwalef6733932018-06-27 05:14:34 -07006028
6029 @Override
6030 public int getTopProcessState() {
6031 synchronized (mGlobalLock) {
6032 return mTopProcessState;
6033 }
6034 }
6035
6036 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006037 public boolean isHeavyWeightProcess(WindowProcessController proc) {
6038 synchronized (mGlobalLock) {
6039 return proc == mHeavyWeightProcess;
6040 }
6041 }
6042
6043 @Override
6044 public void clearHeavyWeightProcessIfEquals(WindowProcessController proc) {
6045 synchronized (mGlobalLock) {
6046 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(proc);
6047 }
6048 }
6049
6050 @Override
6051 public void finishHeavyWeightApp() {
6052 synchronized (mGlobalLock) {
Sudheer Shankaee1da272018-10-20 20:11:44 -07006053 if (mHeavyWeightProcess != null) {
6054 mHeavyWeightProcess.finishActivities();
6055 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006056 ActivityTaskManagerService.this.clearHeavyWeightProcessIfEquals(
6057 mHeavyWeightProcess);
6058 }
6059 }
6060
6061 @Override
Wale Ogunwalef6733932018-06-27 05:14:34 -07006062 public boolean isSleeping() {
6063 synchronized (mGlobalLock) {
6064 return isSleepingLocked();
6065 }
6066 }
6067
6068 @Override
6069 public boolean isShuttingDown() {
6070 synchronized (mGlobalLock) {
6071 return mShuttingDown;
6072 }
6073 }
6074
6075 @Override
6076 public boolean shuttingDown(boolean booted, int timeout) {
6077 synchronized (mGlobalLock) {
6078 mShuttingDown = true;
Wale Ogunwaled32da472018-11-16 07:19:28 -08006079 mRootActivityContainer.prepareForShutdown();
Wale Ogunwalef6733932018-06-27 05:14:34 -07006080 updateEventDispatchingLocked(booted);
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006081 notifyTaskPersisterLocked(null, true);
Wale Ogunwalef6733932018-06-27 05:14:34 -07006082 return mStackSupervisor.shutdownLocked(timeout);
6083 }
6084 }
6085
6086 @Override
6087 public void enableScreenAfterBoot(boolean booted) {
6088 synchronized (mGlobalLock) {
6089 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
6090 SystemClock.uptimeMillis());
6091 mWindowManager.enableScreenAfterBoot();
6092 updateEventDispatchingLocked(booted);
6093 }
6094 }
6095
6096 @Override
6097 public boolean showStrictModeViolationDialog() {
6098 synchronized (mGlobalLock) {
6099 return mShowDialogs && !mSleeping && !mShuttingDown;
6100 }
6101 }
6102
6103 @Override
6104 public void showSystemReadyErrorDialogsIfNeeded() {
6105 synchronized (mGlobalLock) {
6106 try {
6107 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
6108 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
6109 + " data partition or your device will be unstable.");
6110 mUiHandler.post(() -> {
6111 if (mShowDialogs) {
6112 AlertDialog d = new BaseErrorDialog(mUiContext);
6113 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6114 d.setCancelable(false);
6115 d.setTitle(mUiContext.getText(R.string.android_system_label));
6116 d.setMessage(mUiContext.getText(R.string.system_error_wipe_data));
6117 d.setButton(DialogInterface.BUTTON_POSITIVE,
6118 mUiContext.getText(R.string.ok),
6119 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6120 d.show();
6121 }
6122 });
6123 }
6124 } catch (RemoteException e) {
6125 }
6126
6127 if (!Build.isBuildConsistent()) {
6128 Slog.e(TAG, "Build fingerprint is not consistent, warning user");
6129 mUiHandler.post(() -> {
6130 if (mShowDialogs) {
6131 AlertDialog d = new BaseErrorDialog(mUiContext);
6132 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
6133 d.setCancelable(false);
6134 d.setTitle(mUiContext.getText(R.string.android_system_label));
6135 d.setMessage(mUiContext.getText(R.string.system_error_manufacturer));
6136 d.setButton(DialogInterface.BUTTON_POSITIVE,
6137 mUiContext.getText(R.string.ok),
6138 mUiHandler.obtainMessage(DISMISS_DIALOG_UI_MSG, d));
6139 d.show();
6140 }
6141 });
6142 }
6143 }
6144 }
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006145
6146 @Override
Wale Ogunwale906f9c62018-07-23 11:23:44 -07006147 public void onProcessMapped(int pid, WindowProcessController proc) {
6148 synchronized (mGlobalLock) {
6149 mPidMap.put(pid, proc);
6150 }
6151 }
6152
6153 @Override
6154 public void onProcessUnMapped(int pid) {
6155 synchronized (mGlobalLock) {
6156 mPidMap.remove(pid);
6157 }
6158 }
Wale Ogunwale008163e2018-07-23 23:11:08 -07006159
6160 @Override
6161 public void onPackageDataCleared(String name) {
6162 synchronized (mGlobalLock) {
Wale Ogunwale53783742018-09-16 10:21:51 -07006163 mCompatModePackages.handlePackageDataClearedLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006164 mAppWarnings.onPackageDataCleared(name);
6165 }
6166 }
6167
6168 @Override
6169 public void onPackageUninstalled(String name) {
6170 synchronized (mGlobalLock) {
6171 mAppWarnings.onPackageUninstalled(name);
Wale Ogunwale53783742018-09-16 10:21:51 -07006172 mCompatModePackages.handlePackageUninstalledLocked(name);
Wale Ogunwale008163e2018-07-23 23:11:08 -07006173 }
6174 }
Wale Ogunwale53783742018-09-16 10:21:51 -07006175
6176 @Override
6177 public void onPackageAdded(String name, boolean replacing) {
6178 synchronized (mGlobalLock) {
6179 mCompatModePackages.handlePackageAddedLocked(name, replacing);
6180 }
6181 }
6182
6183 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006184 public void onPackageReplaced(ApplicationInfo aInfo) {
6185 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006186 mRootActivityContainer.updateActivityApplicationInfo(aInfo);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006187 }
6188 }
6189
6190 @Override
Wale Ogunwale53783742018-09-16 10:21:51 -07006191 public CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
6192 synchronized (mGlobalLock) {
6193 return compatibilityInfoForPackageLocked(ai);
6194 }
6195 }
6196
Yunfan Chen75157d72018-07-27 14:47:21 +09006197 /**
6198 * Set the corresponding display information for the process global configuration. To be
6199 * called when we need to show IME on a different display.
6200 *
6201 * @param pid The process id associated with the IME window.
6202 * @param displayId The ID of the display showing the IME.
6203 */
6204 @Override
Yunfan Chen79b96062018-10-17 12:45:23 -07006205 public void onImeWindowSetOnDisplay(final int pid, final int displayId) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006206 if (pid == MY_PID || pid < 0) {
6207 if (DEBUG_CONFIGURATION) {
6208 Slog.w(TAG,
6209 "Trying to update display configuration for system/invalid process.");
6210 }
6211 return;
6212 }
6213 mH.post(() -> {
6214 synchronized (mGlobalLock) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006215 final ActivityDisplay activityDisplay =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006216 mRootActivityContainer.getActivityDisplay(displayId);
Yunfan Chen79b96062018-10-17 12:45:23 -07006217 if (activityDisplay == null) {
6218 // Call might come when display is not yet added or has been removed.
Yunfan Chen75157d72018-07-27 14:47:21 +09006219 if (DEBUG_CONFIGURATION) {
6220 Slog.w(TAG, "Trying to update display configuration for non-existing "
Yunfan Chen79b96062018-10-17 12:45:23 -07006221 + "displayId=" + displayId);
Yunfan Chen75157d72018-07-27 14:47:21 +09006222 }
6223 return;
6224 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006225 final WindowProcessController process = mPidMap.get(pid);
6226 if (process == null) {
Yunfan Chen75157d72018-07-27 14:47:21 +09006227 if (DEBUG_CONFIGURATION) {
Yunfan Chen79b96062018-10-17 12:45:23 -07006228 Slog.w(TAG, "Trying to update display configuration for invalid "
6229 + "process, pid=" + pid);
Yunfan Chen75157d72018-07-27 14:47:21 +09006230 }
6231 return;
6232 }
Yunfan Chen79b96062018-10-17 12:45:23 -07006233 process.registerDisplayConfigurationListenerLocked(activityDisplay);
Yunfan Chen75157d72018-07-27 14:47:21 +09006234 }
6235 });
Yunfan Chen79b96062018-10-17 12:45:23 -07006236
Yunfan Chen75157d72018-07-27 14:47:21 +09006237 }
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006238
6239 @Override
6240 public void sendActivityResult(int callingUid, IBinder activityToken, String resultWho,
6241 int requestCode, int resultCode, Intent data) {
6242 synchronized (mGlobalLock) {
6243 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006244 if (r != null && r.getActivityStack() != null) {
6245 r.getActivityStack().sendActivityResultLocked(callingUid, r, resultWho,
6246 requestCode, resultCode, data);
Wale Ogunwaleee6eca12018-09-19 20:37:53 -07006247 }
6248 }
6249 }
6250
6251 @Override
6252 public void clearPendingResultForActivity(IBinder activityToken,
6253 WeakReference<PendingIntentRecord> pir) {
6254 synchronized (mGlobalLock) {
6255 final ActivityRecord r = ActivityRecord.isInStackLocked(activityToken);
6256 if (r != null && r.pendingResults != null) {
6257 r.pendingResults.remove(pir);
6258 }
6259 }
6260 }
6261
6262 @Override
6263 public IIntentSender getIntentSender(int type, String packageName,
6264 int callingUid, int userId, IBinder token, String resultWho,
6265 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
6266 Bundle bOptions) {
6267 synchronized (mGlobalLock) {
6268 return getIntentSenderLocked(type, packageName, callingUid, userId, token,
6269 resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
6270 }
6271 }
Wale Ogunwalec4e63a42018-10-02 13:19:54 -07006272
6273 @Override
6274 public ActivityServiceConnectionsHolder getServiceConnectionsHolder(IBinder token) {
6275 synchronized (mGlobalLock) {
6276 final ActivityRecord r = ActivityRecord.isInStackLocked(token);
6277 if (r == null) {
6278 return null;
6279 }
6280 if (r.mServiceConnectionsHolder == null) {
6281 r.mServiceConnectionsHolder = new ActivityServiceConnectionsHolder(
6282 ActivityTaskManagerService.this, r);
6283 }
6284
6285 return r.mServiceConnectionsHolder;
6286 }
6287 }
Wale Ogunwale214f3482018-10-04 11:00:47 -07006288
6289 @Override
6290 public Intent getHomeIntent() {
6291 synchronized (mGlobalLock) {
6292 return ActivityTaskManagerService.this.getHomeIntent();
6293 }
6294 }
6295
6296 @Override
6297 public boolean startHomeActivity(int userId, String reason) {
6298 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006299 return mRootActivityContainer.startHomeOnDisplay(userId, reason, DEFAULT_DISPLAY);
Louis Chang89f43fc2018-10-05 10:59:14 +08006300 }
6301 }
6302
6303 @Override
6304 public boolean startHomeOnAllDisplays(int userId, String reason) {
6305 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006306 return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
Wale Ogunwale214f3482018-10-04 11:00:47 -07006307 }
6308 }
6309
6310 @Override
6311 public boolean isFactoryTestProcess(WindowProcessController wpc) {
6312 synchronized (mGlobalLock) {
6313 if (mFactoryTest == FACTORY_TEST_OFF) {
6314 return false;
6315 }
6316 if (mFactoryTest == FACTORY_TEST_LOW_LEVEL && mTopComponent != null
6317 && wpc.mName.equals(mTopComponent.getPackageName())) {
6318 return true;
6319 }
6320 return mFactoryTest == FACTORY_TEST_HIGH_LEVEL
6321 && (wpc.mInfo.flags & FLAG_FACTORY_TEST) != 0;
6322 }
6323 }
6324
6325 @Override
6326 public void updateTopComponentForFactoryTest() {
6327 synchronized (mGlobalLock) {
6328 if (mFactoryTest != FACTORY_TEST_LOW_LEVEL) {
6329 return;
6330 }
6331 final ResolveInfo ri = mContext.getPackageManager()
6332 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), STOCK_PM_FLAGS);
6333 final CharSequence errorMsg;
6334 if (ri != null) {
6335 final ActivityInfo ai = ri.activityInfo;
6336 final ApplicationInfo app = ai.applicationInfo;
6337 if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6338 mTopAction = Intent.ACTION_FACTORY_TEST;
6339 mTopData = null;
6340 mTopComponent = new ComponentName(app.packageName, ai.name);
6341 errorMsg = null;
6342 } else {
6343 errorMsg = mContext.getResources().getText(
6344 com.android.internal.R.string.factorytest_not_system);
6345 }
6346 } else {
6347 errorMsg = mContext.getResources().getText(
6348 com.android.internal.R.string.factorytest_no_action);
6349 }
6350 if (errorMsg == null) {
6351 return;
6352 }
6353
6354 mTopAction = null;
6355 mTopData = null;
6356 mTopComponent = null;
6357 mUiHandler.post(() -> {
6358 Dialog d = new FactoryErrorDialog(mUiContext, errorMsg);
6359 d.show();
Wale Ogunwale342fbe92018-10-09 08:44:10 -07006360 mAmInternal.ensureBootCompleted();
Wale Ogunwale214f3482018-10-04 11:00:47 -07006361 });
6362 }
6363 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006364
6365 @Override
6366 public void handleAppDied(WindowProcessController wpc, boolean restarting,
6367 Runnable finishInstrumentationCallback) {
6368 synchronized (mGlobalLock) {
6369 // Remove this application's activities from active lists.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006370 boolean hasVisibleActivities = mRootActivityContainer.handleAppDied(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006371
6372 wpc.clearRecentTasks();
6373 wpc.clearActivities();
6374
6375 if (wpc.isInstrumenting()) {
6376 finishInstrumentationCallback.run();
6377 }
6378
Jorim Jaggid0752812018-10-16 16:07:20 +02006379 if (!restarting && hasVisibleActivities) {
6380 mWindowManager.deferSurfaceLayout();
6381 try {
6382 if (!mRootActivityContainer.resumeFocusedStacksTopActivities()) {
6383 // If there was nothing to resume, and we are not already restarting
6384 // this process, but there is a visible activity that is hosted by the
6385 // process...then make sure all visible activities are running, taking
6386 // care of restarting this process.
6387 mRootActivityContainer.ensureActivitiesVisible(null, 0,
6388 !PRESERVE_WINDOWS);
6389 }
6390 } finally {
6391 mWindowManager.continueSurfaceLayout();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006392 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006393 }
6394 }
6395 }
6396
6397 @Override
6398 public void closeSystemDialogs(String reason) {
6399 enforceNotIsolatedCaller("closeSystemDialogs");
6400
6401 final int pid = Binder.getCallingPid();
6402 final int uid = Binder.getCallingUid();
6403 final long origId = Binder.clearCallingIdentity();
6404 try {
6405 synchronized (mGlobalLock) {
6406 // Only allow this from foreground processes, so that background
6407 // applications can't abuse it to prevent system UI from being shown.
6408 if (uid >= FIRST_APPLICATION_UID) {
6409 final WindowProcessController proc = mPidMap.get(pid);
6410 if (!proc.isPerceptible()) {
6411 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
6412 + " from background process " + proc);
6413 return;
6414 }
6415 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006416 mWindowManager.closeSystemDialogs(reason);
6417
Wale Ogunwaled32da472018-11-16 07:19:28 -08006418 mRootActivityContainer.closeSystemDialogs();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006419 }
Wale Ogunwale2ea36d42018-10-18 10:27:31 -07006420 // Call into AM outside the synchronized block.
6421 mAmInternal.broadcastCloseSystemDialogs(reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006422 } finally {
6423 Binder.restoreCallingIdentity(origId);
6424 }
6425 }
6426
6427 @Override
6428 public void cleanupDisabledPackageComponents(
6429 String packageName, Set<String> disabledClasses, int userId, boolean booted) {
6430 synchronized (mGlobalLock) {
6431 // Clean-up disabled activities.
Wale Ogunwaled32da472018-11-16 07:19:28 -08006432 if (mRootActivityContainer.finishDisabledPackageActivities(
Wale Ogunwale31913b52018-10-13 08:29:31 -07006433 packageName, disabledClasses, true, false, userId) && booted) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006434 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006435 mStackSupervisor.scheduleIdleLocked();
6436 }
6437
6438 // Clean-up disabled tasks
6439 getRecentTasks().cleanupDisabledPackageTasksLocked(
6440 packageName, disabledClasses, userId);
6441 }
6442 }
6443
6444 @Override
6445 public boolean onForceStopPackage(String packageName, boolean doit, boolean evenPersistent,
6446 int userId) {
6447 synchronized (mGlobalLock) {
6448
6449 boolean didSomething =
6450 getActivityStartController().clearPendingActivityLaunches(packageName);
Wale Ogunwaled32da472018-11-16 07:19:28 -08006451 didSomething |= mRootActivityContainer.finishDisabledPackageActivities(packageName,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006452 null, doit, evenPersistent, userId);
6453 return didSomething;
6454 }
6455 }
6456
6457 @Override
6458 public void resumeTopActivities(boolean scheduleIdle) {
6459 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006460 mRootActivityContainer.resumeFocusedStacksTopActivities();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006461 if (scheduleIdle) {
6462 mStackSupervisor.scheduleIdleLocked();
6463 }
6464 }
6465 }
6466
6467 @Override
6468 public void preBindApplication(WindowProcessController wpc) {
6469 synchronized (mGlobalLock) {
6470 mStackSupervisor.getActivityMetricsLogger().notifyBindApplication(wpc.mInfo);
6471 }
6472 }
6473
6474 @Override
6475 public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
6476 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006477 return mRootActivityContainer.attachApplication(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006478 }
6479 }
6480
6481 @Override
6482 public void notifyLockedProfile(@UserIdInt int userId, int currentUserId) {
6483 try {
6484 if (!AppGlobals.getPackageManager().isUidPrivileged(Binder.getCallingUid())) {
6485 throw new SecurityException("Only privileged app can call notifyLockedProfile");
6486 }
6487 } catch (RemoteException ex) {
6488 throw new SecurityException("Fail to check is caller a privileged app", ex);
6489 }
6490
6491 synchronized (mGlobalLock) {
6492 final long ident = Binder.clearCallingIdentity();
6493 try {
6494 if (mAmInternal.shouldConfirmCredentials(userId)) {
6495 if (mKeyguardController.isKeyguardLocked()) {
6496 // Showing launcher to avoid user entering credential twice.
6497 startHomeActivity(currentUserId, "notifyLockedProfile");
6498 }
Wale Ogunwaled32da472018-11-16 07:19:28 -08006499 mRootActivityContainer.lockAllProfileTasks(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006500 }
6501 } finally {
6502 Binder.restoreCallingIdentity(ident);
6503 }
6504 }
6505 }
6506
6507 @Override
6508 public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6509 mAmInternal.enforceCallingPermission(
6510 MANAGE_ACTIVITY_STACKS, "startConfirmDeviceCredentialIntent");
6511
6512 synchronized (mGlobalLock) {
6513 final long ident = Binder.clearCallingIdentity();
6514 try {
6515 intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
6516 FLAG_ACTIVITY_TASK_ON_HOME);
6517 ActivityOptions activityOptions = options != null
6518 ? new ActivityOptions(options) : ActivityOptions.makeBasic();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006519 final ActivityRecord homeActivity =
Wale Ogunwaled32da472018-11-16 07:19:28 -08006520 mRootActivityContainer.getDefaultDisplayHomeActivity();
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006521 if (homeActivity != null) {
Wale Ogunwale8b19de92018-11-29 19:58:26 -08006522 activityOptions.setLaunchTaskId(homeActivity.getTaskRecord().taskId);
Martijn Coenen2a5c8392018-10-01 10:17:06 +02006523 }
Wale Ogunwale31913b52018-10-13 08:29:31 -07006524 mContext.startActivityAsUser(intent, activityOptions.toBundle(),
6525 UserHandle.CURRENT);
6526 } finally {
6527 Binder.restoreCallingIdentity(ident);
6528 }
6529 }
6530 }
6531
6532 @Override
6533 public void writeActivitiesToProto(ProtoOutputStream proto) {
6534 synchronized (mGlobalLock) {
6535 // The output proto of "activity --proto activities"
6536 // is ActivityManagerServiceDumpActivitiesProto
Wale Ogunwaled32da472018-11-16 07:19:28 -08006537 mRootActivityContainer.writeToProto(proto,
Wale Ogunwale31913b52018-10-13 08:29:31 -07006538 ActivityManagerServiceDumpActivitiesProto.ACTIVITY_STACK_SUPERVISOR);
6539 }
6540 }
6541
6542 @Override
6543 public void saveANRState(String reason) {
6544 synchronized (mGlobalLock) {
6545 final StringWriter sw = new StringWriter();
6546 final PrintWriter pw = new FastPrintWriter(sw, false, 1024);
6547 pw.println(" ANR time: " + DateFormat.getDateTimeInstance().format(new Date()));
6548 if (reason != null) {
6549 pw.println(" Reason: " + reason);
6550 }
6551 pw.println();
6552 getActivityStartController().dump(pw, " ", null);
6553 pw.println();
6554 pw.println("-------------------------------------------------------------------------------");
6555 dumpActivitiesLocked(null /* fd */, pw, null /* args */, 0 /* opti */,
6556 true /* dumpAll */, false /* dumpClient */, null /* dumpPackage */,
6557 "" /* header */);
6558 pw.println();
6559 pw.close();
6560
6561 mLastANRState = sw.toString();
6562 }
6563 }
6564
6565 @Override
6566 public void clearSavedANRState() {
6567 synchronized (mGlobalLock) {
6568 mLastANRState = null;
6569 }
6570 }
6571
6572 @Override
6573 public void dump(String cmd, FileDescriptor fd, PrintWriter pw, String[] args, int opti,
6574 boolean dumpAll, boolean dumpClient, String dumpPackage) {
6575 synchronized (mGlobalLock) {
6576 if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)) {
6577 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
6578 } else if (DUMP_LASTANR_CMD.equals(cmd)) {
6579 dumpLastANRLocked(pw);
6580 } else if (DUMP_LASTANR_TRACES_CMD.equals(cmd)) {
6581 dumpLastANRTracesLocked(pw);
6582 } else if (DUMP_STARTER_CMD.equals(cmd)) {
6583 dumpActivityStarterLocked(pw, dumpPackage);
6584 } else if (DUMP_CONTAINERS_CMD.equals(cmd)) {
6585 dumpActivityContainersLocked(pw);
6586 } else if (DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
6587 if (getRecentTasks() != null) {
6588 getRecentTasks().dump(pw, dumpAll, dumpPackage);
6589 }
6590 }
6591 }
6592 }
6593
6594 @Override
6595 public boolean dumpForProcesses(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
6596 String dumpPackage, int dumpAppId, boolean needSep, boolean testPssMode,
6597 int wakefulness) {
6598 synchronized (mGlobalLock) {
6599 if (mHomeProcess != null && (dumpPackage == null
6600 || mHomeProcess.mPkgList.contains(dumpPackage))) {
6601 if (needSep) {
6602 pw.println();
6603 needSep = false;
6604 }
6605 pw.println(" mHomeProcess: " + mHomeProcess);
6606 }
6607 if (mPreviousProcess != null && (dumpPackage == null
6608 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6609 if (needSep) {
6610 pw.println();
6611 needSep = false;
6612 }
6613 pw.println(" mPreviousProcess: " + mPreviousProcess);
6614 }
6615 if (dumpAll && (mPreviousProcess == null || dumpPackage == null
6616 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
6617 StringBuilder sb = new StringBuilder(128);
6618 sb.append(" mPreviousProcessVisibleTime: ");
6619 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
6620 pw.println(sb);
6621 }
6622 if (mHeavyWeightProcess != null && (dumpPackage == null
6623 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
6624 if (needSep) {
6625 pw.println();
6626 needSep = false;
6627 }
6628 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6629 }
6630 if (dumpPackage == null) {
6631 pw.println(" mGlobalConfiguration: " + getGlobalConfiguration());
Wale Ogunwaled32da472018-11-16 07:19:28 -08006632 mRootActivityContainer.dumpDisplayConfigs(pw, " ");
Wale Ogunwale31913b52018-10-13 08:29:31 -07006633 }
6634 if (dumpAll) {
6635 if (dumpPackage == null) {
6636 pw.println(" mConfigWillChange: "
6637 + getTopDisplayFocusedStack().mConfigWillChange);
6638 }
6639 if (mCompatModePackages.getPackages().size() > 0) {
6640 boolean printed = false;
6641 for (Map.Entry<String, Integer> entry
6642 : mCompatModePackages.getPackages().entrySet()) {
6643 String pkg = entry.getKey();
6644 int mode = entry.getValue();
6645 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
6646 continue;
6647 }
6648 if (!printed) {
6649 pw.println(" mScreenCompatPackages:");
6650 printed = true;
6651 }
6652 pw.println(" " + pkg + ": " + mode);
6653 }
6654 }
6655 }
6656
6657 if (dumpPackage == null) {
6658 pw.println(" mWakefulness="
6659 + PowerManagerInternal.wakefulnessToString(wakefulness));
Wale Ogunwaled32da472018-11-16 07:19:28 -08006660 pw.println(" mSleepTokens=" + mRootActivityContainer.mSleepTokens);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006661 if (mRunningVoice != null) {
6662 pw.println(" mRunningVoice=" + mRunningVoice);
6663 pw.println(" mVoiceWakeLock" + mVoiceWakeLock);
6664 }
6665 pw.println(" mSleeping=" + mSleeping);
6666 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + testPssMode);
6667 pw.println(" mVrController=" + mVrController);
6668 }
6669 if (mCurAppTimeTracker != null) {
6670 mCurAppTimeTracker.dumpWithHeader(pw, " ", true);
6671 }
6672 if (mAllowAppSwitchUids.size() > 0) {
6673 boolean printed = false;
6674 for (int i = 0; i < mAllowAppSwitchUids.size(); i++) {
6675 ArrayMap<String, Integer> types = mAllowAppSwitchUids.valueAt(i);
6676 for (int j = 0; j < types.size(); j++) {
6677 if (dumpPackage == null ||
6678 UserHandle.getAppId(types.valueAt(j).intValue()) == dumpAppId) {
6679 if (needSep) {
6680 pw.println();
6681 needSep = false;
6682 }
6683 if (!printed) {
6684 pw.println(" mAllowAppSwitchUids:");
6685 printed = true;
6686 }
6687 pw.print(" User ");
6688 pw.print(mAllowAppSwitchUids.keyAt(i));
6689 pw.print(": Type ");
6690 pw.print(types.keyAt(j));
6691 pw.print(" = ");
6692 UserHandle.formatUid(pw, types.valueAt(j).intValue());
6693 pw.println();
6694 }
6695 }
6696 }
6697 }
6698 if (dumpPackage == null) {
6699 if (mController != null) {
6700 pw.println(" mController=" + mController
6701 + " mControllerIsAMonkey=" + mControllerIsAMonkey);
6702 }
6703 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
6704 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
6705 }
6706
6707 return needSep;
6708 }
6709 }
6710
6711 @Override
sanryhuang498e77e2018-12-06 14:57:01 +08006712 public void writeProcessesToProto(ProtoOutputStream proto, String dumpPackage,
6713 int wakeFullness, boolean testPssMode) {
Wale Ogunwale31913b52018-10-13 08:29:31 -07006714 synchronized (mGlobalLock) {
6715 if (dumpPackage == null) {
6716 getGlobalConfiguration().writeToProto(proto, GLOBAL_CONFIGURATION);
6717 proto.write(CONFIG_WILL_CHANGE, getTopDisplayFocusedStack().mConfigWillChange);
sanryhuang498e77e2018-12-06 14:57:01 +08006718 writeSleepStateToProto(proto, wakeFullness, testPssMode);
6719 if (mRunningVoice != null) {
6720 final long vrToken = proto.start(
6721 ActivityManagerServiceDumpProcessesProto.RUNNING_VOICE);
6722 proto.write(ActivityManagerServiceDumpProcessesProto.Voice.SESSION,
6723 mRunningVoice.toString());
6724 mVoiceWakeLock.writeToProto(
6725 proto, ActivityManagerServiceDumpProcessesProto.Voice.WAKELOCK);
6726 proto.end(vrToken);
6727 }
6728 mVrController.writeToProto(proto,
6729 ActivityManagerServiceDumpProcessesProto.VR_CONTROLLER);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006730 if (mController != null) {
6731 final long token = proto.start(CONTROLLER);
6732 proto.write(CONTROLLER, mController.toString());
6733 proto.write(IS_A_MONKEY, mControllerIsAMonkey);
6734 proto.end(token);
6735 }
6736 mStackSupervisor.mGoingToSleep.writeToProto(proto, GOING_TO_SLEEP);
6737 mStackSupervisor.mLaunchingActivity.writeToProto(proto, LAUNCHING_ACTIVITY);
6738 }
6739
6740 if (mHomeProcess != null && (dumpPackage == null
6741 || mHomeProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006742 mHomeProcess.writeToProto(proto, HOME_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006743 }
6744
6745 if (mPreviousProcess != null && (dumpPackage == null
6746 || mPreviousProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006747 mPreviousProcess.writeToProto(proto, PREVIOUS_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006748 proto.write(PREVIOUS_PROC_VISIBLE_TIME_MS, mPreviousProcessVisibleTime);
6749 }
6750
6751 if (mHeavyWeightProcess != null && (dumpPackage == null
6752 || mHeavyWeightProcess.mPkgList.contains(dumpPackage))) {
Wale Ogunwale51cc98a2018-10-15 10:41:05 -07006753 mHeavyWeightProcess.writeToProto(proto, HEAVY_WEIGHT_PROC);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006754 }
6755
6756 for (Map.Entry<String, Integer> entry
6757 : mCompatModePackages.getPackages().entrySet()) {
6758 String pkg = entry.getKey();
6759 int mode = entry.getValue();
6760 if (dumpPackage == null || dumpPackage.equals(pkg)) {
6761 long compatToken = proto.start(SCREEN_COMPAT_PACKAGES);
6762 proto.write(PACKAGE, pkg);
6763 proto.write(MODE, mode);
6764 proto.end(compatToken);
6765 }
6766 }
6767
6768 if (mCurAppTimeTracker != null) {
6769 mCurAppTimeTracker.writeToProto(proto, CURRENT_TRACKER, true);
6770 }
6771
6772 }
6773 }
6774
6775 @Override
6776 public boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name,
6777 String[] args, int opti, boolean dumpAll, boolean dumpVisibleStacksOnly,
6778 boolean dumpFocusedStackOnly) {
6779 synchronized (mGlobalLock) {
6780 return ActivityTaskManagerService.this.dumpActivity(fd, pw, name, args, opti,
6781 dumpAll, dumpVisibleStacksOnly, dumpFocusedStackOnly);
6782 }
6783 }
6784
6785 @Override
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006786 public void dumpForOom(PrintWriter pw) {
6787 synchronized (mGlobalLock) {
6788 pw.println(" mHomeProcess: " + mHomeProcess);
6789 pw.println(" mPreviousProcess: " + mPreviousProcess);
6790 if (mHeavyWeightProcess != null) {
6791 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
6792 }
6793 }
6794 }
6795
6796 @Override
Wale Ogunwale31913b52018-10-13 08:29:31 -07006797 public boolean canGcNow() {
6798 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006799 return isSleeping() || mRootActivityContainer.allResumedActivitiesIdle();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006800 }
6801 }
6802
6803 @Override
6804 public WindowProcessController getTopApp() {
6805 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006806 final ActivityRecord top = mRootActivityContainer.getTopResumedActivity();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006807 return top != null ? top.app : null;
6808 }
6809 }
6810
6811 @Override
6812 public void rankTaskLayersIfNeeded() {
6813 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006814 if (mRootActivityContainer != null) {
6815 mRootActivityContainer.rankTaskLayersIfNeeded();
Wale Ogunwale31913b52018-10-13 08:29:31 -07006816 }
6817 }
6818 }
6819
6820 @Override
6821 public void scheduleDestroyAllActivities(String reason) {
6822 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006823 mRootActivityContainer.scheduleDestroyAllActivities(null, reason);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006824 }
6825 }
6826
6827 @Override
6828 public void removeUser(int userId) {
6829 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006830 mRootActivityContainer.removeUser(userId);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006831 }
6832 }
6833
6834 @Override
6835 public boolean switchUser(int userId, UserState userState) {
6836 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006837 return mRootActivityContainer.switchUser(userId, userState);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006838 }
6839 }
6840
6841 @Override
6842 public void onHandleAppCrash(WindowProcessController wpc) {
6843 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006844 mRootActivityContainer.handleAppCrash(wpc);
Wale Ogunwale31913b52018-10-13 08:29:31 -07006845 }
6846 }
Wale Ogunwale64258362018-10-16 15:13:37 -07006847
6848 @Override
6849 public int finishTopCrashedActivities(WindowProcessController crashedApp, String reason) {
6850 synchronized (mGlobalLock) {
Wale Ogunwaled32da472018-11-16 07:19:28 -08006851 return mRootActivityContainer.finishTopCrashedActivities(crashedApp, reason);
Wale Ogunwale64258362018-10-16 15:13:37 -07006852 }
6853 }
Wale Ogunwalebff2df42018-10-18 17:09:19 -07006854
6855 @Override
6856 public void onUidActive(int uid, int procState) {
6857 synchronized (mGlobalLock) {
6858 mActiveUids.put(uid, procState);
6859 }
6860 }
6861
6862 @Override
6863 public void onUidInactive(int uid) {
6864 synchronized (mGlobalLock) {
6865 mActiveUids.remove(uid);
6866 }
6867 }
6868
6869 @Override
6870 public void onActiveUidsCleared() {
6871 synchronized (mGlobalLock) {
6872 mActiveUids.clear();
6873 }
6874 }
6875
6876 @Override
6877 public void onUidProcStateChanged(int uid, int procState) {
6878 synchronized (mGlobalLock) {
6879 if (mActiveUids.get(uid) != null) {
6880 mActiveUids.put(uid, procState);
6881 }
6882 }
6883 }
Wale Ogunwale9de19442018-10-18 19:05:03 -07006884
6885 @Override
6886 public void onUidAddedToPendingTempWhitelist(int uid, String tag) {
6887 synchronized (mGlobalLock) {
6888 mPendingTempWhitelist.put(uid, tag);
6889 }
6890 }
6891
6892 @Override
6893 public void onUidRemovedFromPendingTempWhitelist(int uid) {
6894 synchronized (mGlobalLock) {
6895 mPendingTempWhitelist.remove(uid);
6896 }
6897 }
Wale Ogunwalee2172292018-10-25 10:11:10 -07006898
6899 @Override
6900 public boolean handleAppCrashInActivityController(String processName, int pid,
6901 String shortMsg, String longMsg, long timeMillis, String stackTrace,
6902 Runnable killCrashingAppCallback) {
6903 synchronized (mGlobalLock) {
6904 if (mController == null) {
6905 return false;
6906 }
6907
6908 try {
6909 if (!mController.appCrashed(processName, pid, shortMsg, longMsg, timeMillis,
6910 stackTrace)) {
6911 killCrashingAppCallback.run();
6912 return true;
6913 }
6914 } catch (RemoteException e) {
6915 mController = null;
6916 Watchdog.getInstance().setActivityController(null);
6917 }
6918 return false;
6919 }
6920 }
Wale Ogunwaled7889f52018-10-25 11:03:20 -07006921
6922 @Override
6923 public void removeRecentTasksByPackageName(String packageName, int userId) {
6924 synchronized (mGlobalLock) {
6925 mRecentTasks.removeTasksByPackageName(packageName, userId);
6926 }
6927 }
6928
6929 @Override
6930 public void cleanupRecentTasksForUser(int userId) {
6931 synchronized (mGlobalLock) {
6932 mRecentTasks.cleanupLocked(userId);
6933 }
6934 }
6935
6936 @Override
6937 public void loadRecentTasksForUser(int userId) {
6938 synchronized (mGlobalLock) {
6939 mRecentTasks.loadUserRecentsLocked(userId);
6940 }
6941 }
6942
6943 @Override
6944 public void onPackagesSuspendedChanged(String[] packages, boolean suspended, int userId) {
6945 synchronized (mGlobalLock) {
6946 mRecentTasks.onPackagesSuspendedChanged(packages, suspended, userId);
6947 }
6948 }
6949
6950 @Override
6951 public void flushRecentTasks() {
6952 mRecentTasks.flush();
6953 }
Wale Ogunwaled4d67d02018-10-25 18:09:39 -07006954
6955 @Override
6956 public WindowProcessController getHomeProcess() {
6957 synchronized (mGlobalLock) {
6958 return mHomeProcess;
6959 }
6960 }
6961
6962 @Override
6963 public WindowProcessController getPreviousProcess() {
6964 synchronized (mGlobalLock) {
6965 return mPreviousProcess;
6966 }
6967 }
Wale Ogunwale27c48ae2018-10-25 19:01:01 -07006968
6969 @Override
6970 public void clearLockedTasks(String reason) {
6971 synchronized (mGlobalLock) {
6972 getLockTaskController().clearLockedTasks(reason);
6973 }
6974 }
6975
6976 @Override
6977 public void updateUserConfiguration() {
6978 synchronized (mGlobalLock) {
6979 final Configuration configuration = new Configuration(getGlobalConfiguration());
6980 final int currentUserId = mAmInternal.getCurrentUserId();
6981 Settings.System.adjustConfigurationForUser(mContext.getContentResolver(),
6982 configuration, currentUserId, Settings.System.canWrite(mContext));
6983 updateConfigurationLocked(configuration, null /* starting */,
6984 false /* initLocale */, false /* persistent */, currentUserId,
6985 false /* deferResume */);
6986 }
6987 }
Wale Ogunwale387b34c2018-10-25 19:59:40 -07006988
6989 @Override
6990 public boolean canShowErrorDialogs() {
6991 synchronized (mGlobalLock) {
6992 return mShowDialogs && !mSleeping && !mShuttingDown
6993 && !mKeyguardController.isKeyguardOrAodShowing(DEFAULT_DISPLAY)
6994 && !hasUserRestriction(UserManager.DISALLOW_SYSTEM_ERROR_DIALOGS,
6995 mAmInternal.getCurrentUserId())
6996 && !(UserManager.isDeviceInDemoMode(mContext)
6997 && mAmInternal.getCurrentUser().isDemo());
6998 }
6999 }
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -08007000
7001 @Override
7002 public void setProfileApp(String profileApp) {
7003 synchronized (mGlobalLock) {
7004 mProfileApp = profileApp;
7005 }
7006 }
7007
7008 @Override
7009 public void setProfileProc(WindowProcessController wpc) {
7010 synchronized (mGlobalLock) {
7011 mProfileProc = wpc;
7012 }
7013 }
7014
7015 @Override
7016 public void setProfilerInfo(ProfilerInfo profilerInfo) {
7017 synchronized (mGlobalLock) {
7018 mProfilerInfo = profilerInfo;
7019 }
7020 }
Igor Murashkinc0b47e42018-11-07 15:54:18 -08007021
7022 @Override
7023 public ActivityMetricsLaunchObserverRegistry getLaunchObserverRegistry() {
7024 synchronized (mGlobalLock) {
7025 return mStackSupervisor.getActivityMetricsLogger().getLaunchObserverRegistry();
7026 }
7027 }
Winson Chung3fb0f252019-01-08 17:41:55 -08007028
7029 @Override
7030 public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
7031 synchronized (mGlobalLock) {
7032 return ActivityTaskManagerService.this.getTaskSnapshot(taskId, reducedResolution);
7033 }
7034 }
Wale Ogunwale6767eae2018-05-03 15:52:51 -07007035 }
Wale Ogunwaleb73f3962018-11-20 07:58:22 -08007036}