@Override public void toggleState(Context context) { final DevicePolicyManager pm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName cm = new ComponentName(context, LockAdmin.class); if (pm.isAdminActive(cm)) { Runnable lockRunnable = new Runnable() { @Override public void run() { pm.lockNow(); } }; Handler handler = new Handler(); handler.post(lockRunnable); if (Globals.getAppPrefs(context).getBoolean(KEY_DOUBLE_LOCK, DEFAULT_VALUE)) { handler.postDelayed(lockRunnable, 500); } } else { Globals.startIntent(context, new Intent(context, ProxyActivity.class) .putExtra("proxy", new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN) .putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cm) .putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, context.getResources().getString(R.string.admin_explain)))); } }
private State getCurrentState() { ComponentName componentName = componentName(); DevicePolicyManager policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); if (!policyManager.isAdminActive(componentName)) { return State.NEEDS_PERMISSIONS; } if (!policyManager.getCameraDisabled(componentName)) { return State.HAS_PERMISSIONS; } if (!policyManager.isDeviceOwnerApp(BuildConfig.APPLICATION_ID)) { return State.CAMERA_DISABLED; } // Apparently we can't query for user restrictions, so just always set them if they're not // already set. We know that we're allowed to because we're the device owner. policyManager.addUserRestriction(componentName, UserManager.DISALLOW_ADD_USER); policyManager.addUserRestriction(componentName, UserManager.DISALLOW_FACTORY_RESET); return State.IS_DEVICE_OWNER; }
private void removeActiveAdmin() { DevicePolicyManager mgr = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName cn = new ComponentName(mContext, AdminReceiver.class); if ( mgr.isAdminActive(cn)) { mgr.removeActiveAdmin(cn); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_real); if (savedInstanceState == null) { DevicePolicyManager manager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); if (manager.isProfileOwnerApp(getApplicationContext().getPackageName())) { // If the managed profile is already set up, we show the main screen. showMainFragment(); } else { // If not, we show the set up screen. showSetupProfile(); } } }
/** * Checks if the application is available in this profile. * * @param packageName The package name * @return True if the application is available in this profile. */ private boolean isApplicationEnabled(String packageName) { Activity activity = getActivity(); PackageManager packageManager = activity.getPackageManager(); try { ApplicationInfo applicationInfo = packageManager.getApplicationInfo( packageName, PackageManager.GET_UNINSTALLED_PACKAGES); // Return false if the app is not installed in this profile if (0 == (applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED)) { return false; } // Check if the app is not hidden in this profile DevicePolicyManager devicePolicyManager = (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE); return !devicePolicyManager.isApplicationHidden( BasicDeviceAdminReceiver.getComponentName(activity), packageName); } catch (PackageManager.NameNotFoundException e) { return false; } }
/** * Enables forwarding of share intent between private account and managed profile. */ private void enableForwarding() { Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } DevicePolicyManager manager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); try { IntentFilter filter = new IntentFilter(Intent.ACTION_SEND); filter.addDataType("text/plain"); filter.addDataType("image/jpeg"); // This is how you can register an IntentFilter as allowed pattern of Intent forwarding manager.addCrossProfileIntentFilter(BasicDeviceAdminReceiver.getComponentName(activity), filter, FLAG_MANAGED_CAN_ACCESS_PARENT | FLAG_PARENT_CAN_ACCESS_MANAGED); } catch (IntentFilter.MalformedMimeTypeException e) { e.printStackTrace(); } }
/** * Sends a sample intent of a plain text message. This is just a utility function to see how * the intent forwarding works. */ private void sendIntent() { Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } DevicePolicyManager manager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, manager.isProfileOwnerApp(activity.getApplicationContext().getPackageName()) ? "From the managed account" : "From the primary account"); try { startActivity(intent); Log.d(TAG, "A sample intent was sent."); } catch (ActivityNotFoundException e) { Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); } }
/** * Wipes out all the data related to this managed profile. */ private void removeProfile() { Activity activity = getActivity(); if (null == activity || activity.isFinishing()) { return; } DevicePolicyManager manager = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); manager.wipeData(0); // The screen turns off here }
@Override public void onClick(View v) { // First, persist the policy. Then, launch intent to trigger the system screen // requesting user to confirm the activation of the device administrator. writePolicy(); Intent activateDeviceAdminIntent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); activateDeviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mPolicy.getPolicyAdmin()); // It is good practice to include the optional explanation text to explain to // user why the application is requesting to be a device administrator. The system // will display this message on the activation screen. activateDeviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getResources().getString(R.string.device_admin_activation_message)); startActivityForResult(activateDeviceAdminIntent, REQ_ACTIVATE_DEVICE_ADMIN); }
public boolean keyguardEnforcedByDevicePolicy() { DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); if (dpm != null) { int passwordQuality = dpm.getPasswordQuality(null); switch (passwordQuality) { case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX: case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX: case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: return true; } } return false; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCN = new ComponentName(this, MainReceiver.class); // Receiver, not Activity! mDPM = (DevicePolicyManager)getSystemService(DEVICE_POLICY_SERVICE); if (isHuaweiNougat()) { launchEmuiLockActivity(); finish(); } else if (isAdminActive()) { lock(); finish(); } else { enableAppAsAdministrator(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 设备安全管理服务 2.2之前的版本是没有对外暴露的 只能通过反射技术获取 devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE); boolean isAdminActive = devicePolicyManager.isAdminActive(Dar.getCn(this)); if (isAdminActive) { // 锁屏 devicePolicyManager.lockNow(); finish(); }else{ startAddDeviceAdminAty(); } }
public static void lockDevice(Context context) { ComponentName component = new ComponentName(context, LockDeviceReceiver.class); context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); DevicePolicyManager mDevicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); if(mDevicePolicyManager.isAdminActive(component)) mDevicePolicyManager.lockNow(); else { launchApp(context, () -> { Intent intent = new Intent(context, DummyActivity.class); intent.putExtra("device_admin", true); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent, getActivityOptionsBundle(ApplicationType.APPLICATION)); if(context instanceof Activity) ((Activity) context).overridePendingTransition(0, 0); }); } }
public static void uninstall(Context context, Prefs prefs) { try { ComponentName devAdminReceiver = new ComponentName(context, DAReceiver.class); DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); dpm.removeActiveAdmin(devAdminReceiver); if (prefs.proximityToLock && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && !Shell.SU.available()) prefs.setBool(Prefs.KEYS.PROXIMITY_TO_LOCK.toString(), false); } catch (Exception ignored) { } Uri packageUri = Uri.parse("package:" + context.getPackageName()); Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri); uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(uninstallIntent); }
public static boolean isDeviceSecure(Context context) { // Starting with android 6.0 calling isLockScreenDisabled fails altogether because the signature has changed. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { KeyguardManager keyguardMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); return keyguardMgr != null && keyguardMgr.isDeviceSecure(); } try { String LOCKSCREEN_UTILS_CLASSNAME = "com.android.internal.widget.LockPatternUtils"; Class<?> lockUtilsClass = Class.forName(LOCKSCREEN_UTILS_CLASSNAME); Object lockUtils = lockUtilsClass.getConstructor(Context.class).newInstance(context); Method method = lockUtilsClass.getMethod("getActivePasswordQuality"); // Starting with android 5.x this fails with InvocationTargetException (caused by SecurityException - MANAGE_USERS permission is // required because internally some additional logic was added to return false if one can switch between several users) // -> therefore if no exception is thrown, we know the screen lock setting is set to Pattern, PIN/PW or something else other than 'None' or 'Swipe' Integer lockProtectionLevel = (Integer) method.invoke(lockUtils); return lockProtectionLevel >= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING; } catch (InvocationTargetException ignored) { } catch (Exception e) { MobileMessagingLogger.e("Error detecting whether screen lock is disabled: " + e); } return false; }
@Override public void clearPassword(Operation operation) { operation.setStatus(getContextResources().getString(R.string.operation_value_completed)); getResultBuilder().build(operation); getDevicePolicyManager().setPasswordQuality(getCdmDeviceAdmin(), DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); getDevicePolicyManager().setPasswordMinimumLength(getCdmDeviceAdmin(), getDefaultPasswordLength()); getDevicePolicyManager().resetPassword(getContextResources().getString(R.string.shared_pref_default_string), DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY); getDevicePolicyManager().lockNow(); getDevicePolicyManager().setPasswordQuality(getCdmDeviceAdmin(), DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED); if (Constants.DEBUG_MODE_ENABLED) { Log.d(TAG, "Password cleared"); } }
private String statusCodeToString(int newStatusCode) { int newStatus = R.string.encryption_status_unknown; switch (newStatusCode) { case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: newStatus = R.string.encryption_status_unsupported; break; case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: newStatus = R.string.encryption_status_inactive; break; case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: newStatus = R.string.encryption_status_activating; break; case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: newStatus = R.string.encryption_status_active; break; } return mActivity.getString(newStatus); }
private void initUI() { int[] ids = {R.id.button_hw,R.id.button_mac,R.id.button_bat,R.id.button_image,R.id.button_gsensor,R.id.button_brightness, R.id.button_rgb,R.id.button_multitouch,R.id.button_drawing,R.id.button_wifi,R.id.button_bt,R.id.button_sd, R.id.button_mp3,R.id.button_mp4,R.id.button_record,R.id.button_camera,R.id.button_lsensor,R.id.button_mobile, R.id.button_vibrate,R.id.button_flashlight,R.id.button_keyboard,R.id.button_compass,R.id.button_gyro,R.id.button_prox, R.id.button_gps,R.id.button_otg,R.id.button_ethernet,R.id.button_reset,R.id.button_fm}; for(int i =0;i < ids.length;i++) { findViewById(ids[i]).setOnClickListener(this); } mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mDeviceAdmin = new ComponentName(MainActivity.this, MainActivityWiperReceiver.class); //�õ���ǰ�豸��������û�м��� boolean active = mDPM.isAdminActive(mDeviceAdmin); if (!active) { //���û�м���Ļ�����ȥ��ʾ�û������һ�����г���ʱ�� getAdmin(); } }
/** * Change device lock code. * @param code - Operation code. * @param data - Data required(Lock code). */ public void changeLockCode(String code, String data) { ComponentName demoDeviceAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class); devicePolicyManager.setPasswordMinimumLength(demoDeviceAdmin, DEFAULT_PASSWORD_MIN_LENGTH); String password = null; try { JSONObject lockData = new JSONObject(data); if (!lockData.isNull(resources.getString(R.string.intent_extra_password))) { password = (String) lockData.get(resources.getString(R.string.intent_extra_password)); } resultBuilder.build(code); if (password!=null && !password.isEmpty()) { devicePolicyManager.resetPassword(password, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY); devicePolicyManager.lockNow(); } } catch (JSONException e) { Log.e(TAG, "Invalid JSON format." + e); } }
private void setupDeviceAdministratorPermissions(SharedPreferences sharedPreferences) { if (!isAdded() ) return; boolean on = sharedPreferences.getBoolean("useDeviceLock", false); if (on) { DevicePolicyManager mgr = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName cn = new ComponentName(mContext, AdminReceiver.class); if ( !mgr.isAdminActive(cn)) { Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cn); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, getString(R.string.useDeviceLockExplanation)); startActivity(intent); } } else { removeActiveAdmin(); } }
public static boolean lockApplication(Activity activity) { DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); if (dpm.isLockTaskPermitted(activity.getPackageName()) && dpm.isDeviceOwnerApp(activity.getPackageName())) { IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MAIN); intentFilter.addCategory(Intent.CATEGORY_HOME); intentFilter.addCategory(Intent.CATEGORY_DEFAULT); ComponentName adminComponentName = new ComponentName(activity, HomerPlayerDeviceAdmin.class); ComponentName activityComponentName = new ComponentName(activity, MainActivity.class); dpm.addPersistentPreferredActivity( adminComponentName, intentFilter, activityComponentName); lockScreen(activity); return true; } return false; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); //传说中的Log.i Log.i("--->lock!!", "start lock"); mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mComponentName = new ComponentName(this, LockReceiver.class); // 判断是否有权�? if (mDevicePolicyManager.isAdminActive(mComponentName)) { mDevicePolicyManager.lockNow(); // 下面两行都不好使,在android4.2 // android.os.Process.killProcess(android.os.Process.myPid()); // System.exit(0); LockActivity.this.finish(); } else { activeManager(); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); ComponentName deviceAdmin = new ComponentName(this, AdminReceiver.class); mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); if (!mDpm.isAdminActive(deviceAdmin)) { Toast.makeText(this, getString(R.string.not_device_admin), Toast.LENGTH_SHORT).show(); } if (mDpm.isDeviceOwnerApp(getPackageName())) { mDpm.setLockTaskPackages(deviceAdmin, new String[]{getPackageName()}); } else { Toast.makeText(this, getString(R.string.not_device_owner), Toast.LENGTH_SHORT).show(); } mDecorView = getWindow().getDecorView(); mWebView.loadUrl("http://www.vicarasolutions.com/"); }
@Override public boolean onPreferenceClick(Preference preference) { if (super.onPreferenceClick(preference)) { return true; } if (preference == mActivateEncryption) { if (alertIfMonkey(mActivity, R.string.monkey_encryption)) { return true; } // Check to see if encryption is even supported on this device (it's optional). if (mDPM.getStorageEncryptionStatus() == DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setMessage(R.string.encryption_not_supported); builder.setPositiveButton(R.string.encryption_not_supported_ok, null); builder.show(); return true; } // Launch the activity to activate encryption. May or may not return! Intent intent = new Intent(DevicePolicyManager.ACTION_START_ENCRYPTION); startActivityForResult(intent, REQUEST_CODE_START_ENCRYPTION); return true; } return false; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ��ȡ�豸������� policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); componentName = new ComponentName(this, AdminReceiver.class); /* * �������ж��Ƿ���Ȩ�ޣ����û�������activeManage()��Ȼ��������������finish()�� * ��������������ģ���ΪactiveManage()���ܻ��ڵȴ���һ��Activity�Ľ������ô��ʱ��Ȼû��Ȩ��ȴ * ִ����lockNow()�������ͳ����ˡ� ��������2���� * 1������дOnActivityResult()�������������ж��Ƿ��ȡȨ�ɹ�������������finish() * �����������activeManage()��ȡȨ�ޣ��������������������Ч���ܺã� * 2������дOnActivityResult()��������һ�λ�ȡȨ������������finish()��������������˵Ҳ���� * ʧ�ܣ�����Ȩ��û��ȡ�þ�finish�ˣ����������ͻص����棬�����ٰ�һ�������������� �����Ƽ���һ�ַ����� */ // �ж��Ƿ�������Ȩ�ޣ����������������������Լ�����û�����ȡȨ�� if (policyManager.isAdminActive(componentName)) { policyManager.lockNow(); finish(); } else { activeManage(); } setContentView(R.layout.activity_lock_screen); // ���������������������ʱ��Ͳ�������������һ�£� }
/** * This method is used to check the status of storage encryption. * @return Returns the current status. */ public boolean isEncryptionEnabled() { if (isDeviceAdminActive()) { switch (devicePolicyManager.getStorageEncryptionStatus()) { case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: return true; case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: return false; case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: return false; default: return false; } } return false; }
public OperationManager(Context context) { this.context = context; this.resources = context.getResources(); this.devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); this.cdmDeviceAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class); this.appList = new ApplicationManager(context.getApplicationContext()); this.resultBuilder = new ResultPayload(); AGENT_PACKAGE_NAME = context.getPackageName(); AUTHORIZED_PINNING_APPS = new String[]{AGENT_PACKAGE_NAME}; applicationManager = new ApplicationManager(context); notificationService = NotificationService.getInstance(context.getApplicationContext()); if(Constants.DEBUG_MODE_ENABLED) { Log.d(TAG, "New OperationManager created."); } }
@Override protected void onCreate(Bundle savedInstanceState) { DeviceState state; super.onCreate(savedInstanceState); context = this.getApplicationContext(); state = new DeviceState(context); Response androidForWorkCompatibility = state.evaluateAndroidForWorkCompatibility(); manager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); boolean isDeviceActive = Preference.getBoolean(context, Constants.PreferenceFlag.DEVICE_ACTIVE); if (CommonUtils.isNetworkAvailable(context)) { if (isDeviceActive || Constants.SKIP_WORK_PROFILE_CREATION) { skipToEnrollment(); } if (androidForWorkCompatibility.getCode()) { manageAndroidForWorkReceiption(); } else { skipToEnrollment(); } } else { Toast.makeText(context, context.getResources().getString(R.string.network_not_available_message), Toast.LENGTH_LONG).show(); finish(); } }
@Override public boolean onPreferenceChange(Preference pref, Object newValue) { boolean isChecked = (boolean) newValue; if (isChecked) { Log.d(TAG, "switchAdmin.isChecked() == true"); Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, snooperStopperDeviceAdmin); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Monitors failed unlock attempts and shutdowns phone if limit is reached"); startActivityForResult(intent, ACTIVATION_REQUEST); } else { Log.d(TAG, "switchAdmin.isChecked() == false"); devicePolicyManager.removeActiveAdmin(snooperStopperDeviceAdmin); updateSwitchAdminHandler.postDelayed(updateSwitchAdminRunnable, 1000); } return true; }
/** * Return {@code true} iff we are the profile owner of a managed profile. * Note that profile owner can be in primary user and secondary user too. */ @TargetApi(VERSION_CODES.N) public static boolean isManagedProfileOwner(Context context) { final DevicePolicyManager dpm = getDevicePolicyManager(context); if (BuildCompat.isAtLeastN()) { try { return dpm.isManagedProfile(DeviceAdminReceiver.getComponentName(context)); } catch (SecurityException ex) { // This is thrown if we are neither profile owner nor device owner. return false; } } // Pre-N, TestDPC only supports being the profile owner for a managed profile. Other apps // may support being a profile owner in other contexts (e.g. a secondary user) which will // require further checks. return isProfileOwner(context); }
@Override public boolean onPreferenceClick(Preference preference) { if (super.onPreferenceClick(preference)) { return true; } if (preference == mActivateEncryption) { if (alertIfMonkey(mActivity, R.string.monkey_encryption)) { return true; } // Check to see if encryption is even supported on this device (it's optional). if (mDPM.getStorageEncryptionStatus() == DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) { AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setMessage(R.string.encryption_not_supported); builder.setPositiveButton(R.string.encryption_not_supported_ok, null); builder.show(); return true; } // Launch the activity to activate encryption. May or may not return! Intent intent = new org.bbs.apklauncher.emb.IntentHelper(DevicePolicyManager.ACTION_START_ENCRYPTION); startActivityForResult(intent, REQUEST_CODE_START_ENCRYPTION); return true; } return false; }
/** * Sets the persistent device owner state by setting a special app restriction on GmsCore and * notifies GmsCore about the change by sending a broadcast. * * @param state The device owner state to be preserved across factory resets. If null, the * persistent device owner state and the corresponding restiction are cleared. */ @TargetApi(VERSION_CODES.O) public static void setPersistentDoStateWithApplicationRestriction( Context context, DevicePolicyManager dpm, ComponentName admin, String state) { Bundle restrictions = dpm.getApplicationRestrictions(admin, GMSCORE_PACKAGE); if (state == null) { // Clear the restriction restrictions.remove(PERSISTENT_DEVICE_OWNER_STATE); } else { // Set the restriction restrictions.putString(PERSISTENT_DEVICE_OWNER_STATE, state); } dpm.setApplicationRestrictions(admin, GMSCORE_PACKAGE, restrictions); Intent broadcastIntent = new Intent(BROADCAST_ACTION_FRP_CONFIG_CHANGED); broadcastIntent.setPackage(GMSCORE_PACKAGE); broadcastIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); context.sendBroadcast(broadcastIntent); }
/** * @param action Action to be checked * @param context Calling activity's context * @return true, if provisioning is allowed for corresponding action */ @TargetApi(Build.VERSION_CODES.N) public static boolean isProvisioningAllowed(Context context, String action) { if (BuildCompat.isAtLeastN()) { DevicePolicyManager dpm = (DevicePolicyManager) context .getSystemService(Context.DEVICE_POLICY_SERVICE); return dpm.isProvisioningAllowed(action); } else { if (ACTION_PROVISION_MANAGED_DEVICE.equals(action)) { return (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) ? isDeviceUnprovisionedAndNoDeviceOwner(context) : false; } if (ACTION_PROVISION_MANAGED_PROFILE.equals(action)) { return true; } return false; } }
public static void askForAdmin(Activity activity) { ComponentName mComponentName = new ComponentName(activity, AdminReceiver.class); Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName); activity.startActivity(intent); }
public static boolean lockDeviceNow(Context context, Context baseContext) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(baseContext); int lockMethod = prefs.getInt(PreferenceString.LOCK_METHOD, LOCK_METHOD_DEVICE_ADMIN); switch (lockMethod) { case LOCK_METHOD_DEVICE_ADMIN: KeyguardManager keyguardManager = (KeyguardManager) baseContext.getSystemService(Context.KEYGUARD_SERVICE); if (!keyguardManager.inKeyguardRestrictedInputMode()) { DevicePolicyManager dpm = (DevicePolicyManager) baseContext.getSystemService(Context.DEVICE_POLICY_SERVICE); if (dpm.isAdminActive(new ComponentName(baseContext, AdminReceiver.class))) dpm.lockNow(); } return true; case LOCK_METHOD_ROOT: try { KeyguardManager km = (KeyguardManager) baseContext.getSystemService(Context.KEYGUARD_SERVICE); boolean locked = km.inKeyguardRestrictedInputMode(); if (!locked) { // don't lock if already screen off Runtime.getRuntime().exec(new String[]{"su", "-c", "input keyevent 26"}).waitFor(); } return true; } catch (IOException | InterruptedException e) { Toast.makeText(context, "PluckLockEx Root access denied", Toast.LENGTH_SHORT).show(); } case LOCK_METHOD_FAKE: Toast.makeText(context, "PluckLockEx fake lock", Toast.LENGTH_SHORT).show(); return true; } return false; }
public static void checkCameraService(Context context) throws CameraDisabledException, NoCameraException { // Check if device policy has disabled the camera. DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService( Context.DEVICE_POLICY_SERVICE); if (dpm.getCameraDisabled(null)) { throw new CameraDisabledException(); } List<CameraMessage> cameraDatas = getAllCamerasData(false); if(cameraDatas.size() == 0) { throw new NoCameraException(); } }
public static void clearDeviceOwnerApp(Context context) { try { DevicePolicyManager manager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); manager.clearDeviceOwnerApp(context.getPackageName()); } catch (SecurityException e) { e.printStackTrace(); } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); this.deviceAdminComponentName = new ComponentName(this, SecureNoteDeviceAdminReceiver.class); super.setContentView(R.layout.secure_note); this.noteText = (EditText) super.findViewById(R.id.note_text); this.loadButton = (Button) super.findViewById(R.id.load_button); this.saveButton = (Button) super.findViewById(R.id.save_button); this.closeButton = (Button) super.findViewById(R.id.close_button); this.loadButton.setOnClickListener(this); this.saveButton.setOnClickListener(this); this.closeButton.setOnClickListener(this); this.noteText.addTextChangedListener(this); this.password = savedInstanceState == null ? null : savedInstanceState .getString(PASSWORD_KEY); if (this.isDeviceAdminEnabled()) { if (this.noteText.length() == 0) { if (this.isSecureNoteFilePresent()) { this.saveButton.setVisibility(View.GONE); this.noteText.setEnabled(false); this.getPassword(GET_PASSWORD_FOR_LOAD, false); } else { this.loadButton.setVisibility(View.GONE); this.saveButton.setEnabled(false); } } else { this.loadButton.setVisibility(View.GONE); } } }
private boolean enableDeviceAdmin() { if (this.isDeviceAdminEnabled()) { Log.d(TAG, "Device Admin is already active!"); return true; } else { Log.d(TAG, "Device Admin is not active. Requesting it to be enabled"); Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, this.deviceAdminComponentName); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, super.getText(R.string.device_admin_explanation)); super.startActivityForResult(intent, ENABLE_DEVICE_ADMIN_REQUEST); return false; } }
private boolean ensureDeviceAdminPasswordIsSufficient() { this.devicePolicyManager.setPasswordQuality(deviceAdminComponentName, DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC); this.devicePolicyManager.setPasswordMinimumLength(deviceAdminComponentName, 4); this.devicePolicyManager.setMaximumTimeToLock(deviceAdminComponentName, 10000); if (this.devicePolicyManager.isActivePasswordSufficient()) { Log.d(TAG, "Active password is sufficient"); return true; } else { Log.d(TAG, "Active device admin password is insufficient. Setting new password."); super.startActivityForResult(new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD), SET_DEVICE_ADMIN_PASSWORD_REQUEST); return false; } }