• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 
17 package com.android.cts.verifier.managedprovisioning;
18 
19 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
20 import static android.app.admin.DevicePolicyManager.MAKE_USER_EPHEMERAL;
21 import static android.app.admin.DevicePolicyManager.SKIP_SETUP_WIZARD;
22 
23 import static com.android.cts.verifier.Utils.flattenToShortString;
24 
25 import android.Manifest;
26 import android.app.Activity;
27 import android.app.ActivityManager;
28 import android.app.KeyguardManager;
29 import android.app.PendingIntent;
30 import android.app.admin.DevicePolicyManager;
31 import android.app.admin.WifiSsidPolicy;
32 import android.content.ComponentName;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.pm.ApplicationInfo;
37 import android.content.pm.PackageInstaller;
38 import android.content.pm.PackageManager;
39 import android.content.pm.ResolveInfo;
40 import android.graphics.BitmapFactory;
41 import android.net.ProxyInfo;
42 import android.net.wifi.WifiSsid;
43 import android.os.Bundle;
44 import android.os.PersistableBundle;
45 import android.os.UserHandle;
46 import android.os.UserManager;
47 import android.provider.ContactsContract;
48 import android.provider.MediaStore;
49 import android.provider.Settings;
50 import android.util.ArraySet;
51 import android.util.Log;
52 import android.view.inputmethod.InputMethodInfo;
53 import android.view.inputmethod.InputMethodManager;
54 import android.widget.Toast;
55 
56 import com.android.bedstead.dpmwrapper.TestAppSystemServiceFactory;
57 import com.android.cts.verifier.R;
58 
59 import java.io.File;
60 import java.io.FileInputStream;
61 import java.io.InputStream;
62 import java.io.OutputStream;
63 import java.nio.charset.StandardCharsets;
64 import java.util.ArrayList;
65 import java.util.Arrays;
66 import java.util.Collections;
67 import java.util.List;
68 import java.util.Set;
69 import java.util.concurrent.TimeUnit;
70 import java.util.stream.Collectors;
71 
72 public class CommandReceiverActivity extends Activity {
73     private static final String TAG = "CommandReceiverActivity";
74 
75     public static final String ACTION_EXECUTE_COMMAND =
76             "com.android.cts.verifier.managedprovisioning.action.EXECUTE_COMMAND";
77     public static final String EXTRA_COMMAND =
78             "com.android.cts.verifier.managedprovisioning.extra.COMMAND";
79 
80     public static final String COMMAND_SET_USER_RESTRICTION = "set-user_restriction";
81     public static final String COMMAND_DISALLOW_KEYGUARD_UNREDACTED_NOTIFICATIONS =
82             "disallow-keyguard-unredacted-notifications";
83     public static final String COMMAND_SET_AUTO_TIME_REQUIRED = "set-auto-time-required";
84     public static final String COMMAND_SET_GLOBAL_SETTING =
85             "set-global-setting";
86     public static final String COMMAND_SET_MAXIMUM_TO_LOCK = "set-maximum-time-to-lock";
87     public static final String COMMAND_SET_KEYGUARD_DISABLED = "set-keyguard-disabled";
88     public static final String COMMAND_SET_LOCK_SCREEN_INFO = "set-lock-screen-info";
89     public static final String COMMAND_SET_STATUSBAR_DISABLED = "set-statusbar-disabled";
90     public static final String COMMAND_SET_LOCK_TASK_FEATURES = "set-lock-task-features";
91     public static final String COMMAND_ALLOW_ONLY_SYSTEM_INPUT_METHODS =
92             "allow-only-system-input-methods";
93     public static final String COMMAND_ALLOW_ONLY_SYSTEM_ACCESSIBILITY_SERVICES =
94             "allow-only-system-accessibility-services";
95     public static final String COMMAND_CLEAR_POLICIES = "clear-policies";
96     public static final String COMMAND_REMOVE_DEVICE_OWNER = "remove-device-owner";
97     public static final String COMMAND_REQUEST_BUGREPORT = "request-bugreport";
98     public static final String COMMAND_SET_USER_ICON = "set-user-icon";
99     public static final String COMMAND_RETRIEVE_NETWORK_LOGS = "retrieve-network-logs";
100     public static final String COMMAND_RETRIEVE_SECURITY_LOGS = "retrieve-security-logs";
101     public static final String COMMAND_SET_ORGANIZATION_NAME = "set-organization-name";
102     public static final String COMMAND_ENABLE_NETWORK_LOGGING = "enable-network-logging";
103     public static final String COMMAND_DISABLE_NETWORK_LOGGING = "disable-network-logging";
104     public static final String COMMAND_INSTALL_HELPER_PACKAGE = "install-helper-package";
105     public static final String COMMAND_UNINSTALL_HELPER_PACKAGE = "uninstall-helper-package";
106     public static final String COMMAND_SET_PERMISSION_GRANT_STATE = "set-permission-grant-state";
107     public static final String COMMAND_ADD_PERSISTENT_PREFERRED_ACTIVITIES =
108             "add-persistent-preferred-activities";
109     public static final String COMMAND_CLEAR_PERSISTENT_PREFERRED_ACTIVITIES =
110             "clear-persistent-preferred-activities";
111     public static final String COMMAND_CREATE_MANAGED_PROFILE = "create-managed-profile";
112     public static final String COMMAND_REMOVE_MANAGED_PROFILE = "remove-managed-profile";
113     public static final String COMMAND_SET_ALWAYS_ON_VPN = "set-always-on-vpn";
114     public static final String COMMAND_CLEAR_ALWAYS_ON_VPN = "clear-always-on-vpn";
115     public static final String COMMAND_SET_GLOBAL_HTTP_PROXY = "set-global-http-proxy";
116     public static final String COMMAND_CLEAR_GLOBAL_HTTP_PROXY = "clear-global-http-proxy";
117     public static final String COMMAND_INSTALL_CA_CERT = "install-ca-cert";
118     public static final String COMMAND_CLEAR_CA_CERT = "clear-ca-cert";
119     public static final String COMMAND_SET_MAXIMUM_PASSWORD_ATTEMPTS =
120             "set-maximum-password-attempts";
121     public static final String COMMAND_CLEAR_MAXIMUM_PASSWORD_ATTEMPTS =
122             "clear-maximum-password-attempts";
123     public static final String COMMAND_SET_DEFAULT_IME = "set-default-ime";
124     public static final String COMMAND_CLEAR_DEFAULT_IME = "clear-default-ime";
125     public static final String COMMAND_CREATE_MANAGED_USER = "create-managed-user";
126     public static final String COMMAND_CREATE_MANAGED_USER_WITHOUT_SETUP =
127             "create-managed-user-without-setup";
128     public static final String COMMAND_REMOVE_SECONDARY_USERS = "remove-secondary-users";
129     public static final String COMMAND_WITH_USER_SWITCHER_MESSAGE = "with-user-switcher-message";
130     public static final String COMMAND_WITHOUT_USER_SWITCHER_MESSAGE =
131             "without-user-switcher-message";
132     public static final String COMMAND_ENABLE_LOGOUT = "enable-logout";
133     public static final String COMMAND_DISABLE_USB_DATA_SIGNALING = "disable-usb-data-signaling";
134     public static final String COMMAND_ENABLE_USB_DATA_SIGNALING = "enable-usb-data-signaling";
135     public static final String COMMAND_SET_REQUIRED_PASSWORD_COMPLEXITY =
136             "set-required-password-complexity";
137     public static final String COMMAND_SET_WIFI_SECURITY_LEVEL = "set-wifi-security-level";
138     public static final String COMMAND_SET_SSID_ALLOWLIST = "set-ssid-allowlist";
139     public static final String COMMAND_SET_SSID_DENYLIST = "set-ssid-denylist";
140     public static final String COMMAND_CHECK_NEW_USER_DISCLAIMER = "check-new-user-disclaimer";
141 
142     public static final String EXTRA_USER_RESTRICTION =
143             "com.android.cts.verifier.managedprovisioning.extra.USER_RESTRICTION";
144     public static final String EXTRA_USE_CURRENT_USER_DPM =
145             "com.android.cts.verifier.managedprovisioning.extra.USE_CURRENT_USER_DPM";
146     public static final String EXTRA_SETTING =
147             "com.android.cts.verifier.managedprovisioning.extra.SETTING";
148     // This extra can be used along with a command extra to set policy to
149     // specify if that policy is enforced or not.
150     public static final String EXTRA_ENFORCED =
151             "com.android.cts.verifier.managedprovisioning.extra.ENFORCED";
152     public static final String EXTRA_VALUE =
153             "com.android.cts.verifier.managedprovisioning.extra.VALUE";
154     public static final String EXTRA_ORGANIZATION_NAME =
155             "com.android.cts.verifier.managedprovisioning.extra.ORGANIZATION_NAME";
156     public static final String EXTRA_PERMISSION =
157             "com.android.cts.verifier.managedprovisioning.extra.PERMISSION";
158     public static final String EXTRA_GRANT_STATE =
159             "com.android.cts.verifier.managedprovisioning.extra.GRANT_STATE";
160 
161     // We care about installing and uninstalling only. It does not matter what apk is used.
162     // NotificationBot.apk is a good choice because it comes bundled with the CTS verifier.
163     protected static final String HELPER_APP_LOCATION = "/sdcard/NotificationBot.apk";
164     protected static final String HELPER_APP_PKG = "com.android.cts.robot";
165 
166     public static final String ACTION_INSTALL_COMPLETE =
167             "com.android.cts.verifier.managedprovisioning.action.ACTION_INSTALL_COMPLETE";
168     public static final String ACTION_UNINSTALL_COMPLETE =
169             "com.android.cts.verifier.managedprovisioning.action.ACTION_UNINSTALL_COMPLETE";
170 
171     /*
172      * The CA cert below is the content of cacert.pem as generated by:
173      *
174      * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
175      */
176     private static final String TEST_CA =
177             "-----BEGIN CERTIFICATE-----\n" +
178             "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
179             "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
180             "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
181             "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
182             "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
183             "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
184             "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
185             "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
186             "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
187             "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
188             "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
189             "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
190             "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
191             "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
192             "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
193             "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
194             "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
195             "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
196             "wQ==\n" +
197             "-----END CERTIFICATE-----";
198 
199     private ComponentName mAdmin;
200     private DevicePolicyManager mDpm;
201     private UserManager mUm;
202     private ActivityManager mAm;
203 
204     @Override
onCreate(Bundle savedInstanceState)205     public void onCreate(Bundle savedInstanceState) {
206         super.onCreate(savedInstanceState);
207         final Intent intent = getIntent();
208         try {
209             // On phones, the test runs on user 0, which is the Device Owner, but on headless system
210             // user mode it runs in a different user.
211             // Most DPM operations must be set on device owner user, but a few - like adding user
212             // restrictions - must be set in the current user.
213             boolean forDeviceOwner = !intent.getBooleanExtra(EXTRA_USE_CURRENT_USER_DPM, false);
214             mDpm = TestAppSystemServiceFactory.getDevicePolicyManager(this,
215                             DeviceAdminTestReceiver.class, forDeviceOwner);
216 
217             mUm = getSystemService(UserManager.class);
218             mAm = getSystemService(ActivityManager.class);
219             mAdmin = DeviceAdminTestReceiver.getReceiverComponentName();
220             final String command = intent.getStringExtra(EXTRA_COMMAND);
221             Log.i(TAG, "Command: " + command + " forDeviceOwner: " + forDeviceOwner);
222             switch (command) {
223                 case COMMAND_SET_USER_RESTRICTION: {
224                     String restrictionKey = intent.getStringExtra(EXTRA_USER_RESTRICTION);
225                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
226                     Log.i(TAG, "Setting '" + restrictionKey + "'=" + enforced
227                             + " using " + mDpm + " for user "
228                             + (forDeviceOwner ? UserHandle.SYSTEM : UserHandle.myUserId()));
229                     if (enforced) {
230                         mDpm.addUserRestriction(mAdmin, restrictionKey);
231                     } else {
232                         mDpm.clearUserRestriction(mAdmin, restrictionKey);
233                     }
234                 } break;
235                 case COMMAND_DISALLOW_KEYGUARD_UNREDACTED_NOTIFICATIONS: {
236                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
237                     mDpm.setKeyguardDisabledFeatures(mAdmin, enforced
238                             ? DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS
239                             : 0);
240                 } break;
241                 case COMMAND_SET_AUTO_TIME_REQUIRED: {
242                     mDpm.setAutoTimeRequired(mAdmin,
243                             intent.getBooleanExtra(EXTRA_ENFORCED, false));
244                     break;
245                 }
246                 case COMMAND_SET_LOCK_SCREEN_INFO: {
247                     mDpm.setDeviceOwnerLockScreenInfo(mAdmin, intent.getStringExtra(EXTRA_VALUE));
248                     break;
249                 }
250                 case COMMAND_SET_MAXIMUM_TO_LOCK: {
251                     final long timeInSeconds = Long.parseLong(intent.getStringExtra(EXTRA_VALUE));
252                     mDpm.setMaximumTimeToLock(mAdmin,
253                             TimeUnit.SECONDS.toMillis(timeInSeconds) /* in milliseconds */);
254                 } break;
255                 case COMMAND_SET_KEYGUARD_DISABLED: {
256                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
257                     KeyguardManager km = this.getSystemService(KeyguardManager.class);
258                     if (km.isKeyguardSecure()) {
259                         Toast.makeText(this, getString(R.string.device_owner_lockscreen_secure),
260                                 Toast.LENGTH_SHORT).show();
261                     } else {
262                         mDpm.setKeyguardDisabled(mAdmin, enforced);
263                     }
264                 } break;
265                 case COMMAND_SET_STATUSBAR_DISABLED: {
266                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
267                     Log.d(TAG, "calling setStatusBarDisabled(" + flattenToShortString(mAdmin)
268                             + ", " + enforced + ") using " + mDpm + " on user "
269                             + UserHandle.myUserId());
270                     mDpm.setStatusBarDisabled(mAdmin, enforced);
271                 } break;
272                 case COMMAND_SET_LOCK_TASK_FEATURES: {
273                     int flags = intent.getIntExtra(EXTRA_VALUE,
274                             DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
275                     mDpm.setLockTaskFeatures(mAdmin, flags);
276                     // If feature HOME is used, we need to allow the current launcher
277                     if ((flags & LOCK_TASK_FEATURE_HOME) != 0) {
278                         mDpm.setLockTaskPackages(mAdmin,
279                                 new String[] {getPackageName(), getCurrentLauncherPackage()});
280                     } else {
281                         mDpm.setLockTaskPackages(mAdmin, new String[] {getPackageName()});
282                     }
283                 } break;
284                 case COMMAND_ALLOW_ONLY_SYSTEM_INPUT_METHODS: {
285                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
286                     mDpm.setPermittedInputMethods(mAdmin,
287                             enforced ? getEnabledNonSystemImes() : null);
288                 } break;
289                 case COMMAND_ALLOW_ONLY_SYSTEM_ACCESSIBILITY_SERVICES: {
290                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
291                     mDpm.setPermittedAccessibilityServices(mAdmin,
292                             enforced ? new ArrayList() : null);
293                 } break;
294                 case COMMAND_SET_GLOBAL_SETTING: {
295                     final String setting = intent.getStringExtra(EXTRA_SETTING);
296                     final String value = intent.getStringExtra(EXTRA_VALUE);
297                     Log.d(TAG, "Setting global property '" + setting + "' to '" + value
298                             + "' using " + mDpm);
299                     mDpm.setGlobalSetting(mAdmin, setting, value);
300                 } break;
301                 case COMMAND_REMOVE_DEVICE_OWNER: {
302                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
303                         Log.e(TAG, COMMAND_REMOVE_DEVICE_OWNER + ": " + getPackageName()
304                                 + " is not DO for user " + UserHandle.myUserId());
305                         return;
306                     }
307                     clearAllPoliciesAndRestrictions();
308                     Log.i(TAG, "Clearing device owner app " + getPackageName());
309                     mDpm.clearDeviceOwnerApp(getPackageName());
310 
311                     if (UserManager.isHeadlessSystemUserMode()) {
312                         Log.i(TAG, "Clearing profile owner app (" + mAdmin.flattenToString()
313                                 + " on user " + UserHandle.myUserId());
314                         DevicePolicyManager localDpm = getSystemService(DevicePolicyManager.class);
315                         localDpm.clearProfileOwner(mAdmin);
316                     }
317 
318                 } break;
319                 case COMMAND_REQUEST_BUGREPORT: {
320                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
321                         return;
322                     }
323                     final boolean bugreportStarted = mDpm.requestBugreport(mAdmin);
324                     if (!bugreportStarted) {
325                         Utils.showBugreportNotification(this, getString(
326                                 R.string.bugreport_already_in_progress),
327                                 Utils.BUGREPORT_NOTIFICATION_ID);
328                     }
329                 } break;
330                 case COMMAND_CLEAR_POLICIES: {
331                     int mode = intent.getIntExtra(PolicyTransparencyTestListActivity.EXTRA_MODE,
332                             PolicyTransparencyTestListActivity.MODE_DEVICE_OWNER);
333                     if (mode == PolicyTransparencyTestListActivity.MODE_DEVICE_OWNER) {
334                         if (!mDpm.isDeviceOwnerApp(getPackageName())) {
335                             return;
336                         }
337                         clearAllPoliciesAndRestrictions();
338                     } else if (mode == PolicyTransparencyTestListActivity.MODE_MANAGED_PROFILE
339                             || mode == PolicyTransparencyTestListActivity.MODE_MANAGED_USER) {
340                         if (!mDpm.isProfileOwnerApp(getPackageName())) {
341                             return;
342                         }
343                         clearProfileOwnerRelatedPoliciesAndRestrictions(mode);
344                     }
345                     // No policies need to be cleared for COMP at the moment.
346                 } break;
347                 case COMMAND_SET_USER_ICON: {
348                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
349                         return;
350                     }
351                     int iconRes = intent.getIntExtra(EXTRA_VALUE,
352                             com.android.cts.verifier.R.drawable.icon);
353                     mDpm.setUserIcon(mAdmin, BitmapFactory.decodeResource(getResources(), iconRes));
354                 } break;
355                 case COMMAND_RETRIEVE_NETWORK_LOGS: {
356                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
357                         return;
358                     }
359                     mDpm.setNetworkLoggingEnabled(mAdmin, true);
360                     mDpm.retrieveNetworkLogs(mAdmin, 0 /* batchToken */);
361                     mDpm.setNetworkLoggingEnabled(mAdmin, false);
362                 } break;
363                 case COMMAND_RETRIEVE_SECURITY_LOGS: {
364                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
365                         return;
366                     }
367                     mDpm.setSecurityLoggingEnabled(mAdmin, true);
368                     mDpm.retrieveSecurityLogs(mAdmin);
369                     mDpm.setSecurityLoggingEnabled(mAdmin, false);
370                 } break;
371                 case COMMAND_SET_ORGANIZATION_NAME: {
372                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
373                         return;
374                     }
375                     mDpm.setOrganizationName(mAdmin,
376                             intent.getStringExtra(EXTRA_ORGANIZATION_NAME));
377                 } break;
378                 case COMMAND_ENABLE_NETWORK_LOGGING: {
379                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
380                         return;
381                     }
382                     mDpm.setNetworkLoggingEnabled(mAdmin, true);
383                 } break;
384                 case COMMAND_DISABLE_NETWORK_LOGGING: {
385                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
386                         return;
387                     }
388                     mDpm.setNetworkLoggingEnabled(mAdmin, false);
389                 } break;
390                 case COMMAND_INSTALL_HELPER_PACKAGE: {
391                     installHelperPackage();
392                 } break;
393                 case COMMAND_UNINSTALL_HELPER_PACKAGE: {
394                     uninstallHelperPackage();
395                 } break;
396                 case COMMAND_SET_PERMISSION_GRANT_STATE: {
397                     String pkgName = getPackageName();
398                     String permission = intent.getStringExtra(EXTRA_PERMISSION);
399                     int grantState = intent.getIntExtra(EXTRA_GRANT_STATE,
400                             DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
401                     String action;
402                     switch (grantState) {
403                         case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED:
404                             action = "Granting " + permission;
405                             break;
406                         case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED:
407                             action = "Denying " + permission;
408                             break;
409                         case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT:
410                             action = "Setting " + permission + " to default state";
411                             break;
412                         default:
413                             action = "Setting grantState of " + permission + " to " + grantState;
414                     }
415                     Log.d(TAG, action + " to " + pkgName + " using " + mDpm);
416                     int stateBefore = mDpm.getPermissionGrantState(mAdmin, pkgName, permission);
417                     mDpm.setPermissionGrantState(mAdmin, pkgName, permission, grantState);
418                     int stateAfter = mDpm.getPermissionGrantState(mAdmin, pkgName, permission);
419                     Log.d(TAG, "Grant state: before=" + stateBefore + ", after=" + stateAfter);
420                 } break;
421                 case COMMAND_ADD_PERSISTENT_PREFERRED_ACTIVITIES: {
422                     final ComponentName componentName =
423                             EnterprisePrivacyTestDefaultAppActivity.COMPONENT_NAME;
424                     IntentFilter filter;
425                     // Camera
426                     filter = new IntentFilter();
427                     filter.addAction(MediaStore.ACTION_IMAGE_CAPTURE);
428                     filter.addAction(MediaStore.ACTION_VIDEO_CAPTURE);
429                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
430                     // Map
431                     filter = new IntentFilter();
432                     filter.addAction(Intent.ACTION_VIEW);
433                     filter.addDataScheme("geo");
434                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
435                     // E-mail
436                     filter = new IntentFilter();
437                     filter.addAction(Intent.ACTION_SENDTO);
438                     filter.addAction(Intent.ACTION_SEND);
439                     filter.addAction(Intent.ACTION_SEND_MULTIPLE);
440                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
441                     // Calendar
442                     filter = new IntentFilter();
443                     filter.addAction(Intent.ACTION_INSERT);
444                     filter.addDataType("vnd.android.cursor.dir/event");
445                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
446                     // Contacts
447                     filter = new IntentFilter();
448                     filter.addAction(Intent.ACTION_PICK);
449                     filter.addDataType(ContactsContract.Contacts.CONTENT_TYPE);
450                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
451                     // Dialer
452                     filter = new IntentFilter();
453                     filter.addAction(Intent.ACTION_DIAL);
454                     filter.addAction(Intent.ACTION_CALL);
455                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
456                     getPackageManager().setComponentEnabledSetting(componentName,
457                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
458                             PackageManager.DONT_KILL_APP);
459                 } break;
460                 case COMMAND_CLEAR_PERSISTENT_PREFERRED_ACTIVITIES: {
461                     mDpm.clearPackagePersistentPreferredActivities(mAdmin, getPackageName());
462                     getPackageManager().setComponentEnabledSetting(
463                             EnterprisePrivacyTestDefaultAppActivity.COMPONENT_NAME,
464                             PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
465                             PackageManager.DONT_KILL_APP);
466                 } break;
467                 case COMMAND_SET_ALWAYS_ON_VPN: {
468                     if (!isDeviceOwnerAppOrEquivalent(getPackageName())) {
469                         return;
470                     }
471                     mDpm.setAlwaysOnVpnPackage(mAdmin, getPackageName(),
472                             false /* lockdownEnabled */);
473                 } break;
474                 case COMMAND_CLEAR_ALWAYS_ON_VPN: {
475                     if (!isDeviceOwnerAppOrEquivalent(getPackageName())) {
476                         return;
477                     }
478                     mDpm.setAlwaysOnVpnPackage(mAdmin, null /* vpnPackage */,
479                             false /* lockdownEnabled */);
480                 } break;
481                 case COMMAND_SET_GLOBAL_HTTP_PROXY: {
482                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
483                         return;
484                     }
485                     mDpm.setRecommendedGlobalProxy(mAdmin,
486                             ProxyInfo.buildDirectProxy("example.com", 123));
487                 } break;
488                 case COMMAND_CLEAR_GLOBAL_HTTP_PROXY: {
489                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
490                         return;
491                     }
492                     mDpm.setRecommendedGlobalProxy(mAdmin, null);
493                 } break;
494                 case COMMAND_INSTALL_CA_CERT: {
495                     if (!isDeviceOwnerAppOrEquivalent(getPackageName())) {
496                         return;
497                     }
498                     mDpm.installCaCert(mAdmin, TEST_CA.getBytes());
499                 } break;
500                 case COMMAND_CLEAR_CA_CERT: {
501                     if (!isDeviceOwnerAppOrEquivalent(getPackageName())) {
502                         return;
503                     }
504                     mDpm.uninstallCaCert(mAdmin, TEST_CA.getBytes());
505                 } break;
506                 case COMMAND_SET_MAXIMUM_PASSWORD_ATTEMPTS: {
507                     if (!isDeviceOwner()) return;
508                     int max = 100;
509                     Log.d(TAG, "Setting maximum password attempts to " + max + " using" + mDpm);
510                     mDpm.setMaximumFailedPasswordsForWipe(mAdmin, max);
511                 } break;
512                 case COMMAND_CLEAR_MAXIMUM_PASSWORD_ATTEMPTS: {
513                     if (!isDeviceOwner()) return;
514                     Log.d(TAG, "Clearing maximum password attempts using" + mDpm);
515                     mDpm.setMaximumFailedPasswordsForWipe(mAdmin, 0);
516                 } break;
517                 case COMMAND_SET_DEFAULT_IME: {
518                     if (!isDeviceOwner()) return;
519                     Log.d(TAG, "Setting " + Settings.Secure.DEFAULT_INPUT_METHOD + " using "
520                             + mDpm);
521                     mDpm.setSecureSetting(mAdmin, Settings.Secure.DEFAULT_INPUT_METHOD,
522                             getPackageName());
523                 } break;
524                 case COMMAND_CLEAR_DEFAULT_IME: {
525                     if (!isDeviceOwner()) return;
526                     Log.d(TAG, "Clearing " + Settings.Secure.DEFAULT_INPUT_METHOD + " using "
527                             + mDpm);
528                     mDpm.setSecureSetting(mAdmin, Settings.Secure.DEFAULT_INPUT_METHOD, null);
529                 } break;
530                 case COMMAND_CREATE_MANAGED_USER:{
531                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
532                         return;
533                     }
534                     PersistableBundle extras = new PersistableBundle();
535                     extras.putBoolean(DeviceAdminTestReceiver.EXTRA_MANAGED_USER_TEST, true);
536                     UserHandle userHandle = mDpm.createAndManageUser(mAdmin, "managed user", mAdmin,
537                             extras,
538                             SKIP_SETUP_WIZARD | MAKE_USER_EPHEMERAL);
539                     Log.i(TAG, "Created user " + userHandle + "; setting affiliation ids to "
540                             + DeviceAdminTestReceiver.AFFILIATION_ID);
541                     mDpm.setAffiliationIds(mAdmin,
542                             Collections.singleton(DeviceAdminTestReceiver.AFFILIATION_ID));
543                     // TODO(b/204483021): move to helper class / restore after user is logged out
544                     if (UserManager.isHeadlessSystemUserMode()) {
545                         mAm.setStopUserOnSwitch(ActivityManager.STOP_USER_ON_SWITCH_FALSE);
546                     }
547                     Log.d(TAG, "Starting user " + userHandle);
548                     mDpm.startUserInBackground(mAdmin, userHandle);
549                 } break;
550                 case COMMAND_CREATE_MANAGED_USER_WITHOUT_SETUP:{
551                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
552                         return;
553                     }
554                     PersistableBundle extras = new PersistableBundle();
555                     extras.putBoolean(DeviceAdminTestReceiver.EXTRA_MANAGED_USER_TEST, true);
556                     mDpm.createAndManageUser(mAdmin, "managed user", mAdmin, extras, /* flags */ 0);
557                 } break;
558                 case COMMAND_REMOVE_SECONDARY_USERS: {
559                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
560                         return;
561                     }
562                     for (UserHandle secondaryUser : mDpm.getSecondaryUsers(mAdmin)) {
563                         mDpm.removeUser(mAdmin, secondaryUser);
564                     }
565                 } break;
566                 case COMMAND_WITH_USER_SWITCHER_MESSAGE: {
567                     createAndSwitchUserWithMessage("Start user session", "End user session");
568                 } break;
569                 case COMMAND_WITHOUT_USER_SWITCHER_MESSAGE: {
570                     createAndSwitchUserWithMessage(null, null);
571                 } break;
572                 case COMMAND_ENABLE_LOGOUT: {
573                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
574                         return;
575                     }
576                     mDpm.addUserRestriction(mAdmin, UserManager.DISALLOW_USER_SWITCH);
577                     mDpm.setLogoutEnabled(mAdmin, true);
578                     UserHandle userHandle = mDpm.createAndManageUser(mAdmin, "managed user", mAdmin,
579                             null, SKIP_SETUP_WIZARD | MAKE_USER_EPHEMERAL);
580                     mDpm.switchUser(mAdmin, userHandle);
581                 } break;
582                 case COMMAND_DISABLE_USB_DATA_SIGNALING: {
583                     mDpm.setUsbDataSignalingEnabled(false);
584                     break;
585                 }
586                 case COMMAND_ENABLE_USB_DATA_SIGNALING: {
587                     mDpm.setUsbDataSignalingEnabled(true);
588                     break;
589                 }
590                 case COMMAND_SET_REQUIRED_PASSWORD_COMPLEXITY: {
591                     int complexity = intent.getIntExtra(EXTRA_VALUE,
592                             DevicePolicyManager.PASSWORD_COMPLEXITY_NONE);
593                     Log.d(TAG, "calling setRequiredPasswordComplexity(" + complexity + ")");
594                     mDpm.setRequiredPasswordComplexity(complexity);
595                 } break;
596                 case COMMAND_SET_WIFI_SECURITY_LEVEL: {
597                     int level = intent.getIntExtra(EXTRA_VALUE,
598                             DevicePolicyManager.WIFI_SECURITY_OPEN);
599                     Log.d(TAG, "calling setWifiSecurityLevel(" + level + ")");
600                     mDpm.setMinimumRequiredWifiSecurityLevel(level);
601                 } break;
602                 case COMMAND_SET_SSID_ALLOWLIST: {
603                     String ssid = intent.getStringExtra(EXTRA_VALUE);
604                     WifiSsidPolicy policy;
605                     if (ssid.isEmpty()) {
606                         policy = null;
607                     } else {
608                         Set<WifiSsid> ssids = new ArraySet<>(Arrays.asList(
609                                 WifiSsid.fromBytes(ssid.getBytes(StandardCharsets.UTF_8))));
610                         policy = new WifiSsidPolicy(
611                                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, ssids);
612                     }
613                     mDpm.setWifiSsidPolicy(policy);
614                 } break;
615                 case COMMAND_SET_SSID_DENYLIST: {
616                     String ssid = intent.getStringExtra(EXTRA_VALUE);
617                     WifiSsidPolicy policy;
618                     if (ssid.isEmpty()) {
619                         policy = null;
620                     } else {
621                         Set<WifiSsid> ssids = new ArraySet<>(Arrays.asList(
622                                 WifiSsid.fromBytes(ssid.getBytes(StandardCharsets.UTF_8))));
623                         policy = new WifiSsidPolicy(
624                                 WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST, ssids);
625                     }
626                     mDpm.setWifiSsidPolicy(policy);
627                 } break;
628             }
629         } catch (Exception e) {
630             Log.e(TAG, "Failed to execute command: " + intent, e);
631         } finally {
632             finish();
633         }
634     }
635 
636     /**
637      * Checks if {@code CtsVerifier} is the device owner.
638      */
isDeviceOwner()639     private boolean isDeviceOwner() {
640         // Cannot use mDpm as it would be the DPM of the current user on headless system user mode,
641         // which would return false
642         DevicePolicyManager dpm = TestAppSystemServiceFactory.getDevicePolicyManager(this,
643                 DeviceAdminTestReceiver.class, /* forDeviceOwner= */ true);
644         boolean isIt = dpm.isDeviceOwnerApp(getPackageName());
645         Log.v(TAG, "is " + getPackageName() + " DO, using " + dpm + "? " + isIt);
646         return isIt;
647     }
648 
649     /**
650      * Checks if the {@code packageName} is a device owner app, or a profile owner app in the
651      * headless system user mode.
652       */
isDeviceOwnerAppOrEquivalent(String packageName)653     private boolean isDeviceOwnerAppOrEquivalent(String packageName) {
654         return mDpm.isDeviceOwnerApp(packageName)
655                 || (UserManager.isHeadlessSystemUserMode() && mDpm.isProfileOwnerApp(packageName));
656     }
657 
installHelperPackage()658     private void installHelperPackage() throws Exception {
659         if (UserManager.isHeadlessSystemUserMode()) {
660             // App was already installed on user 0 (as instructed), so we just install it for the
661             // current user - installing directly to current user would be harder as it would
662             // require a custom ContentProvider to push the APK into a secondary user using adb
663             Log.i(TAG, "installing existing helper app (" + HELPER_APP_PKG + ") using " + mDpm);
664             mDpm.installExistingPackage(mAdmin, HELPER_APP_PKG);
665             return;
666         }
667         LogAndSelfUnregisterBroadcastReceiver.register(this, ACTION_INSTALL_COMPLETE);
668         final PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();
669         final PackageInstaller.Session session = packageInstaller.openSession(
670                 packageInstaller.createSession(new PackageInstaller.SessionParams(
671                         PackageInstaller.SessionParams.MODE_FULL_INSTALL)));
672         final File file = new File(HELPER_APP_LOCATION);
673         Log.i(TAG, "installing helper package from " + file);
674         final InputStream in = new FileInputStream(file);
675         final OutputStream out = session.openWrite("CommandReceiverActivity", 0, file.length());
676         final byte[] buffer = new byte[65536];
677         int count;
678         while ((count = in.read(buffer)) != -1) {
679             out.write(buffer, 0, count);
680         }
681         session.fsync(out);
682         in.close();
683         out.close();
684         session.commit(PendingIntent
685                 .getBroadcast(this, 0, new Intent(ACTION_INSTALL_COMPLETE),
686                         PendingIntent.FLAG_MUTABLE_UNAUDITED)
687                 .getIntentSender());
688     }
689 
uninstallHelperPackage()690     private void uninstallHelperPackage() {
691         LogAndSelfUnregisterBroadcastReceiver.register(this, ACTION_UNINSTALL_COMPLETE);
692         PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();
693         Log.i(TAG, "Uninstalling package " + HELPER_APP_PKG + " using " + packageInstaller);
694         try {
695             packageInstaller.uninstall(HELPER_APP_PKG, PendingIntent.getBroadcast(this,
696                     /* requestCode= */ 0, new Intent(ACTION_UNINSTALL_COMPLETE),
697                     PendingIntent.FLAG_MUTABLE_UNAUDITED).getIntentSender());
698         } catch (IllegalArgumentException e) {
699             // The package is not installed: that's fine
700         }
701     }
702 
clearAllPoliciesAndRestrictions()703     private void clearAllPoliciesAndRestrictions() throws Exception {
704         Log.d(TAG, "clearAllPoliciesAndRestrictions() started");
705         clearProfileOwnerRelatedPolicies();
706         clearPolicyTransparencyUserRestriction(
707                 PolicyTransparencyTestListActivity.MODE_DEVICE_OWNER);
708 
709         // There are a few user restrictions that are used, but not for policy transparency
710         mDpm.clearUserRestriction(mAdmin, UserManager.DISALLOW_CONFIG_BLUETOOTH);
711         mDpm.clearUserRestriction(mAdmin, UserManager.DISALLOW_CONFIG_VPN);
712         mDpm.clearUserRestriction(mAdmin, UserManager.DISALLOW_DATA_ROAMING);
713         mDpm.clearUserRestriction(mAdmin, UserManager.DISALLOW_USER_SWITCH);
714 
715         mDpm.setDeviceOwnerLockScreenInfo(mAdmin, null);
716         mDpm.setKeyguardDisabled(mAdmin, false);
717         mDpm.setAutoTimeRequired(mAdmin, false);
718         mDpm.setStatusBarDisabled(mAdmin, false);
719         mDpm.setOrganizationName(mAdmin, null);
720         mDpm.setNetworkLoggingEnabled(mAdmin, false);
721         mDpm.setSecurityLoggingEnabled(mAdmin, false);
722         mDpm.setPermissionGrantState(mAdmin, getPackageName(),
723                 Manifest.permission.ACCESS_FINE_LOCATION,
724                 DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
725         mDpm.setPermissionGrantState(mAdmin, getPackageName(), Manifest.permission.RECORD_AUDIO,
726                 DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
727         mDpm.setPermissionGrantState(mAdmin, getPackageName(), Manifest.permission.CAMERA,
728                 DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
729         mDpm.clearPackagePersistentPreferredActivities(mAdmin, getPackageName());
730         mDpm.setAlwaysOnVpnPackage(mAdmin, null, false);
731         mDpm.setRecommendedGlobalProxy(mAdmin, null);
732         mDpm.uninstallCaCert(mAdmin, TEST_CA.getBytes());
733         mDpm.setMaximumFailedPasswordsForWipe(mAdmin, 0);
734         mDpm.setSecureSetting(mAdmin, Settings.Secure.DEFAULT_INPUT_METHOD, null);
735         mDpm.setStartUserSessionMessage(mAdmin, null);
736         mDpm.setEndUserSessionMessage(mAdmin, null);
737         mDpm.setLogoutEnabled(mAdmin, false);
738 
739         uninstallHelperPackage();
740 
741         // Must wait until package is uninstalled to reset affiliation ids, otherwise the package
742         // cannot be removed on headless system user mode (as caller must be an affiliated PO)
743         Log.d(TAG, "resetting affiliation ids");
744         mDpm.setAffiliationIds(mAdmin, Collections.emptySet());
745 
746         removeManagedProfile();
747         getPackageManager().setComponentEnabledSetting(
748                 EnterprisePrivacyTestDefaultAppActivity.COMPONENT_NAME,
749                 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
750                 PackageManager.DONT_KILL_APP);
751         Log.d(TAG, "clearAllPoliciesAndRestrictions() finished");
752     }
753 
clearProfileOwnerRelatedPoliciesAndRestrictions(int mode)754     private void clearProfileOwnerRelatedPoliciesAndRestrictions(int mode) {
755         clearPolicyTransparencyUserRestriction(mode);
756         clearProfileOwnerRelatedPolicies();
757     }
758 
clearProfileOwnerRelatedPolicies()759     private void clearProfileOwnerRelatedPolicies() {
760         Log.d(TAG, "clearProfileOwnerRelatedPolicies() started");
761         mDpm.setKeyguardDisabledFeatures(mAdmin, 0);
762         mDpm.setPasswordQuality(mAdmin, 0);
763         mDpm.setMaximumTimeToLock(mAdmin, 0);
764         mDpm.setPermittedAccessibilityServices(mAdmin, null);
765         mDpm.setPermittedInputMethods(mAdmin, null);
766         Log.d(TAG, "clearProfileOwnerRelatedPolicies() finished");
767     }
768 
clearPolicyTransparencyUserRestriction(int mode)769     private void clearPolicyTransparencyUserRestriction(int mode) {
770         for (String userRestriction : UserRestrictions.getUserRestrictionsForPolicyTransparency(
771                 mode)) {
772             mDpm.clearUserRestriction(mAdmin, userRestriction);
773         }
774     }
775 
removeManagedProfile()776     private void removeManagedProfile() {
777         for (UserHandle userHandle : mUm.getUserProfiles()) {
778             Log.d(TAG, "removing managed profile for " + userHandle);
779             mDpm.removeUser(mAdmin, userHandle);
780         }
781     }
782 
783     /**
784      * Creates an intent to set the given user restriction using the device owner's {@code dpm}.
785      */
createSetDeviceOwnerUserRestrictionIntent(String restriction, boolean enforced)786     public static Intent createSetDeviceOwnerUserRestrictionIntent(String restriction,
787             boolean enforced) {
788         return createSetUserRestrictionIntent(restriction, enforced, /* currentUserDpm= */ false);
789     }
790 
791     /**
792      * Creates an intent to set the given user restriction using the current user's {@code dpm}.
793      */
createSetCurrentUserRestrictionIntent(String restriction, boolean enforced)794     public static Intent createSetCurrentUserRestrictionIntent(String restriction,
795             boolean enforced) {
796         return createSetUserRestrictionIntent(restriction, enforced, /* currentUserDpm= */ true);
797     }
798 
createSetUserRestrictionIntent(String restriction, boolean enforced, boolean forceCurrentUserDpm)799     private static Intent createSetUserRestrictionIntent(String restriction, boolean enforced,
800             boolean forceCurrentUserDpm) {
801         Log.d(TAG, "createSetUserRestrictionIntent(): restriction=" + restriction
802                 + ", enforced=" + enforced + ", forceCurrentUserDpm=" + forceCurrentUserDpm);
803         Intent intent = new Intent(ACTION_EXECUTE_COMMAND);
804         if (forceCurrentUserDpm) {
805             intent.putExtra(EXTRA_USE_CURRENT_USER_DPM, true);
806         }
807         return intent
808                 .putExtra(EXTRA_COMMAND, COMMAND_SET_USER_RESTRICTION)
809                 .putExtra(EXTRA_USER_RESTRICTION, restriction)
810                 .putExtra(EXTRA_ENFORCED, enforced);
811     }
812 
getEnabledNonSystemImes()813     private List<String> getEnabledNonSystemImes() {
814         InputMethodManager inputMethodManager = getSystemService(InputMethodManager.class);
815         final List<InputMethodInfo> inputMethods = inputMethodManager.getEnabledInputMethodList();
816         return inputMethods.stream()
817                 .filter(inputMethodInfo -> !isSystemInputMethodInfo(inputMethodInfo))
818                 .map(inputMethodInfo -> inputMethodInfo.getPackageName())
819                 .filter(packageName -> !packageName.equals(getPackageName()))
820                 .distinct()
821                 .collect(Collectors.toList());
822     }
823 
isSystemInputMethodInfo(InputMethodInfo inputMethodInfo)824     private boolean isSystemInputMethodInfo(InputMethodInfo inputMethodInfo) {
825         final ApplicationInfo applicationInfo = inputMethodInfo.getServiceInfo().applicationInfo;
826         return (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
827     }
828 
createAndSwitchUserWithMessage(String startUserSessionMessage, String endUserSessionMessage)829     private void createAndSwitchUserWithMessage(String startUserSessionMessage,
830             String endUserSessionMessage) {
831         if (!mDpm.isDeviceOwnerApp(getPackageName())) {
832             return;
833         }
834         mDpm.setStartUserSessionMessage(mAdmin, startUserSessionMessage);
835         mDpm.setEndUserSessionMessage(mAdmin, endUserSessionMessage);
836         mDpm.setAffiliationIds(mAdmin,
837                 Collections.singleton(DeviceAdminTestReceiver.AFFILIATION_ID));
838 
839         PersistableBundle extras = new PersistableBundle();
840         extras.putBoolean(DeviceAdminTestReceiver.EXTRA_LOGOUT_ON_START, true);
841         UserHandle userHandle = mDpm.createAndManageUser(mAdmin, "managed user", mAdmin,
842                 extras,
843                 SKIP_SETUP_WIZARD | MAKE_USER_EPHEMERAL);
844         // TODO(b/204483021): move to helper class / restore after user is logged out
845         if (UserManager.isHeadlessSystemUserMode()) {
846             mAm.setStopUserOnSwitch(ActivityManager.STOP_USER_ON_SWITCH_FALSE);
847         }
848         Log.d(TAG, "Switching to user " + userHandle);
849         mDpm.switchUser(mAdmin, userHandle);
850     }
851 
getCurrentLauncherPackage()852     private String getCurrentLauncherPackage() {
853         ResolveInfo resolveInfo = getPackageManager()
854             .resolveActivity(new Intent(Intent.ACTION_MAIN)
855                 .addCategory(Intent.CATEGORY_HOME), PackageManager.MATCH_DEFAULT_ONLY);
856         if (resolveInfo == null || resolveInfo.activityInfo == null) {
857             return null;
858         }
859 
860         return resolveInfo.activityInfo.packageName;
861     }
862 
createIntentForDisablingKeyguardOrStatusBar(Context context, String command, boolean disabled)863     static Intent createIntentForDisablingKeyguardOrStatusBar(Context context, String command,
864             boolean disabled) {
865         return new Intent(context, CommandReceiverActivity.class)
866                 .putExtra(CommandReceiverActivity.EXTRA_USE_CURRENT_USER_DPM, true)
867                 .putExtra(CommandReceiverActivity.EXTRA_COMMAND, command)
868                 .putExtra(CommandReceiverActivity.EXTRA_ENFORCED, disabled);
869     }
870 }
871