Example usage for android.content Context DEVICE_POLICY_SERVICE

List of usage examples for android.content Context DEVICE_POLICY_SERVICE

Introduction

In this page you can find the example usage for android.content Context DEVICE_POLICY_SERVICE.

Prototype

String DEVICE_POLICY_SERVICE

To view the source code for android.content Context DEVICE_POLICY_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.admin.DevicePolicyManager for working with global device policy management.

Usage

From source file:ro.ciubex.keepscreenlock.MainApplication.java

/**
 * Called when the application is starting, before any activity, service,
 * or receiver objects (excluding content providers) have been created.
 *//*from ww w.j  a v a 2  s  .  c  o m*/
@Override
public void onCreate() {
    super.onCreate();
    MainApplication.isEmulator = String.valueOf(Build.PRODUCT).startsWith("sdk");
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mDeviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    mComponentName = new ComponentName(this, AdminPermissionReceiver.class);
    mSdkInt = android.os.Build.VERSION.SDK_INT;
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    initLocale();
    checkKeepScreenLockReceiver();
}

From source file:de.schildbach.wallet.ui.ReportIssueDialogFragment.java

private static void appendDeviceInfo(final Appendable report, final Context context) throws IOException {
    final Resources res = context.getResources();
    final android.content.res.Configuration config = res.getConfiguration();
    final ActivityManager activityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    final DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context
            .getSystemService(Context.DEVICE_POLICY_SERVICE);

    report.append("Device Model: " + Build.MODEL + "\n");
    report.append("Android Version: " + Build.VERSION.RELEASE + "\n");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        report.append("Android security patch level: ").append(Build.VERSION.SECURITY_PATCH).append("\n");
    report.append("ABIs: ")
            .append(Joiner.on(", ").skipNulls()
                    .join(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? supportedAbisLollipop()
                            : supportedAbisKitKat()))
            .append("\n");
    report.append("Board: " + Build.BOARD + "\n");
    report.append("Brand: " + Build.BRAND + "\n");
    report.append("Device: " + Build.DEVICE + "\n");
    report.append("Display: " + Build.DISPLAY + "\n");
    report.append("Finger Print: " + Build.FINGERPRINT + "\n");
    report.append("Host: " + Build.HOST + "\n");
    report.append("ID: " + Build.ID + "\n");
    report.append("Product: " + Build.PRODUCT + "\n");
    report.append("Tags: " + Build.TAGS + "\n");
    report.append("Time: " + Build.TIME + "\n");
    report.append("Type: " + Build.TYPE + "\n");
    report.append("User: " + Build.USER + "\n");
    report.append("Configuration: " + config + "\n");
    report.append("Screen Layout: size "
            + (config.screenLayout & android.content.res.Configuration.SCREENLAYOUT_SIZE_MASK) + " long "
            + (config.screenLayout & android.content.res.Configuration.SCREENLAYOUT_LONG_MASK) + "\n");
    report.append("Display Metrics: " + res.getDisplayMetrics() + "\n");
    report.append(//from w  ww. j  ava2s .c o m
            "Memory Class: " + activityManager.getMemoryClass() + "/" + activityManager.getLargeMemoryClass()
                    + (activityManager.isLowRamDevice() ? " (low RAM device)" : "") + "\n");
    report.append("Storage Encryption Status: " + devicePolicyManager.getStorageEncryptionStatus() + "\n");
    report.append("Bluetooth MAC: " + bluetoothMac() + "\n");
    report.append("Runtime: ").append(System.getProperty("java.vm.name")).append(" ")
            .append(System.getProperty("java.vm.version")).append("\n");
}

From source file:com.android.cts.verifier.managedprovisioning.ByodHelperActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        Log.w(TAG, "Restored state");
        mOriginalSettings = savedInstanceState.getBundle(ORIGINAL_SETTINGS_NAME);
    } else {/*  w  w w .  jav  a  2  s.  c  o  m*/
        mOriginalSettings = new Bundle();
    }

    mAdminReceiverComponent = new ComponentName(this, DeviceAdminTestReceiver.class.getName());
    mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent = getIntent();
    String action = intent.getAction();
    Log.d(TAG, "ByodHelperActivity.onCreate: " + action);

    // we are explicitly started by {@link DeviceAdminTestReceiver} after a successful provisioning.
    if (action.equals(ACTION_PROFILE_PROVISIONED)) {
        // Jump back to CTS verifier with result.
        Intent response = new Intent(ACTION_PROFILE_OWNER_STATUS);
        response.putExtra(EXTRA_PROVISIONED, isProfileOwner());
        startActivityInPrimary(response);
        // Queried by CtsVerifier in the primary side using startActivityForResult.
    } else if (action.equals(ACTION_QUERY_PROFILE_OWNER)) {
        Intent response = new Intent();
        response.putExtra(EXTRA_PROVISIONED, isProfileOwner());
        setResult(RESULT_OK, response);
        // Request to delete work profile.
    } else if (action.equals(ACTION_REMOVE_MANAGED_PROFILE)) {
        if (isProfileOwner()) {
            Log.d(TAG, "Clearing cross profile intents");
            mDevicePolicyManager.clearCrossProfileIntentFilters(mAdminReceiverComponent);
            mDevicePolicyManager.wipeData(0);
            showToast(R.string.provisioning_byod_profile_deleted);
        }
    } else if (action.equals(ACTION_INSTALL_APK)) {
        boolean allowNonMarket = intent.getBooleanExtra(EXTRA_ALLOW_NON_MARKET_APPS, false);
        boolean wasAllowed = getAllowNonMarket();

        // Update permission to install non-market apps
        setAllowNonMarket(allowNonMarket);
        mOriginalSettings.putBoolean(INSTALL_NON_MARKET_APPS, wasAllowed);

        // Request to install a non-market application- easiest way is to reinstall ourself
        final Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE)
                .setData(Uri.parse("package:" + getPackageName()))
                .putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true).putExtra(Intent.EXTRA_RETURN_RESULT, true);
        startActivityForResult(installIntent, REQUEST_INSTALL_PACKAGE);

        // Not yet ready to finish- wait until the result comes back
        return;
        // Queried by CtsVerifier in the primary side using startActivityForResult.
    } else if (action.equals(ACTION_CHECK_INTENT_FILTERS)) {
        final boolean intentFiltersSetForManagedIntents = new IntentFiltersTestHelper(this)
                .checkCrossProfileIntentFilters(IntentFiltersTestHelper.FLAG_INTENTS_FROM_MANAGED);
        setResult(intentFiltersSetForManagedIntents ? RESULT_OK : RESULT_FAILED, null);
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_IMAGE)) {
        // We need the camera permission to send the image capture intent.
        grantCameraPermissionToSelf();
        Intent captureImageIntent = getCaptureImageIntent();
        Pair<File, Uri> pair = getTempUri("image.jpg");
        mImageFile = pair.first;
        mImageUri = pair.second;
        captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        if (captureImageIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureImageIntent, REQUEST_IMAGE_CAPTURE);
        } else {
            Log.e(TAG, "Capture image intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT)
            || action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITHOUT_EXTRA_OUTPUT)) {
        // We need the camera permission to send the video capture intent.
        grantCameraPermissionToSelf();
        Intent captureVideoIntent = getCaptureVideoIntent();
        int videoCaptureRequestId;
        if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT)) {
            mVideoUri = getTempUri("video.mp4").second;
            captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri);
            videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITH_EXTRA_OUTPUT;
        } else {
            videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITHOUT_EXTRA_OUTPUT;
        }
        if (captureVideoIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureVideoIntent, videoCaptureRequestId);
        } else {
            Log.e(TAG, "Capture video intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_AUDIO)) {
        Intent captureAudioIntent = getCaptureAudioIntent();
        if (captureAudioIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureAudioIntent, REQUEST_AUDIO_CAPTURE);
        } else {
            Log.e(TAG, "Capture audio intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (ACTION_KEYGUARD_DISABLED_FEATURES.equals(action)) {
        final int value = intent.getIntExtra(EXTRA_PARAMETER_1,
                DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE);
        mDevicePolicyManager.setKeyguardDisabledFeatures(mAdminReceiverComponent, value);
    } else if (ACTION_LOCKNOW.equals(action)) {
        mDevicePolicyManager.lockNow();
        setResult(RESULT_OK);
    } else if (action.equals(ACTION_TEST_NFC_BEAM)) {
        Intent testNfcBeamIntent = new Intent(this, NfcTestActivity.class);
        testNfcBeamIntent.putExtras(intent);
        startActivity(testNfcBeamIntent);
        finish();
        return;
    } else if (action.equals(ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG)) {
        sendIntentInsideChooser(new Intent(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_PERSONAL));
    } else if (action.equals(ACTION_TEST_APP_LINKING_DIALOG)) {
        mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
        Intent toSend = new Intent(Intent.ACTION_VIEW);
        toSend.setData(Uri.parse("http://com.android.cts.verifier"));
        sendIntentInsideChooser(toSend);
    } else if (action.equals(ACTION_SET_USER_RESTRICTION)) {
        final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1);
        if (restriction != null) {
            mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                    restriction);
        }
    } else if (action.equals(ACTION_CLEAR_USER_RESTRICTION)) {
        final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1);
        if (restriction != null) {
            mDevicePolicyManager.clearUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                    restriction);
        }
    } else if (action.equals(ACTION_BYOD_SET_LOCATION_AND_CHECK_UPDATES)) {
        handleLocationAction();
        return;
    } else if (action.equals(ACTION_NOTIFICATION)) {
        showNotification(Notification.VISIBILITY_PUBLIC);
    } else if (ACTION_NOTIFICATION_ON_LOCKSCREEN.equals(action)) {
        mDevicePolicyManager.lockNow();
        showNotification(Notification.VISIBILITY_PRIVATE);
    } else if (ACTION_CLEAR_NOTIFICATION.equals(action)) {
        mNotificationManager.cancel(NOTIFICATION_ID);
    } else if (ACTION_TEST_SELECT_WORK_CHALLENGE.equals(action)) {
        mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, Color.BLUE);
        mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent,
                getResources().getString(R.string.provisioning_byod_confirm_work_credentials_header));
        startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD));
    } else if (ACTION_LAUNCH_CONFIRM_WORK_CREDENTIALS.equals(action)) {
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        Intent launchIntent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
        startActivity(launchIntent);
    } else if (ACTION_SET_ORGANIZATION_INFO.equals(action)) {
        if (intent.hasExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME)) {
            final String organizationName = intent
                    .getStringExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME);
            mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent, organizationName);
        }
        final int organizationColor = intent.getIntExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_COLOR,
                mDevicePolicyManager.getOrganizationColor(mAdminReceiverComponent));
        mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, organizationColor);
    } else if (ACTION_TEST_PARENT_PROFILE_PASSWORD.equals(action)) {
        startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PARENT_PROFILE_PASSWORD));
    }
    // This activity has no UI and is only used to respond to CtsVerifier in the primary side.
    finish();
}

From source file:org.wso2.emm.agent.services.operation.OperationProcessor.java

private boolean isDeviceAdminActive() {
    DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context
            .getSystemService(Context.DEVICE_POLICY_SERVICE);
    ComponentName cdmDeviceAdmin = new ComponentName(context, AgentDeviceAdminReceiver.class);
    return devicePolicyManager.isAdminActive(cdmDeviceAdmin);
}

From source file:org.durka.hallmonitor.CoreStateManager.java

public void refreshAdminApp() {
    final DevicePolicyManager dpm = (DevicePolicyManager) mAppContext
            .getSystemService(Context.DEVICE_POLICY_SERVICE);
    ComponentName me = new ComponentName(mAppContext, AdminReceiver.class);
    adminApp = dpm.isAdminActive(me);/*from  w ww  . j a  v  a 2s .c om*/
    if (adminApp) {
        Log.d(LOG_TAG, "We are an admin.");
    } else {
        Log.d(LOG_TAG, "We are not an admin so cannot do anything.");
    }
    refreshLockMode();
}

From source file:com.dudu.aios.ui.activity.MainRecordActivity.java

private void initData() {
    log_init = LoggerFactory.getLogger("init.start");
    log_web = LoggerFactory.getLogger("workFlow.webSocket");

    log_init.debug("MainActivity onCreate?...");

    setWeatherAlarm();//from   ww  w .  j  av a 2s. co m

    registerTFlashCardReceiver();

    registerScreenReceiver();

    // ???
    mPolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

    // AdminReceiver  DeviceAdminReceiver
    componentName = new ComponentName(this, AdminReceiver.class);

}

From source file:com.wso2.mobile.mdm.services.Operation.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void revokePolicy() {
    String policy;//  ww w .  j  a  v a2  s . c o  m
    JSONArray jArray = null;
    devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
    ComponentName cameraAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class);
    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);

    try {

        policy = mainPref.getString("policy", "");

        jArray = new JSONArray(policy);
        for (int i = 0; i < jArray.length(); i++) {
            if (jArray.getJSONObject(i) != null) {
                JSONObject policyObj = (JSONObject) jArray.getJSONObject(i);
                if (policyObj.getString("data") != null && policyObj.getString("data") != "") {

                    if (policyObj.getString("code").trim().equals(CommonUtilities.OPERATION_WIFI)) {
                        JSONObject jobj = new JSONObject(policyObj.getString("data"));
                        if (!jobj.isNull("ssid")) {
                            String rev_ssid = (String) jobj.get("ssid");
                            WiFiConfig config = new WiFiConfig(context);
                            config.removeWiFiConfigurationBySSID(rev_ssid);
                        }
                    } else if (policyObj.getString("code").trim()
                            .equals(CommonUtilities.OPERATION_DISABLE_CAMERA)) {
                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                            devicePolicyManager.setCameraDisabled(cameraAdmin, false);
                        }
                    } else if (policyObj.getString("code").trim()
                            .equals(CommonUtilities.OPERATION_ENCRYPT_STORAGE)) {
                        JSONObject jobj = new JSONObject(policyObj.getString("data"));
                        boolean encryptFunc = false;
                        if (!jobj.isNull("function")
                                && jobj.get("function").toString().equalsIgnoreCase("encrypt")) {
                            encryptFunc = true;
                        } else if (!jobj.isNull("function")
                                && jobj.get("function").toString().equalsIgnoreCase("decrypt")) {
                            encryptFunc = false;
                        } else if (!jobj.isNull("function")) {
                            encryptFunc = Boolean.parseBoolean(jobj.get("function").toString());
                        }
                        if (encryptFunc) {
                            if (devicePolicyManager
                                    .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) {
                                if (devicePolicyManager
                                        .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVE
                                        || devicePolicyManager
                                                .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVATING) {
                                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                                        devicePolicyManager.setStorageEncryption(cameraAdmin, false);
                                    }
                                }
                            }
                        }
                    } else if (policyObj.getString("code").trim()
                            .equals(CommonUtilities.OPERATION_PASSWORD_POLICY)) {
                        devicePolicyManager.setPasswordQuality(cameraAdmin,
                                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
                    }
                }
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.afwsamples.testdpc.SetupManagementFragment.java

@TargetApi(Build.VERSION_CODES.O)
private void passAffiliationIds(Intent intent, PersistableBundle adminExtras) {
    ComponentName admin = DeviceAdminReceiver.getComponentName(getActivity());
    DevicePolicyManager dpm = (DevicePolicyManager) getActivity()
            .getSystemService(Context.DEVICE_POLICY_SERVICE);
    List<String> ids = dpm.getAffiliationIds(admin);
    String affiliationId = null;//from  ww w.  j  a  v  a  2s.  c  o m
    if (ids.size() == 0) {
        SecureRandom randomGenerator = new SecureRandom();
        affiliationId = Integer.toString(randomGenerator.nextInt(1000000));
        dpm.setAffiliationIds(admin, Arrays.asList(affiliationId));
    } else {
        affiliationId = ids.get(0);
    }
    adminExtras.putString(LaunchIntentUtil.EXTRA_AFFILIATION_ID, affiliationId);
}

From source file:org.wso2.cdm.agent.services.Operation.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void revokePolicy() {

    JSONArray jArray = null;//ww  w .jav  a 2s  . com
    devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
    ComponentName cameraAdmin = new ComponentName(context, WSO2DeviceAdminReceiver.class);
    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);

    try {

        String policy = mainPref.getString("policy", "");
        Log.e("policy revoke() ", policy);
        //         [{"data":{"function":"Enable"},"code":"508A"},{"data":{"password":"12345"},"code":"526A"}]

        jArray = new JSONArray(policy.trim());
        for (int i = 0; i < jArray.length(); i++) {
            if (jArray.getJSONObject(i) != null) {
                JSONObject policyObj = (JSONObject) jArray.getJSONObject(i);

                if (policyObj.getString("code").trim().equals(CommonUtilities.OPERATION_WIFI)) {
                    JSONObject jobj = new JSONObject(policyObj.getString("data"));
                    if (!jobj.isNull("ssid")) {
                        String rev_ssid = (String) jobj.get("ssid");
                        WiFiConfig config = new WiFiConfig(context);
                        config.removeWiFiConfigurationBySSID(rev_ssid);
                    }
                } else if (policyObj.getString("code").trim()
                        .equals(CommonUtilities.OPERATION_DISABLE_CAMERA)) {
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        devicePolicyManager.setCameraDisabled(cameraAdmin, false);
                    }
                } else if (policyObj.getString("code").trim()
                        .equals(CommonUtilities.OPERATION_ENCRYPT_STORAGE)) {
                    if (policyObj.getString("data") != null && policyObj.getString("data") != "") {
                        JSONObject jobj = new JSONObject(policyObj.getString("data"));
                        boolean encryptFunc = false;
                        if (!jobj.isNull("function")
                                && jobj.get("function").toString().equalsIgnoreCase("encrypt")) {
                            encryptFunc = true;
                        } else if (!jobj.isNull("function")
                                && jobj.get("function").toString().equalsIgnoreCase("decrypt")) {
                            encryptFunc = false;
                        } else if (!jobj.isNull("function")) {
                            encryptFunc = Boolean.parseBoolean(jobj.get("function").toString());
                        }
                        if (encryptFunc) {
                            if (devicePolicyManager
                                    .getStorageEncryptionStatus() != devicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED) {
                                if (devicePolicyManager
                                        .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVE
                                        || devicePolicyManager
                                                .getStorageEncryptionStatus() == devicePolicyManager.ENCRYPTION_STATUS_ACTIVATING) {
                                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                                        devicePolicyManager.setStorageEncryption(cameraAdmin, false);
                                    }
                                }
                            }
                        }
                    }
                } else if (policyObj.getString("code").trim()
                        .equals(CommonUtilities.OPERATION_PASSWORD_POLICY)) {
                    devicePolicyManager.setPasswordQuality(cameraAdmin,
                            DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
                }
                //                     policyObj.getString("code").trim().equals(CommonUtilities.OPERATION_CHANGE_LOCK_CODE)
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.softanalle.scma.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    setContentView(R.layout.activity_main);

    PropertyConfigurator.getConfigurator(this).configure();

    logger.debug("onCreate()");

    pictureButton_ = (Button) findViewById(R.id.pictureButton);
    toggleButton_ = (ToggleButton) findViewById(R.id.powerButton);
    ledIndicator_ = (LedIndicator) findViewById(R.id.ledIndicator1);
    focusButton_ = (Button) findViewById(R.id.focusButton);

    toggleButton_.setEnabled(false);//from w w w  . j  a va 2 s  .  co m
    toggleButton_.setChecked(false);

    // camera stuff

    if (checkCameraHardware(getApplicationContext())) {
        // ok, we have camera
        Log.i(TAG, "Device has camera");
    } else {
        logger.error("Unable to find camera");
        Toast.makeText(getApplicationContext(), "Camera is missing!", Toast.LENGTH_LONG).show();
    }

    FrameLayout tmp = (FrameLayout) findViewById(R.id.camera_preview);

    mPreview = new Preview(this);

    logger.debug("Created Preview -object");
    //Log.d(TAG, "Preview created");

    mPreview.startPreview();
    logger.debug("Preview object started");

    if (tmp == null) {
        logger.debug(TAG + ": Layout IS NULL");
        Toast.makeText(getApplicationContext(), "Layout is NULL: ", Toast.LENGTH_LONG).show();
        //} else {

        //Log.d(TAG, "Layout found");
    }

    if (mPreview != null) {
        logger.debug("Will add preview");
        try {
            tmp.addView(mPreview);
            //tmp.addView(mPreview);
        } catch (Exception e) {
            logger.error("onCreate(): got exception: " + e.toString());
            Toast.makeText(getApplicationContext(), "Got exception: " + e.toString(), Toast.LENGTH_LONG).show();

        }

    } else {
        logger.error("onCreate(): Preview creation FAILED");
    }

    logger.debug("onCreate(): Added preview");

    ledIndicator_.bringToFront();
    toggleButton_.bringToFront();
    pictureButton_.bringToFront();
    focusButton_.bringToFront();

    mPulseWidth = new int[mLedCount];
    mLedState = new boolean[mLedCount];
    mDefaultPulseWidth = new int[mLedCount];
    synchronized (lock_) {
        for (int index = 0; index < mLedCount; index++) {
            mLedState[index] = false;

            mDefaultPulseWidth[index] = defaultPulseWidth;
            //mPulseWidth[index] = mDefaultPulseWidth[index];
        }
    }

    pictureButton_.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            logger.debug("pictureButton.onClick()");
            if (powerState_) {
                // disable buttons -> no error clicks
                pictureButton_.setEnabled(false);
                toggleButton_.setEnabled(false);
                focusButton_.setEnabled(false);
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        // run the picture sequence
                        takeColorSeries();
                    }
                };

                new Thread(runnable).start();
            }
        }
    });

    toggleButton_.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            logger.debug("toggleButton.onClick(" + ((ToggleButton) v).isChecked() + ")");
            // mPreview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
            if (((ToggleButton) v).isChecked()) {
                powerState_ = true;
                pictureButton_.setEnabled(true);
                mLedState[mFocusLedIndex] = true;
                mPulseWidth[mFocusLedIndex] = defaultFocusPulseWidth;
                mCurrentLedIndex = mFocusLedIndex;

                // make sure we don't go to screenlock while working
                /*
                PowerManager pm = (PowerManager) getApplicationContext().getSystemService( Context.POWER_SERVICE );
                wl = pm.newWakeLock(
                      PowerManager.SCREEN_DIM_WAKE_LOCK
                      | PowerManager.ON_AFTER_RELEASE,
                      TAG);               
                wl.acquire();
                */
            } else {
                powerState_ = false;
                pictureButton_.setEnabled(false);
                mShutdown = true;
                mLedState[mFocusLedIndex] = false;

                // release screen un-locker
                //wl.release();

            }
        }
    });

    focusButton_.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            logger.debug("focusButton.onClick()");
            try {
                ledIndicator_.setLedState(LED_INDEX_FOCUS, true);
                Thread.sleep(10);
                focusCamera();
                Thread.sleep(10);
                ledIndicator_.setLedState(LED_INDEX_FOCUS, false);
            } catch (Exception e) {

            }
        }
    });

    pictureButton_.setEnabled(false);

    logger.debug("onCreate(): controls initialized");

    Log.d(TAG, "onCreate'd");
    mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    Log.d(TAG, "  getCameraDisabled(): " + mDPM.getCameraDisabled(null));

    // Display the fragment as the main content.
    /*
      getFragmentManager().beginTransaction()
        .replace(android.R.id.content, new SettingsFragment())
        .commit();
    */
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    getSettings();

    /*
    List<Integer> modes = mPreview.getSupportedPictureFormats();
    String lista = "";
    if ( modes != null && modes.size() > 0) {
       for (Integer i : modes) {
    lista += Integer.toString(i) + " ";
       }
    } else {
       lista = "List query failed";
    }
    Toast.makeText(getApplicationContext(), "Supported Picture formats: " + lista, Toast.LENGTH_LONG).show();
    */
    enableUi(false);
    Log.d(TAG, "onCreate - done");
    /*
           cl = new ChangeLog(this);
           if (cl.firstRun())
               cl.getLogDialog().show();
       */
    // set windows flags to keep full screen
    this.getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}