private void disableUnusableTimeouts(ListPreference screenTimeoutPreference) {
   final DevicePolicyManager dpm =
       (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
   final long maxTimeout = dpm != null ? dpm.getMaximumTimeToLock(null) : 0;
   if (maxTimeout == 0) {
     return; // policy not enforced
   }
   final CharSequence[] entries = screenTimeoutPreference.getEntries();
   final CharSequence[] values = screenTimeoutPreference.getEntryValues();
   ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
   ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
   for (int i = 0; i < values.length; i++) {
     long timeout = Long.parseLong(values[i].toString());
     if (timeout <= maxTimeout) {
       revisedEntries.add(entries[i]);
       revisedValues.add(values[i]);
     }
   }
   if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
     screenTimeoutPreference.setEntries(
         revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
     screenTimeoutPreference.setEntryValues(
         revisedValues.toArray(new CharSequence[revisedValues.size()]));
     final int userPreference = Integer.parseInt(screenTimeoutPreference.getValue());
     if (userPreference <= maxTimeout) {
       screenTimeoutPreference.setValue(String.valueOf(userPreference));
     } else {
       // There will be no highlighted selection since nothing in the list matches
       // maxTimeout. The user can still select anything less than maxTimeout.
       // TODO: maybe append maxTimeout to the list and mark selected.
     }
   }
   screenTimeoutPreference.setEnabled(revisedEntries.size() > 0);
 }
 /**
  * If we are not the active device admin, try to become so.
  *
  * <p>Also checks for any policies that we have added during the lifetime of this app. This
  * catches the case where the user granted an earlier (smaller) set of policies but an app upgrade
  * requires that new policies be granted.
  *
  * @return true if we are already active, false if we are not
  */
 public boolean isActiveAdmin() {
   DevicePolicyManager dpm = getDPM();
   return dpm.isAdminActive(mAdminName)
       && dpm.hasGrantedPolicy(mAdminName, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
       && dpm.hasGrantedPolicy(mAdminName, DeviceAdminInfo.USES_ENCRYPTED_STORAGE)
       && dpm.hasGrantedPolicy(mAdminName, DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
 }
    /**
     * Invokes an activity to change the user's pattern, password or PIN based on given quality and
     * minimum quality specified by DevicePolicyManager. If quality is {@link
     * DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, password is cleared.
     *
     * @param quality the desired quality. Ignored if DevicePolicyManager requires more security
     * @param disabled whether or not to show LockScreen at all. Only meaningful when quality is
     *     {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}
     */
    void updateUnlockMethodAndFinish(int quality, boolean disabled) {
      // Sanity check. We should never get here without confirming user's existing password.
      if (!mPasswordConfirmed) {
        throw new IllegalStateException("Tried to update password without confirming it");
      }

      final boolean isFallback =
          getActivity()
              .getIntent()
              .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);

      quality = upgradeQuality(quality, null);

      if (quality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC) {
        int minLength = mDPM.getPasswordMinimumLength(null);
        if (minLength < MIN_PASSWORD_LENGTH) {
          minLength = MIN_PASSWORD_LENGTH;
        }
        final int maxLength = mDPM.getPasswordMaximumLength(quality);
        Intent intent = new Intent().setClass(getActivity(), ChooseLockPassword.class);
        intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, quality);
        intent.putExtra(ChooseLockPassword.PASSWORD_MIN_KEY, minLength);
        intent.putExtra(ChooseLockPassword.PASSWORD_MAX_KEY, maxLength);
        intent.putExtra(CONFIRM_CREDENTIALS, false);
        intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback);
        if (isFallback) {
          startActivityForResult(intent, FALLBACK_REQUEST);
          return;
        } else {
          mFinishPending = true;
          intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
          startActivity(intent);
        }
      } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
        Intent intent = new Intent(getActivity(), ChooseLockPattern.class);
        intent.putExtra("key_lock_method", "pattern");
        intent.putExtra(CONFIRM_CREDENTIALS, false);
        intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, isFallback);
        if (isFallback) {
          startActivityForResult(intent, FALLBACK_REQUEST);
          return;
        } else {
          mFinishPending = true;
          intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
          startActivity(intent);
        }
      } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) {
        Intent intent = getBiometricSensorIntent();
        mFinishPending = true;
        startActivity(intent);
      } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
        mChooseLockSettingsHelper.utils().clearLock(false);
        mChooseLockSettingsHelper.utils().setLockScreenDisabled(disabled);
        getActivity().setResult(Activity.RESULT_OK);
        finish();
      } else {
        finish();
      }
    }
 /**
  * API: Remote wipe (from server). This is final, there is no confirmation. It will only return to
  * the caller if there is an unexpected failure. The wipe includes external storage.
  */
 public void remoteWipe() {
   DevicePolicyManager dpm = getDPM();
   if (dpm.isAdminActive(mAdminName)) {
     dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);
   } else {
     LogUtils.d(Logging.LOG_TAG, "Could not remote wipe because not device admin.");
   }
 }
 /**
  * 锁定屏幕
  *
  * @return
  */
 public boolean lockScreen(Context context) {
   if (isActive()) {
     String password = SafeSharedpreference.getString(context, ConstConfig.LOCKSCREEN_PWD);
     policyManager.lockNow();
     if (!password.equals("")) {
       policyManager.resetPassword(password, 0);
     }
     return true;
   }
   return false;
 }
 @TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
 private static void throwIfCameraDisabled(Activity activity) throws CameraDisabledException {
   // Check if device policy has disabled the camera.
   if (ApiHelper.HAS_GET_CAMERA_DISABLED) {
     DevicePolicyManager dpm =
         (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
     if (dpm.getCameraDisabled(null)) {
       throw new CameraDisabledException();
     }
   }
 }
 public void onClick(View v) {
   // TODO Auto-generated method stub
   devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
   if (devicePolicyManager.isAdminActive(Dar.getCn(this))) {
     devicePolicyManager.lockNow();
   } else {
     Intent intent = new Intent("android.intent.action.oneKeyLock");
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(intent);
   }
 }
 public void testSetBluetoothContactSharingDisabled_setterAndGetter() {
   mDevicePolicyManager.setBluetoothContactSharingDisabled(
       BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, false);
   assertFalse(
       mDevicePolicyManager.getBluetoothContactSharingDisabled(
           BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT));
   mDevicePolicyManager.setBluetoothContactSharingDisabled(
       BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT, true);
   assertTrue(
       mDevicePolicyManager.getBluetoothContactSharingDisabled(
           BaseManagedProfileTest.ADMIN_RECEIVER_COMPONENT));
 }
Exemple #9
0
  private String getMiscInfos() {
    String result = "<table>";

    // admins
    {
      DevicePolicyManager dPM =
          (DevicePolicyManager) _context.getSystemService(Context.DEVICE_POLICY_SERVICE);
      String admins = "";

      if (dPM == null) {
        admins = "<li>No Device Policy Manager support.";
      } else if (dPM.getActiveAdmins() == null || dPM.getActiveAdmins().size() == 0) {
        admins = "<li>no active device admins.";
      } else {
        for (ComponentName name : dPM.getActiveAdmins()) {
          admins += "\r\n<li>" + name.toShortString();
        }
      }
      result += "\r\n<tr><td>List of device admin</td><td><ul>" + admins + "</ul></td></tr>\r\n";
    }

    {
      result +=
          "\r\n<tr><td>Android ID</td><td><ul><li>"
              + Secure.getString(_context.getContentResolver(), Secure.ANDROID_ID)
              + "</ul></td></tr>\r\n";
    }

    {
      result += "\r\n<tr><td>Configuration</td><td><ul>";

      Configuration config = _context.getResources().getConfiguration();
      for (Field field : Configuration.class.getDeclaredFields()) {
        try {
          // discard constants
          if (field.get(config) != null && !field.getName().toUpperCase().equals(field.getName())) {
            result += "\r\n<li>" + field.getName() + ": " + field.get(config).toString();
          }
        } catch (IllegalAccessException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IllegalArgumentException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      result += "</ul></td></tr>\r\n";
    }

    result += "</table>";

    return result;
  }
Exemple #10
0
  private void onLock() {
    boolean active = manger.isAdminActive(componentName);
    if (active) {
      manger.lockNow();

    } else {
      Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
      intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
      startActivityForResult(intent, 0);
      manger.lockNow();
    }
  }
 private boolean isActiveDeviceAdmin(String packageName, int userId) {
   DevicePolicyManager dpm = getContext().getSystemService(DevicePolicyManager.class);
   if (dpm == null) return false;
   List<ComponentName> components = dpm.getActiveAdminsAsUser(userId);
   if (components == null) return false;
   final int size = components.size();
   for (int i = 0; i < size; i++) {
     if (components.get(i).getPackageName().equals(packageName)) {
       return true;
     }
   }
   return false;
 }
  /**
   * Revokes device encrypt policy on the device (Device external storage encryption).
   *
   * @param operation - Operation object.
   */
  private void revokeEncryptPolicy(org.wso2.emm.agent.beans.Operation operation) {

    boolean encryptStatus =
        (devicePolicyManager.getStorageEncryptionStatus()
                != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED
            && (devicePolicyManager.getStorageEncryptionStatus()
                    == devicePolicyManager.ENCRYPTION_STATUS_ACTIVE
                || devicePolicyManager.getStorageEncryptionStatus()
                    == devicePolicyManager.ENCRYPTION_STATUS_ACTIVATING));

    if (operation.isEnabled() && encryptStatus) {
      devicePolicyManager.setStorageEncryption(deviceAdmin, false);
    }
  }
    void updatePolicies() {
      SharedPreferences prefs = getSamplePreferences(this);
      final int pwQuality =
          prefs.getInt(PREF_PASSWORD_QUALITY, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
      final int pwLength = prefs.getInt(PREF_PASSWORD_LENGTH, 0);
      final int maxFailedPw = prefs.getInt(PREF_MAX_FAILED_PW, 0);

      boolean active = mDPM.isAdminActive(mDeviceAdminSample);
      if (active) {
        mDPM.setPasswordQuality(mDeviceAdminSample, pwQuality);
        mDPM.setPasswordMinimumLength(mDeviceAdminSample, pwLength);
        mDPM.setMaximumFailedPasswordsForWipe(mDeviceAdminSample, maxFailedPw);
      }
    }
Exemple #14
0
  /**
   * Clear device password.
   *
   * @param code - Operation code.
   * @param requestMode - Request mode(Normal mode or policy bundle mode).
   */
  public void clearPassword(String code) {
    ComponentName demoDeviceAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class);
    resultBuilder.build(code);

    devicePolicyManager.setPasswordQuality(
        demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
    devicePolicyManager.setPasswordMinimumLength(demoDeviceAdmin, DEFAULT_PASSWORD_LENGTH);
    devicePolicyManager.resetPassword(
        resources.getString(R.string.shared_pref_default_string),
        DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
    devicePolicyManager.lockNow();
    devicePolicyManager.setPasswordQuality(
        demoDeviceAdmin, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
  }
 public void onClick(View v) {
   if (mAM.isUserAMonkey()) {
     // Don't trust monkeys to do the right thing!
     AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this);
     builder.setMessage("You can't lock my screen because you are a monkey!");
     builder.setPositiveButton("I admit defeat", null);
     builder.show();
     return;
   }
   boolean active = mDPM.isAdminActive(mDeviceAdminSample);
   if (active) {
     mDPM.lockNow();
   }
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate");
    mainContext = this.getApplicationContext();
    Settings.System.putInt(
        getContentResolver(),
        Settings.System.SCREEN_OFF_TIMEOUT,
        0); // as soon as system will allow
    setContentView(R.layout.activity_main_screen);

    powerState = new PowerState();
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    crashHandler = new CrashHandler();
    // Thread.setDefaultUncaughtExceptionHandler(crashHandler);

    if (MainActivity.lastActionTime == 0)
      MainActivity.lastActionTime = SystemClock.elapsedRealtime();

    if (devicePolicyManager == null) {
      devicePolicyManager =
          (DevicePolicyManager) this.getSystemService(Activity.DEVICE_POLICY_SERVICE);
      IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
      filter.addCategory(Intent.CATEGORY_HOME);
      filter.addCategory(Intent.CATEGORY_DEFAULT);
      devicePolicyManager.addPersistentPreferredActivity(
          DeviceOwnerReceiver.getComponentName(this),
          filter,
          DeviceOwnerReceiver.getComponentName(this));
      String[] packages = {this.getPackageName()};
      devicePolicyManager.setLockTaskPackages(DeviceOwnerReceiver.getComponentName(this), packages);
    }

    startService(new Intent(this, ActiveNotification.class));
    sendBroadcast(new Intent(TaskManager.INIT_INTENT));

    getWindow()
        .getDecorView()
        .setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

    if (devicePolicyManager.isLockTaskPermitted(getPackageName())) startLockTask();
  }
Exemple #17
0
  /**
   * Encrypt/Decrypt device storage.
   *
   * @param code - Operation code.
   * @param data - Data required(Encryption enable/disable switch).
   * @param requestMode - Request mode(Normal mode or policy bundle mode).
   */
  public void encryptStorage(String code, String data) {
    boolean doEncrypt = true;
    try {
      JSONObject encryptData = new JSONObject(data);
      if (!encryptData.isNull(resources.getString(R.string.intent_extra_function))
          && encryptData
              .get(resources.getString(R.string.intent_extra_function))
              .toString()
              .equalsIgnoreCase(resources.getString(R.string.intent_extra_encrypt))) {
        doEncrypt = true;
      } else if (!encryptData.isNull(resources.getString(R.string.intent_extra_function))
          && encryptData
              .get(resources.getString(R.string.intent_extra_function))
              .toString()
              .equalsIgnoreCase(resources.getString(R.string.intent_extra_decrypt))) {
        doEncrypt = false;
      } else if (!encryptData.isNull(resources.getString(R.string.intent_extra_function))) {
        doEncrypt =
            Boolean.parseBoolean(
                encryptData.get(resources.getString(R.string.intent_extra_function)).toString());
      }
    } catch (JSONException e) {
      Log.e(TAG, "Invalid JSON format." + e);
    }

    ComponentName admin = new ComponentName(context, AgentDeviceAdminReceiver.class);

    if (doEncrypt
        && devicePolicyManager.getStorageEncryptionStatus()
            != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED
        && (devicePolicyManager.getStorageEncryptionStatus()
            == DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE)) {

      devicePolicyManager.setStorageEncryption(admin, doEncrypt);
      Intent intent = new Intent(DevicePolicyManager.ACTION_START_ENCRYPTION);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      context.startActivity(intent);

    } else if (!doEncrypt
        && devicePolicyManager.getStorageEncryptionStatus()
            != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED
        && (devicePolicyManager.getStorageEncryptionStatus()
                == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
            || devicePolicyManager.getStorageEncryptionStatus()
                == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING)) {

      devicePolicyManager.setStorageEncryption(admin, doEncrypt);
    }

    String status;
    if (devicePolicyManager.getStorageEncryptionStatus()
        != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) {
      status = resources.getString(R.string.shared_pref_default_status);
    } else {
      status = resources.getString(R.string.shared_pref_false_status);
    }

    resultBuilder.build(code, status);
  }
 public void onClick(View v) {
   if (mAM.isUserAMonkey()) {
     // Don't trust monkeys to do the right thing!
     AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this);
     builder.setMessage("You can't reset my password because you are a monkey!");
     builder.setPositiveButton("I admit defeat", null);
     builder.show();
     return;
   }
   boolean active = mDPM.isAdminActive(mDeviceAdminSample);
   if (active) {
     mDPM.resetPassword(
         mPassword.getText().toString(), DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
   }
 }
  @Override
  public boolean onPreferenceChange(Preference preference, Object newValue) {
    if (newValue == null) return false;

    boolean current = mDPM.isAdminActive(mDeviceAdminRcvr);
    boolean now = (Boolean) newValue;
    if (current == now) return true;
    else if (now) {
      Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
      intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminRcvr);
      mActivity.startActivityForResult(intent, SettingsActivity.ADMIN_RESULT);
    } else mDPM.removeActiveAdmin(mDeviceAdminRcvr);

    return true;
  }
 public void onClick(View v) {
   if (mAM.isUserAMonkey()) {
     // Don't trust monkeys to do the right thing!
     AlertDialog.Builder builder = new AlertDialog.Builder(Controller.this);
     builder.setMessage("You can't lock my screen because you are a monkey!");
     builder.setPositiveButton("I admit defeat", null);
     builder.show();
     return;
   }
   boolean active = mDPM.isAdminActive(mDeviceAdminSample);
   if (active) {
     long timeMs = 1000L * Long.parseLong(mTimeout.getText().toString());
     mDPM.setMaximumTimeToLock(mDeviceAdminSample, timeMs);
   }
 }
 @Override
 protected void tearDown() throws Exception {
   if (mDevicePolicyManager.isDeviceOwnerApp(PACKAGE_NAME)
       || mDevicePolicyManager.isProfileOwnerApp(PACKAGE_NAME)) {
     mDevicePolicyManager.setUninstallBlocked(getWho(), TEST_APP_PKG, false);
   }
   try {
     mContext.unregisterReceiver(mBroadcastReceiver);
   } catch (IllegalArgumentException e) {
     // ignore
   }
   if (mSession != null) {
     mSession.abandon();
   }
   super.tearDown();
 }
Exemple #22
0
  /**
   * Disable/Enable device camera.
   *
   * @param code - Operation code.
   * @param data - Data required(Camera enable/disable switch).
   * @param requestMode - Request mode(Normal mode or policy bundle mode).
   */
  public void disableCamera(String code, String data) {
    boolean camFunc = false;
    try {
      JSONObject inputData = new JSONObject(data);
      if (!inputData.isNull(resources.getString(R.string.intent_extra_function))
          && inputData
              .get(resources.getString(R.string.intent_extra_function))
              .toString()
              .equalsIgnoreCase(resources.getString(R.string.intent_extra_enable))) {
        camFunc = false;
      } else if (!inputData.isNull(resources.getString(R.string.intent_extra_function))
          && inputData
              .get(resources.getString(R.string.intent_extra_function))
              .toString()
              .equalsIgnoreCase(resources.getString(R.string.intent_extra_disable))) {
        camFunc = true;
      } else if (!inputData.isNull(resources.getString(R.string.intent_extra_function))) {
        camFunc =
            Boolean.parseBoolean(
                inputData.get(resources.getString(R.string.intent_extra_function)).toString());
      }

      ComponentName cameraAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class);

      resultBuilder.build(code);

      devicePolicyManager.setCameraDisabled(cameraAdmin, camFunc);
    } catch (JSONException e) {
      Log.e(TAG, "Invalid JSON format." + e);
    }
  }
Exemple #23
0
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow()
          .setFlags(
              WindowManager.LayoutParams.FLAG_FULLSCREEN,
              WindowManager.LayoutParams.FLAG_FULLSCREEN);
      setContentView(R.layout.activity_show);
      layout = (GridLayout) findViewById(R.id.container);
      imageButton = (ImageButton) findViewById(R.id.imageButton);
      imageButton.setOnTouchListener(new layoutOntouchListener());

      arcMenu = (ArcMenu) findViewById(R.id.arc_menu);
      initArcMenu(arcMenu, ITEM_DRAWABLES);

      componentName = new ComponentName(this, ShowActivity.class);

      dpm = (DevicePolicyManager) getSystemService("device_policy");

      service = new Intent(this, ScreenoffService.class);
      startService(service);

      if (!dpm.isAdminActive(componentName)) {
        getAdmin();
      }
      return;
    }
Exemple #24
0
  /**
   * Wipe the device.
   *
   * @param code - Operation code.
   * @param data - Data required by the operation(PIN).
   */
  public void wipeDevice(String code, String data) {
    String inputPin;
    String savedPin = Preference.getString(context, resources.getString(R.string.shared_pref_pin));

    try {
      JSONObject wipeKey = new JSONObject(data);
      inputPin = (String) wipeKey.get(resources.getString(R.string.shared_pref_pin));
      String status;
      if (inputPin.trim().equals(savedPin.trim())) {
        status = resources.getString(R.string.shared_pref_default_status);
      } else {
        status = resources.getString(R.string.shared_pref_false_status);
      }

      resultBuilder.build(code, status);

      if (inputPin.trim().equals(savedPin.trim())) {
        Toast.makeText(context, resources.getString(R.string.toast_message_wipe), Toast.LENGTH_LONG)
            .show();
        try {
          Thread.sleep(PRE_WIPE_WAIT_TIME);
        } catch (InterruptedException e) {
          Log.e(TAG, "Wipe pause interrupted :" + e.toString());
        }
        devicePolicyManager.wipeData(ACTIVATION_REQUEST);
      } else {
        Toast.makeText(
                context, resources.getString(R.string.toast_message_wipe_failed), Toast.LENGTH_LONG)
            .show();
      }
    } catch (JSONException e) {
      Log.e(TAG, "Invalid JSON format." + e);
    }
  }
  private void updateUI() {
    LockMediator lm = LockMediator.getInstance(getActivity());
    boolean isActive = dpm.isAdminActive(cn);
    disabledWarning.setVisibility(isActive ? View.GONE : View.VISIBLE);
    passwordWarning.setVisibility(
        CryptoUtils.isPasswordSaved(getActivity()) ? View.GONE : View.VISIBLE);
    warning.setVisibility(isActive && areOtherAdminsSet() ? View.VISIBLE : View.GONE);
    toggle.setChecked(isActive);

    if (!CryptoUtils.isPasswordSaved(getActivity())) {
      pinPasswordStatus.setText(R.string.unset);
      pinPasswordStatus.setTextColor(COLOR_WARNING);
    } else {
      boolean isPIN = CryptoUtils.isPIN(getActivity());
      pinPasswordStatus.setText(isPIN ? R.string.pin : R.string.password);
      pinPasswordStatus.setTextColor(COLOR_OK);
    }
    LockMediator.Status status = lm.getLockMediatorStatus();
    boolean isSecure = status.security || !isActive;

    lockscreenStatus.setText(isSecure ? R.string.enabled : R.string.bypassed);
    lockscreenStatus.setTextColor(isSecure ? COLOR_OK : COLOR_INFO);

    keyguardStatus.setText(R.string.enabled);
    keyguardStatus.setTextColor(COLOR_OK);
    getActivity().sendBroadcast(new Intent(KeyguardService.ACTION_PING));
  }
 void updateButtonStates() {
   boolean active = mDPM.isAdminActive(mDeviceAdminSample);
   if (active) {
     mEnableButton.setEnabled(false);
     mDisableButton.setEnabled(true);
     mPasswordQuality.setEnabled(true);
     mPasswordLength.setEnabled(true);
     mSetPasswordButton.setEnabled(true);
     mPassword.setEnabled(true);
     mResetPasswordButton.setEnabled(true);
     mForceLockButton.setEnabled(true);
     mWipeDataButton.setEnabled(true);
     mWipeAllDataButton.setEnabled(true);
   } else {
     mEnableButton.setEnabled(true);
     mDisableButton.setEnabled(false);
     mPasswordQuality.setEnabled(false);
     mPasswordLength.setEnabled(false);
     mSetPasswordButton.setEnabled(false);
     mPassword.setEnabled(false);
     mResetPasswordButton.setEnabled(false);
     mForceLockButton.setEnabled(false);
     mWipeDataButton.setEnabled(false);
     mWipeAllDataButton.setEnabled(false);
   }
 }
  @Override
  public void onResume() {
    super.onResume();

    if (mDpm.getMaximumTimeToLock(null) > 0) {
      // A DeviceAdmin has specified a maximum time until the device
      // will lock...  in this case we can't allow the user to turn
      // on "stay awake when plugged in" because that would defeat the
      // restriction.
      mDisabledPrefs.add(mKeepScreenOn);
    } else {
      mDisabledPrefs.remove(mKeepScreenOn);
    }

    final ContentResolver cr = getActivity().getContentResolver();
    mLastEnabledState =
        Settings.Global.getInt(cr, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
    mEnabledSwitch.setChecked(mLastEnabledState);
    setPrefsEnabledState(mLastEnabledState);

    if (mHaveDebugSettings && !mLastEnabledState) {
      // Overall debugging is disabled, but there are some debug
      // settings that are enabled.  This is an invalid state.  Switch
      // to debug settings being enabled, so the user knows there is
      // stuff enabled and can turn it all off if they want.
      Settings.Global.putInt(
          getActivity().getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
      mLastEnabledState = true;
      mEnabledSwitch.setChecked(mLastEnabledState);
      setPrefsEnabledState(mLastEnabledState);
    }

    updateKillAppLongpressBackOptions();
  }
 @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();
     }
   }
 }
 /**
  * Save a lock pattern.
  *
  * @param pattern The new pattern to save.
  * @param isFallback Specifies if this is a fallback to biometric weak
  */
 public void saveLockPattern(List<LockPatternView.Cell> pattern, boolean isFallback) {
   // Compute the hash
   final byte[] hash = LockPatternUtils.patternToHash(pattern);
   try {
     // Write the hash to file
     RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "rw");
     // Truncate the file if pattern is null, to clear the lock
     if (pattern == null) {
       raf.setLength(0);
     } else {
       raf.write(hash, 0, hash.length);
     }
     raf.close();
     DevicePolicyManager dpm = getDevicePolicyManager();
     KeyStore keyStore = KeyStore.getInstance();
     if (pattern != null) {
       keyStore.password(patternToString(pattern));
       setBoolean(PATTERN_EVER_CHOSEN_KEY, true);
       if (!isFallback) {
         deleteGallery();
         setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
         dpm.setActivePasswordState(
             DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, pattern.size(), 0, 0, 0, 0, 0, 0);
       } else {
         setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK);
         setLong(PASSWORD_TYPE_ALTERNATE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
         finishBiometricWeak();
         dpm.setActivePasswordState(
             DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK, 0, 0, 0, 0, 0, 0, 0);
       }
     } else {
       if (keyStore.isEmpty()) {
         keyStore.reset();
       }
       dpm.setActivePasswordState(
           DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0);
     }
   } catch (FileNotFoundException fnfe) {
     // Cant do much, unless we want to fail over to using the settings
     // provider
     Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
   } catch (IOException ioe) {
     // Cant do much
     Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
   }
 }
Exemple #30
0
 private boolean isCameraDisabledByDpm() {
   final DevicePolicyManager dpm =
       (DevicePolicyManager) getContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
   if (dpm != null) {
     try {
       final int userId = ActivityManagerNative.getDefault().getCurrentUser().id;
       final int disabledFlags = dpm.getKeyguardDisabledFeatures(null, userId);
       final boolean disabledBecauseKeyguardSecure =
           (disabledFlags & DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA) != 0
               && KeyguardTouchDelegate.getInstance(getContext()).isSecure();
       return dpm.getCameraDisabled(null) || disabledBecauseKeyguardSecure;
     } catch (RemoteException e) {
       Log.e(TAG, "Can't get userId", e);
     }
   }
   return false;
 }