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:com.example.samsungmdm.MainActivity.java

private void grantAdminPrivileges() {
    mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mAdminName = new ComponentName(this, MyDeviceAdminReceiver.class);

    if (!mDPM.isAdminActive(mAdminName)) {
        //Not yet device admin
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "This needs to be added");
        startActivityForResult(intent, REQUEST_ENABLE);
    }/*from   w  w w.j  av  a 2  s .  c om*/
}

From source file:org.wso2.emm.agent.services.MessageProcessor.java

/**
 * Local notification message handler.//from   www .  ja va2 s.c  om
 *
 * @param context Context of the application.
 */
public MessageProcessor(Context context) {
    this.context = context;

    deviceId = Preference.getString(context, DEVICE_ID_PREFERENCE_KEY);
    operationProcessor = new OperationProcessor(context.getApplicationContext());
    mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    this.devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);

    if (deviceId == null) {
        DeviceInfo deviceInfo = new DeviceInfo(context.getApplicationContext());
        deviceId = deviceInfo.getDeviceId();
        Preference.putString(context, DEVICE_ID_PREFERENCE_KEY, deviceId);
    }
}

From source file:de.schildbach.wallet.util.CrashReporter.java

public 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(Strings.emptyToNull(Build.CPU_ABI),
            Strings.emptyToNull(Build.CPU_ABI2))).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("Memory Class: " + activityManager.getMemoryClass() + "/"
            + activityManager.getLargeMemoryClass()
            + (ActivityManagerCompat.isLowRamDevice(activityManager) ? " (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.exchange.adapter.ProvisionParser.java

private boolean deviceSupportsEncryption() {
    DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
    int status = dpm.getStorageEncryptionStatus();
    return status != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
}

From source file:com.decad3nce.aegis.AegisActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mViewPager = new ViewPager(this);
    mViewPager.setId(R.id.pager);//from www  .  ja  va 2 s.  co m
    setContentView(mViewPager);

    final ActionBar bar = getActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
    bar.setDisplayShowHomeEnabled(true);
    bar.setHomeButtonEnabled(true);
    bar.setTitle(R.string.app_name);

    mTabsAdapter = new TabsAdapter(this, mViewPager);
    mTabsAdapter.addTab(bar.newTab().setText(R.string.alarm_section), SMSAlarmFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText(R.string.lock_section), SMSLockFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText(R.string.wipe_section), SMSWipeFragment.class, null);
    mTabsAdapter.addTab(bar.newTab().setText(R.string.locate_section), SMSLocateFragment.class, null);
    if (savedInstanceState != null) {
        bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    }

    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    alarmEnabled = preferences.getBoolean(PREFERENCES_ALARM_ENABLED,
            this.getResources().getBoolean(R.bool.config_default_alarm_enabled));
    wipeEnabled = preferences.getBoolean(PREFERENCES_WIPE_ENABLED,
            this.getResources().getBoolean(R.bool.config_default_wipe_enabled));
    lockEnabled = preferences.getBoolean(PREFERENCES_LOCK_ENABLED,
            this.getResources().getBoolean(R.bool.config_default_lock_enabled));
    locateEnabled = preferences.getBoolean(PREFERENCES_LOCATE_ENABLED,
            this.getResources().getBoolean(R.bool.config_default_locate_enabled));

    invalidateOptionsMenu();

    mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
}

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

public Operation(Context context) {
    this.context = context;
    this.resources = context.getResources();
    this.devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
    this.appList = new ApplicationManager(context.getApplicationContext());
    this.resultBuilder = new BuildResultPayload(context.getApplicationContext());
    deviceInfo = new DeviceInfo(context.getApplicationContext());
    phoneState = DeviceStateFactory.getDeviceState(context.getApplicationContext(), deviceInfo.getSdkVersion());
    gps = new GPSTracker(context.getApplicationContext());
}

From source file:org.wso2.iot.agent.activities.AlreadyRegisteredActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_already_registered);

    textViewLastSync = (TextView) findViewById(R.id.textViewLastSync);
    imageViewRefresh = (ImageView) findViewById(R.id.imageViewRefresh);
    devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    cdmDeviceAdmin = new ComponentName(this, AgentDeviceAdminReceiver.class);
    context = this;
    DeviceInfo info = new DeviceInfo(context);
    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        if (extras.containsKey(getResources().getString(R.string.intent_extra_fresh_reg_flag))) {
            isFreshRegistration = extras
                    .getBoolean(getResources().getString(R.string.intent_extra_fresh_reg_flag));
        }/*from w  w  w  .  j a v  a2s .c o  m*/
    }
    String registrationId = Preference.getString(context, Constants.PreferenceFlag.REG_ID);

    if (registrationId != null && !registrationId.isEmpty()) {
        regId = registrationId;
    } else {
        regId = info.getDeviceId();
    }

    if (isFreshRegistration) {
        Preference.putBoolean(context, Constants.PreferenceFlag.REGISTERED, true);
        if (!isDeviceAdminActive()) {
            startEvents();
        }
        // In FCM, for fresh registrations, the initial FCM notification has been ignored
        // purposely to avoid calling the server during enrollment flow and causing threading
        // issues. Therefore after initial enrollment, pending operations is called manually.
        if (Constants.NOTIFIER_FCM
                .equals(Preference.getString(context, Constants.PreferenceFlag.NOTIFIER_TYPE))) {
            MessageProcessor messageProcessor = new MessageProcessor(context);
            try {
                if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED)) {
                    messageProcessor.getMessages();
                }
            } catch (AndroidAgentException e) {
                Log.e(TAG, "Failed to perform operation", e);
            }
        }
        isFreshRegistration = false;
    }

    RelativeLayout relativeLayoutSync = (RelativeLayout) findViewById(R.id.layoutSync);
    relativeLayoutSync.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED) && isDeviceAdminActive()) {
                syncWithServer();
            }
        }
    });

    RelativeLayout relativeLayoutDeviceInfo = (RelativeLayout) findViewById(R.id.layoutDeviceInfo);
    relativeLayoutDeviceInfo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadDeviceInfoActivity();
        }
    });

    RelativeLayout relativeLayoutChangePIN = (RelativeLayout) findViewById(R.id.layoutChangePIN);
    relativeLayoutChangePIN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadPinCodeActivity();
        }
    });

    RelativeLayout relativeLayoutRegistration = (RelativeLayout) findViewById(R.id.layoutRegistration);
    if (Constants.HIDE_UNREGISTER_BUTTON) {
        relativeLayoutRegistration.setVisibility(View.GONE);
    } else {
        relativeLayoutRegistration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUnregisterDialog();
            }
        });
    }

    TextView textViewAgentVersion = (TextView) findViewById(R.id.textViewVersion);
    String versionText = BuildConfig.BUILD_TYPE + " v" + BuildConfig.VERSION_NAME + " ("
            + BuildConfig.VERSION_CODE + ") ";
    textViewAgentVersion.setText(versionText);

    if (Build.VERSION.SDK_INT >= 23) {
        List<String> missingPermissions = new ArrayList<>();

        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.READ_PHONE_STATE);
        }
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        // This is to handle permission obtaining for Android N devices where operations such
        // as mute that can cause a device to go into "do not disturb" will need additional
        // permission. Added here as well to support already enrolled devices to optain the
        // permission without reenrolling.
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M
                && !devicePolicyManager.isProfileOwnerApp(Constants.AGENT_PACKAGE)
                && notificationManager != null && !notificationManager.isNotificationPolicyAccessGranted()) {
            CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context,
                    getResources().getString(R.string.dialog_do_not_distrub_title),
                    getResources().getString(R.string.dialog_do_not_distrub_message),
                    getResources().getString(R.string.ok), doNotDisturbClickListener);
        }

        if (missingPermissions.isEmpty()) {
            NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.cancel(Constants.PERMISSION_MISSING,
                    Constants.PERMISSION_MISSING_NOTIFICATION_ID);
        } else {
            ActivityCompat.requestPermissions(AlreadyRegisteredActivity.this,
                    missingPermissions.toArray(new String[missingPermissions.size()]), 110);
        }
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            int locationSetting = Settings.Secure.getInt(context.getContentResolver(),
                    Settings.Secure.LOCATION_MODE);
            if (locationSetting == 0) {
                Intent enableLocationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(enableLocationIntent);
                Toast.makeText(context, R.string.msg_need_location, Toast.LENGTH_LONG).show();
            }
        } catch (Settings.SettingNotFoundException e) {
            Log.w(TAG, "Location setting is not available on this device");
        }
    }

    boolean isRegistered = Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED);
    if (isRegistered) {
        if (CommonUtils.isNetworkAvailable(context)) {
            String serverIP = Constants.DEFAULT_HOST;
            String prefIP = Preference.getString(context, Constants.PreferenceFlag.IP);
            if (prefIP != null) {
                serverIP = prefIP;
            }
            regId = Preference.getString(context, Constants.PreferenceFlag.REG_ID);

            if (regId != null) {
                if (serverIP != null && !serverIP.isEmpty()) {
                    ServerConfig utils = new ServerConfig();
                    utils.setServerIP(serverIP);
                    if (utils.getHostFromPreferences(context) != null
                            && !utils.getHostFromPreferences(context).isEmpty()) {
                        CommonUtils.callSecuredAPI(AlreadyRegisteredActivity.this,
                                utils.getAPIServerURL(context) + Constants.DEVICES_ENDPOINT + regId
                                        + Constants.IS_REGISTERED_ENDPOINT,
                                HTTP_METHODS.GET, null, AlreadyRegisteredActivity.this,
                                Constants.IS_REGISTERED_REQUEST_CODE);
                    } else {
                        try {
                            CommonUtils.clearAppData(context);
                        } catch (AndroidAgentException e) {
                            String msg = "Device already dis-enrolled.";
                            Log.e(TAG, msg, e);
                        }
                        loadInitialActivity();
                    }
                } else {
                    Log.e(TAG, "There is no valid IP to contact server");
                }
            }
        } else {
            if (!Constants.HIDE_ERROR_DIALOG) {
                CommonDialogUtils.showNetworkUnavailableMessage(AlreadyRegisteredActivity.this);
            }
        }
    } else {
        loadInitialActivity();
    }
}

From source file:org.wso2.emm.agent.services.operationMgt.OperationManager.java

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();
    deviceInfo = new DeviceInfo(context.getApplicationContext());
    notificationDAO = new NotificationDAO(context);
    AGENT_PACKAGE_NAME = context.getPackageName();
    AUTHORIZED_PINNING_APPS = new String[] { AGENT_PACKAGE_NAME };
    notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    applicationManager = new ApplicationManager(context);
}

From source file:de.Maxr1998.xposed.maxlock.ui.settings.SettingsFragment.java

@SuppressLint("WorldReadableFiles")
@Override/*from www  .j av  a2 s  .  c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    //noinspection deprecation
    getPreferenceManager().setSharedPreferencesMode(Activity.MODE_WORLD_READABLE);
    addPreferencesFromResource(R.xml.preferences_main);
    PREFS = PreferenceManager.getDefaultSharedPreferences(getActivity());
    PREFS_KEYS = getActivity().getSharedPreferences(Common.PREFS_KEY, Context.MODE_PRIVATE);
    //noinspection deprecation
    PREFS_THEME = getActivity().getSharedPreferences(Common.PREFS_THEME, Context.MODE_WORLD_READABLE);

    devicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
    deviceAdmin = new ComponentName(getActivity(), UninstallProtectionReceiver.class);
}

From source file:org.wso2.iot.agent.events.listeners.ApplicationStateListener.java

/**
 * This method will check if the app just installed is allowed if a app white-listing policy is enforced.
 *///w  ww .j  a va 2s . c  o m
private void applyEnforcement(String packageName) {
    DevicePolicyManager devicePolicyManager;
    ComponentName cdmfDeviceAdmin;
    devicePolicyManager = (DevicePolicyManager) context.getApplicationContext()
            .getSystemService(Context.DEVICE_POLICY_SERVICE);
    cdmfDeviceAdmin = AgentDeviceAdminReceiver.getComponentName(context.getApplicationContext());
    String permittedPackageName;
    JSONObject permittedApp;
    String permissionName;
    Boolean isAllowed = false;
    String whiteListAppsPref = Preference.getString(context, Constants.AppRestriction.WHITE_LIST_APPS);
    String ownershipType = Preference.getString(context, Constants.DEVICE_TYPE);
    if (!whiteListAppsPref.equals("")) {
        try {
            JSONArray whiteListApps = new JSONArray(whiteListAppsPref);
            for (int i = 0; i < whiteListApps.length(); i++) {
                permittedApp = new JSONObject(whiteListApps.getString(i));
                permittedPackageName = permittedApp.getString(Constants.AppRestriction.PACKAGE_NAME);
                if (permittedPackageName.equals(packageName)) {
                    permissionName = permittedApp.getString(Constants.AppRestriction.RESTRICTION_TYPE);
                    if (permissionName.equals(Constants.AppRestriction.WHITE_LIST)) {
                        isAllowed = true;
                        break;
                    }
                }
            }
            if (!isAllowed) {
                String disallowedApps = Preference.getString(context, Constants.AppRestriction.DISALLOWED_APPS);
                disallowedApps = disallowedApps + context.getString(R.string.whitelist_package_split_regex)
                        + packageName;
                Preference.putString(context, Constants.AppRestriction.DISALLOWED_APPS, disallowedApps);
                //Calls devicePolicyManager if the agent is profile-owner or device-owner.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
                        && (devicePolicyManager.isProfileOwnerApp(cdmfDeviceAdmin.getPackageName())
                                || devicePolicyManager.isDeviceOwnerApp(cdmfDeviceAdmin.getPackageName()))) {
                    devicePolicyManager.setApplicationHidden(cdmfDeviceAdmin, packageName, true);
                } else if (Constants.OWNERSHIP_COPE.equals(ownershipType)) {
                    CommonUtils.callSystemApp(context, Constants.Operation.APP_RESTRICTION, "false",
                            packageName);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Invalid JSON format..");
        }
    }
}