• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 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.tv.settings.deviceadmin;
18 
19 import android.app.Activity;
20 import android.app.ActivityManager;
21 import android.app.AppOpsManager;
22 import android.app.Dialog;
23 import android.app.admin.DeviceAdminInfo;
24 import android.app.admin.DeviceAdminReceiver;
25 import android.app.admin.DevicePolicyManager;
26 import android.app.settings.SettingsEnums;
27 import android.content.ComponentName;
28 import android.content.DialogInterface;
29 import android.content.Intent;
30 import android.content.pm.ActivityInfo;
31 import android.content.pm.ApplicationInfo;
32 import android.content.pm.PackageInfo;
33 import android.content.pm.PackageManager;
34 import android.content.pm.PackageManager.NameNotFoundException;
35 import android.content.pm.ResolveInfo;
36 import android.content.pm.UserInfo;
37 import android.content.res.Resources;
38 import android.os.Binder;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.IBinder;
42 import android.os.RemoteCallback;
43 import android.os.RemoteException;
44 import android.os.UserHandle;
45 import android.os.UserManager;
46 import android.text.TextUtils;
47 import android.util.EventLog;
48 import android.util.Log;
49 import android.view.KeyEvent;
50 import android.view.View;
51 import android.view.ViewGroup;
52 import android.widget.AppSecurityPermissions;
53 import android.widget.Button;
54 import android.widget.ImageView;
55 import android.widget.TextView;
56 
57 import androidx.appcompat.app.AlertDialog;
58 import androidx.fragment.app.FragmentActivity;
59 
60 import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
61 import com.android.settingslib.RestrictedLockUtilsInternal;
62 import com.android.tv.settings.EventLogTags;
63 import com.android.tv.settings.R;
64 
65 import org.xmlpull.v1.XmlPullParserException;
66 
67 import java.io.IOException;
68 import java.util.ArrayList;
69 import java.util.List;
70 import java.util.Optional;
71 
72 
73 public class DeviceAdminAdd extends FragmentActivity {
74     static final String TAG = "DeviceAdminAdd";
75 
76     static final int DIALOG_WARNING = 1;
77 
78     public static final String EXTRA_DEVICE_ADMIN_PACKAGE_NAME =
79             "android.app.extra.DEVICE_ADMIN_PACKAGE_NAME";
80 
81     public static final String EXTRA_CALLED_FROM_SUPPORT_DIALOG =
82             "android.app.extra.CALLED_FROM_SUPPORT_DIALOG";
83 
84     private final IBinder mToken = new Binder();
85 
86     DevicePolicyManager mDPM;
87     AppOpsManager mAppOps;
88     DeviceAdminInfo mDeviceAdmin;
89 
90     boolean mRefreshing;
91     boolean mAddingProfileOwner;
92     boolean mWaitingForRemoveMsg;
93     boolean mUninstalling = false;
94     boolean mAdding;
95     boolean mAdminPoliciesInitialized;
96 
97     ImageView mAdminIcon;
98     TextView mAdminName;
99     TextView mAdminDescription;
100     TextView mAddMsg;
101     TextView mProfileOwnerWarning;
102     ImageView mAddMsgExpander;
103     TextView mAdminWarning;
104     TextView mSupportMessage;
105     ViewGroup mAdminPolicies;
106     Button mActionButton;
107     Button mUninstallButton;
108     Button mCancelButton;
109 
110     Handler mHandler;
111 
112 
113     @Override
onCreate(Bundle icicle)114     protected void onCreate(Bundle icicle) {
115         super.onCreate(icicle);
116 
117         mDPM = getSystemService(DevicePolicyManager.class);
118         mAppOps = getSystemService(AppOpsManager.class);
119         PackageManager packageManager = getPackageManager();
120 
121         if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
122             Log.w(TAG, "Cannot start ADD_DEVICE_ADMIN as a new task");
123             finish();
124             return;
125         }
126 
127         String action = getIntent().getAction();
128         ComponentName who = (ComponentName) getIntent().getParcelableExtra(
129                 DevicePolicyManager.EXTRA_DEVICE_ADMIN);
130         if (who == null) {
131             String packageName = getIntent().getStringExtra(EXTRA_DEVICE_ADMIN_PACKAGE_NAME);
132             Optional<ComponentName> installedAdmin = findAdminWithPackageName(packageName);
133             if (!installedAdmin.isPresent()) {
134                 Log.w(TAG, "No component specified in " + action);
135                 finish();
136                 return;
137             }
138             who = installedAdmin.get();
139             mUninstalling = true;
140 
141             Log.d(TAG, "Uninstalling admin " + who);
142         }
143 
144         if (action != null && action.equals(DevicePolicyManager.ACTION_SET_PROFILE_OWNER)) {
145             setResult(RESULT_CANCELED);
146             setFinishOnTouchOutside(true);
147             mAddingProfileOwner = true;
148             String callingPackage = getCallingPackage();
149             if (callingPackage == null || !callingPackage.equals(who.getPackageName())) {
150                 Log.e(TAG, "Unknown or incorrect caller");
151                 finish();
152                 return;
153             }
154             try {
155                 PackageInfo packageInfo = packageManager.getPackageInfo(callingPackage, 0);
156                 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
157                     Log.e(TAG, "Cannot set a non-system app as a profile owner");
158                     finish();
159                     return;
160                 }
161             } catch (NameNotFoundException nnfe) {
162                 Log.e(TAG, "Cannot find the package " + callingPackage);
163                 finish();
164                 return;
165             }
166         }
167 
168         ActivityInfo ai;
169         try {
170             ai = packageManager.getReceiverInfo(who, PackageManager.GET_META_DATA);
171         } catch (PackageManager.NameNotFoundException e) {
172             Log.w(TAG, "Unable to retrieve device policy " + who, e);
173             finish();
174             return;
175         }
176 
177         // When activating, make sure the given component name is actually a valid device admin.
178         // No need to check this when deactivating, because it is safe to deactivate an active
179         // invalid device admin.
180         if (!mDPM.isAdminActive(who)) {
181             List<ResolveInfo> avail = packageManager.queryBroadcastReceivers(
182                     new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
183                     PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
184             int count = avail == null ? 0 : avail.size();
185             boolean found = false;
186             for (int i = 0; i < count; i++) {
187                 ResolveInfo ri = avail.get(i);
188                 if (ai.packageName.equals(ri.activityInfo.packageName)
189                         && ai.name.equals(ri.activityInfo.name)) {
190                     try {
191                         // We didn't retrieve the meta data for all possible matches, so
192                         // need to use the activity info of this specific one that was retrieved.
193                         ri.activityInfo = ai;
194                         DeviceAdminInfo dpi = new DeviceAdminInfo(this, ri);
195                         found = true;
196                     } catch (XmlPullParserException e) {
197                         Log.w(TAG, "Bad " + ri.activityInfo, e);
198                     } catch (IOException e) {
199                         Log.w(TAG, "Bad " + ri.activityInfo, e);
200                     }
201                     break;
202                 }
203             }
204             if (!found) {
205                 Log.w(TAG, "Request to add invalid device admin: " + who);
206                 finish();
207                 return;
208             }
209         }
210 
211         ResolveInfo ri = new ResolveInfo();
212         ri.activityInfo = ai;
213         try {
214             mDeviceAdmin = new DeviceAdminInfo(this, ri);
215         } catch (XmlPullParserException e) {
216             Log.w(TAG, "Unable to retrieve device policy " + who, e);
217             finish();
218             return;
219         } catch (IOException e) {
220             Log.w(TAG, "Unable to retrieve device policy " + who, e);
221             finish();
222             return;
223         }
224 
225         // This admin already exists, an we have two options at this point.  If new policy
226         // bits are set, show the user the new list.  If nothing has changed, simply return
227         // "OK" immediately.
228         if (DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN.equals(getIntent().getAction())) {
229             mRefreshing = false;
230             if (mDPM.isAdminActive(who)) {
231                 if (mDPM.isRemovingAdmin(who, android.os.Process.myUserHandle().getIdentifier())) {
232                     Log.w(TAG, "Requested admin is already being removed: " + who);
233                     finish();
234                     return;
235                 }
236 
237                 ArrayList<DeviceAdminInfo.PolicyInfo> newPolicies = mDeviceAdmin.getUsedPolicies();
238                 for (int i = 0; i < newPolicies.size(); i++) {
239                     DeviceAdminInfo.PolicyInfo pi = newPolicies.get(i);
240                     if (!mDPM.hasGrantedPolicy(who, pi.ident)) {
241                         mRefreshing = true;
242                         break;
243                     }
244                 }
245                 if (!mRefreshing) {
246                     // Nothing changed (or policies were removed) - return immediately
247                     setResult(Activity.RESULT_OK);
248                     finish();
249                     return;
250                 }
251             }
252         }
253 
254         if (mAddingProfileOwner) {
255             // If we're trying to add a profile owner and user setup hasn't completed yet, no
256             // need to prompt for permission. Just add and finish
257             if (!mDPM.hasUserSetupCompleted()) {
258                 addAndFinish();
259                 return;
260             }
261 
262             // otherwise, only the defined default supervision profile owner can be set after user
263             // setup.
264             final String supervisor = getString(
265                     getResources().getIdentifier("config_defaultSupervisionProfileOwnerComponent",
266                             "string", "android"));
267             final String supervisionRolePackage = getString(
268                     getResources().getIdentifier("config_systemSupervision", "string", "android"));
269             if (supervisor == null && supervisionRolePackage == null) {
270                 Log.w(TAG, "Unable to set profile owner post-setup, no default supervisor"
271                         + "profile owner defined");
272                 finish();
273                 return;
274             }
275 
276             final ComponentName supervisorComponent = ComponentName.unflattenFromString(
277                     supervisor);
278             if (who.compareTo(supervisorComponent) != 0
279                     && !who.getPackageName().equals(supervisionRolePackage)) {
280                 Log.w(TAG, "Unable to set non-default profile owner post-setup " + who);
281                 finish();
282                 return;
283             } else {
284                 addAndFinish();
285             }
286         }
287 
288         // Create UI for device admin config (CtsVerifier mostly)
289         createAddDeviceAdminUi();
290     }
291 
addAndFinish()292     void addAndFinish() {
293         try {
294             logSpecialPermissionChange(true, mDeviceAdmin.getComponent().getPackageName());
295             mDPM.setActiveAdmin(mDeviceAdmin.getComponent(), mRefreshing);
296             EventLog.writeEvent(EventLogTags.EXP_DET_DEVICE_ADMIN_ACTIVATED_BY_USER,
297                 mDeviceAdmin.getActivityInfo().applicationInfo.uid);
298 
299             setResult(Activity.RESULT_OK);
300         } catch (RuntimeException e) {
301             // Something bad happened...  could be that it was
302             // already set, though.
303             Log.w(TAG, "Exception trying to activate admin "
304                     + mDeviceAdmin.getComponent(), e);
305             if (mDPM.isAdminActive(mDeviceAdmin.getComponent())) {
306                 setResult(Activity.RESULT_OK);
307             }
308         }
309         if (mAddingProfileOwner) {
310             try {
311                 mDPM.setProfileOwner(mDeviceAdmin.getComponent(), UserHandle.myUserId());
312             } catch (RuntimeException re) {
313                 setResult(Activity.RESULT_CANCELED);
314             }
315         }
316         finish();
317     }
318 
logSpecialPermissionChange(boolean allow, String packageName)319     void logSpecialPermissionChange(boolean allow, String packageName) {
320         int logCategory = allow ? SettingsEnums.APP_SPECIAL_PERMISSION_ADMIN_ALLOW :
321                 SettingsEnums.APP_SPECIAL_PERMISSION_ADMIN_DENY;
322     }
323 
324     @Override
onResume()325     protected void onResume() {
326         super.onResume();
327         mActionButton.setEnabled(true);
328         if (!mAddingProfileOwner) {
329             updateInterface();
330         }
331         // As long as we are running, don't let anyone overlay stuff on top of the screen.
332         mAppOps.setUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, true, mToken);
333         mAppOps.setUserRestriction(AppOpsManager.OP_TOAST_WINDOW, true, mToken);
334     }
335 
336     @Override
onPause()337     protected void onPause() {
338         super.onPause();
339         // This just greys out the button. The actual listener is attached to R.id.restricted_action
340         mActionButton.setEnabled(false);
341         mAppOps.setUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, false, mToken);
342         mAppOps.setUserRestriction(AppOpsManager.OP_TOAST_WINDOW, false, mToken);
343         try {
344             ActivityManager.getService().resumeAppSwitches();
345         } catch (RemoteException e) {
346         }
347     }
348 
349 
350      /**
351      * @return an {@link Optional} containing the admin with a given package name, if it exists,
352      *         or {@link Optional#empty()} otherwise.
353      */
findAdminWithPackageName(String packageName)354     private Optional<ComponentName> findAdminWithPackageName(String packageName) {
355         List<ComponentName> admins = mDPM.getActiveAdmins();
356         if (admins == null) {
357             return Optional.empty();
358         }
359         return admins.stream().filter(i -> i.getPackageName().equals(packageName)).findAny();
360     }
361 
isAdminUninstallable()362     private boolean isAdminUninstallable() {
363         // System apps can't be uninstalled.
364         return !mDeviceAdmin.getActivityInfo().applicationInfo.isSystemApp();
365     }
366 
createAddDeviceAdminUi()367     private void createAddDeviceAdminUi() {
368         setContentView(R.layout.device_admin_add);
369 
370         mAdminIcon = (ImageView) findViewById(R.id.admin_icon);
371         mAdminName = (TextView) findViewById(R.id.admin_name);
372         mAdminDescription = (TextView) findViewById(R.id.admin_description);
373         mProfileOwnerWarning = (TextView) findViewById(R.id.profile_owner_warning);
374 
375         mAddMsg = (TextView) findViewById(R.id.add_msg);
376         mAddMsgExpander = (ImageView) findViewById(R.id.add_msg_expander);
377 
378 
379         mAdminWarning = (TextView) findViewById(R.id.admin_warning);
380         mAdminPolicies = (ViewGroup) findViewById(R.id.admin_policies);
381         mSupportMessage = (TextView) findViewById(R.id.admin_support_message);
382 
383         mCancelButton = (Button) findViewById(R.id.cancel_button);
384         mCancelButton.setFilterTouchesWhenObscured(true);
385         mCancelButton.setOnClickListener(new View.OnClickListener() {
386             public void onClick(View v) {
387                 EventLog.writeEvent(EventLogTags.EXP_DET_DEVICE_ADMIN_DECLINED_BY_USER,
388                         mDeviceAdmin.getActivityInfo().applicationInfo.uid);
389                 finish();
390             }
391         });
392 
393         mUninstallButton = (Button) findViewById(R.id.uninstall_button);
394         mUninstallButton.setFilterTouchesWhenObscured(true);
395         mUninstallButton.setOnClickListener(new View.OnClickListener() {
396             public void onClick(View v) {
397                 EventLog.writeEvent(EventLogTags.EXP_DET_DEVICE_ADMIN_UNINSTALLED_BY_USER,
398                         mDeviceAdmin.getActivityInfo().applicationInfo.uid);
399                 mDPM.uninstallPackageWithActiveAdmins(mDeviceAdmin.getPackageName());
400                 finish();
401             }
402         });
403 
404         mActionButton = (Button) findViewById(R.id.action_button);
405 
406         final View restrictedAction = findViewById(R.id.restricted_action);
407         restrictedAction.setFilterTouchesWhenObscured(true);
408         final View.OnClickListener restrictedActionClickListener = v -> {
409             if (!mActionButton.isEnabled()) {
410                 return;
411             }
412             if (mAdding) {
413                 addAndFinish();
414             } else if (mUninstalling) {
415                 mDPM.uninstallPackageWithActiveAdmins(mDeviceAdmin.getPackageName());
416                 finish();
417             } else if (!mWaitingForRemoveMsg) {
418                 try {
419                     // Don't allow the admin to put a dialog up in front
420                     // of us while we interact with the user.
421                     ActivityManager.getService().stopAppSwitches();
422                 } catch (RemoteException e) {
423                     Log.w(TAG, "Unable to stop app switches.", e);
424                 }
425                 mWaitingForRemoveMsg = true;
426                 mDPM.getRemoveWarning(mDeviceAdmin.getComponent(),
427                         new RemoteCallback(new RemoteCallback.OnResultListener() {
428                             @Override
429                             public void onResult(Bundle result) {
430                                 CharSequence msg = result != null
431                                         ? result.getCharSequence(
432                                         DeviceAdminReceiver.EXTRA_DISABLE_WARNING)
433                                         : null;
434                                 continueRemoveAction(msg);
435                             }
436                         }, mHandler));
437                 // Don't want to wait too long.
438                 getWindow().getDecorView().getHandler().postDelayed(
439                         () -> continueRemoveAction(null), 2 * 1000);
440             }
441         };
442         restrictedAction.setOnKeyListener((view, keyCode, keyEvent) -> {
443             if ((keyEvent.getFlags() & KeyEvent.FLAG_FROM_SYSTEM) == 0) {
444                 Log.e(TAG, "Can not activate device-admin with KeyEvent from non-system app.");
445                 // Consume event to suppress click.
446                 return true;
447             }
448             // Fallback to view click handler.
449             return false;
450         });
451         restrictedAction.setOnClickListener(restrictedActionClickListener);
452     }
453 
updateInterface()454     void updateInterface() {
455         findViewById(R.id.restricted_icon).setVisibility(View.GONE);
456         mAdminIcon.setImageDrawable(mDeviceAdmin.loadIcon(getPackageManager()));
457         mAdminName.setText(mDeviceAdmin.loadLabel(getPackageManager()));
458         try {
459             mAdminDescription.setText(
460                     mDeviceAdmin.loadDescription(getPackageManager()));
461             mAdminDescription.setVisibility(View.VISIBLE);
462         } catch (Resources.NotFoundException e) {
463             mAdminDescription.setVisibility(View.GONE);
464         }
465         String mAddMsgText = null;
466         if (mAddMsgText != null) {
467             mAddMsg.setText(mAddMsgText);
468             mAddMsg.setVisibility(View.VISIBLE);
469         } else {
470             mAddMsg.setVisibility(View.GONE);
471             mAddMsgExpander.setVisibility(View.GONE);
472         }
473         if (!mRefreshing && !mAddingProfileOwner
474                 && mDPM.isAdminActive(mDeviceAdmin.getComponent())) {
475             mAdding = false;
476             final boolean isProfileOwner =
477                     mDeviceAdmin.getComponent().equals(mDPM.getProfileOwner());
478             final boolean isManagedProfile = isManagedProfile(mDeviceAdmin);
479             if (isProfileOwner && isManagedProfile) {
480                 // Profile owner in a managed profile, user can remove profile to disable admin.
481                 mAdminWarning.setText(R.string.admin_profile_owner_message);
482                 mActionButton.setText(R.string.remove_managed_profile_label);
483 
484                 final EnforcedAdmin admin = getAdminEnforcingCantRemoveProfile();
485                 final boolean hasBaseRestriction = hasBaseCantRemoveProfileRestriction();
486                 if ((hasBaseRestriction && mDPM.isOrganizationOwnedDeviceWithManagedProfile())
487                         || (admin != null && !hasBaseRestriction)) {
488                     findViewById(R.id.restricted_icon).setVisibility(View.VISIBLE);
489                 }
490                 mActionButton.setEnabled(admin == null && !hasBaseRestriction);
491             } else if (isProfileOwner || mDeviceAdmin.getComponent().equals(
492                             mDPM.getDeviceOwnerComponentOnCallingUser())) {
493                 // Profile owner in a user or device owner, user can't disable admin.
494                 if (isProfileOwner) {
495                     // Show profile owner in a user description.
496                     mAdminWarning.setText(R.string.admin_profile_owner_user_message);
497                 } else {
498                     // Show device owner description.
499                     mAdminWarning.setText(R.string.admin_device_owner_message);
500                 }
501                 mActionButton.setText(R.string.remove_device_admin);
502                 mActionButton.setEnabled(false);
503             } else {
504                 addDeviceAdminPolicies(false /* showDescription */);
505                 mAdminWarning.setText(getString(R.string.device_admin_status,
506                         mDeviceAdmin.getActivityInfo().applicationInfo.loadLabel(
507                         getPackageManager())));
508                 setTitle(R.string.active_device_admin_msg);
509                 if (mUninstalling) {
510                     mActionButton.setText(R.string.remove_and_uninstall_device_admin);
511                 } else {
512                     mActionButton.setText(R.string.remove_device_admin);
513                 }
514             }
515             CharSequence supportMessage = mDPM.getLongSupportMessageForUser(
516                     mDeviceAdmin.getComponent(), UserHandle.myUserId());
517             if (!TextUtils.isEmpty(supportMessage)) {
518                 mSupportMessage.setText(supportMessage);
519                 mSupportMessage.setVisibility(View.VISIBLE);
520             } else {
521                 mSupportMessage.setVisibility(View.GONE);
522             }
523         } else {
524             addDeviceAdminPolicies(true /* showDescription */);
525             mAdminWarning.setText(getString(R.string.device_admin_warning,
526                     mDeviceAdmin.getActivityInfo().applicationInfo.loadLabel(getPackageManager())));
527             setTitle(R.string.add_device_admin_msg);
528             mActionButton.setText(R.string.add_device_admin);
529             if (isAdminUninstallable()) {
530                 mUninstallButton.setVisibility(View.VISIBLE);
531             }
532             mSupportMessage.setVisibility(View.GONE);
533             mAdding = true;
534         }
535     }
536 
continueRemoveAction(CharSequence msg)537     void continueRemoveAction(CharSequence msg) {
538         if (!mWaitingForRemoveMsg) {
539             return;
540         }
541         mWaitingForRemoveMsg = false;
542         if (msg == null) {
543             try {
544                 ActivityManager.getService().resumeAppSwitches();
545             } catch (RemoteException e) {
546             }
547             logSpecialPermissionChange(false, mDeviceAdmin.getComponent().getPackageName());
548             mDPM.removeActiveAdmin(mDeviceAdmin.getComponent());
549             finish();
550         } else {
551             try {
552                 // Continue preventing anything from coming in front.
553                 ActivityManager.getService().stopAppSwitches();
554             } catch (RemoteException e) {
555             }
556             Bundle args = new Bundle();
557             args.putCharSequence(
558                     DeviceAdminReceiver.EXTRA_DISABLE_WARNING, msg);
559             showDialog(DIALOG_WARNING, args);
560         }
561     }
562 
addDeviceAdminPolicies(boolean showDescription)563     private void addDeviceAdminPolicies(boolean showDescription) {
564         if (!mAdminPoliciesInitialized) {
565             boolean isAdminUser = UserManager.get(this).isAdminUser();
566             for (DeviceAdminInfo.PolicyInfo pi : mDeviceAdmin.getUsedPolicies()) {
567                 int descriptionId = isAdminUser ? pi.description : pi.descriptionForSecondaryUsers;
568                 int labelId = isAdminUser ? pi.label : pi.labelForSecondaryUsers;
569                 View view = AppSecurityPermissions.getPermissionItemView(this, getText(labelId),
570                         showDescription ? getText(descriptionId) : "", true);
571                 mAdminPolicies.addView(view);
572             }
573             mAdminPoliciesInitialized = true;
574         }
575     }
576 
577     @Override
onCreateDialog(int id, Bundle args)578     protected Dialog onCreateDialog(int id, Bundle args) {
579         switch (id) {
580             case DIALOG_WARNING: {
581                 CharSequence msg = args.getCharSequence(DeviceAdminReceiver.EXTRA_DISABLE_WARNING);
582                 AlertDialog.Builder builder = new AlertDialog.Builder(this);
583                 builder.setMessage(msg);
584                 builder.setPositiveButton(R.string.settings_ok,
585                         new DialogInterface.OnClickListener() {
586                             public void onClick(DialogInterface dialog, int which) {
587                             try {
588                                 ActivityManager.getService().resumeAppSwitches();
589                             } catch (RemoteException e) {
590                             }
591                             mDPM.removeActiveAdmin(mDeviceAdmin.getComponent());
592                             finish();
593                         }
594                     });
595                 builder.setNegativeButton(R.string.settings_cancel, null);
596                 return builder.create();
597             }
598             default:
599                 return super.onCreateDialog(id, args);
600 
601         }
602     }
603 
604     /**
605      * @return true if adminInfo is running in a managed profile.
606      */
isManagedProfile(DeviceAdminInfo adminInfo)607     private boolean isManagedProfile(DeviceAdminInfo adminInfo) {
608         UserManager um = UserManager.get(this);
609         UserInfo info = um.getUserInfo(
610                 UserHandle.getUserId(adminInfo.getActivityInfo().applicationInfo.uid));
611         return info != null ? info.isManagedProfile() : false;
612     }
613 
getAdminEnforcingCantRemoveProfile()614     private EnforcedAdmin getAdminEnforcingCantRemoveProfile() {
615         // Removing a managed profile is disallowed if DISALLOW_REMOVE_MANAGED_PROFILE
616         // is set in the parent rather than the user itself.
617         return RestrictedLockUtilsInternal.checkIfRestrictionEnforced(this,
618                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, getParentUserId());
619     }
620 
hasBaseCantRemoveProfileRestriction()621     private boolean hasBaseCantRemoveProfileRestriction() {
622         return RestrictedLockUtilsInternal.hasBaseUserRestriction(this,
623                 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, getParentUserId());
624     }
625 
getParentUserId()626     private int getParentUserId() {
627         return UserManager.get(this).getProfileParent(UserHandle.myUserId()).id;
628     }
629 }
630