Example usage for android.app NotificationManager isNotificationPolicyAccessGranted

List of usage examples for android.app NotificationManager isNotificationPolicyAccessGranted

Introduction

In this page you can find the example usage for android.app NotificationManager isNotificationPolicyAccessGranted.

Prototype

public boolean isNotificationPolicyAccessGranted() 

Source Link

Document

Checks the ability to modify notification do not disturb policy for the calling package.

Usage

From source file:com.metinkale.prayerapp.utils.PermissionUtils.java

public void needNotificationPolicy(final Activity act) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return;/*  w w w.ja  va 2s .c  o  m*/
    }
    NotificationManager nm = (NotificationManager) act.getSystemService(Context.NOTIFICATION_SERVICE);
    pNotPolicy = nm.isNotificationPolicyAccessGranted();
    if (!pNotPolicy) {
        Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);

        PackageManager packageManager = act.getPackageManager();
        if (intent.resolveActivity(packageManager) != null) {
            act.startActivity(intent);
        } else {
            ActivityCompat.requestPermissions(act,
                    new String[] { Manifest.permission.ACCESS_NOTIFICATION_POLICY }, 0);
        }
    }
}

From source file:com.metinkale.prayerapp.utils.PermissionUtils.java

private void checkPermissions(Context c) {
    pCalendar = ContextCompat.checkSelfPermission(c,
            Manifest.permission.WRITE_CALENDAR) == PackageManager.PERMISSION_GRANTED;
    pCamera = ContextCompat.checkSelfPermission(c,
            Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
    pStorage = ContextCompat.checkSelfPermission(c,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    pLocation = ContextCompat.checkSelfPermission(c,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        NotificationManager nm = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
        pNotPolicy = nm.isNotificationPolicyAccessGranted();
        Crashlytics.setBool("pNotPolicy", pLocation);
    } else/* ww w  .  j  ava  2 s .  c  o  m*/
        pNotPolicy = true;

    Crashlytics.setBool("pCalendar", pCalendar);
    Crashlytics.setBool("pCamera", pCamera);
    Crashlytics.setBool("pStorage", pStorage);
    Crashlytics.setBool("pLocation", pLocation);

}

From source file:com.z3r0byte.magis.Services.AutoSilentService.java

private void setup() {
    if (autoSilent) {
        TimerTask notificationTask = new TimerTask() {
            @Override/*w  ww .j  a  va 2s  . c om*/
            public void run() {
                NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                        && !notificationManager.isNotificationPolicyAccessGranted()) {
                    Log.w(TAG, "run: Not allowed to change state of do not disturb!");
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                            getApplicationContext());
                    mBuilder.setSmallIcon(R.drawable.magis512);

                    Intent resultIntent = new Intent(
                            android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
                    TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
                    stackBuilder.addParentStack(CalendarActivity.class);
                    stackBuilder.addNextIntent(resultIntent);
                    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    mBuilder.setContentIntent(resultPendingIntent);

                    mBuilder.setContentTitle("Magis kan de telefoon niet op stil zetten");
                    mBuilder.setContentText("Klik om op te lossen");
                    mBuilder.setAutoCancel(true);
                    mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(9999, mBuilder.build());
                    return;
                }
                appointments = calendarDB.getSilentAppointments(getMargin());
                if (doSilent(appointments)) {
                    silenced(true);
                    AudioManager audiomanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                    if (audiomanager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) {
                        audiomanager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                    }
                } else {
                    if (isSilencedByApp()) {
                        AudioManager audiomanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                        audiomanager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
                        silenced(false);
                    }
                }
            }
        };
        timer.schedule(notificationTask, 20000, 1000);
    }
}

From source file:com.example.android.shushme.MainActivity.java

@Override
public void onResume() {
    super.onResume();

    // Initialize location permissions checkbox
    CheckBox locationPermissions = (CheckBox) findViewById(R.id.location_permission_checkbox);
    if (ActivityCompat.checkSelfPermission(MainActivity.this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locationPermissions.setChecked(false);
    } else {//from   w  w w. j  a  v a2s  .  co m
        locationPermissions.setChecked(true);
        locationPermissions.setEnabled(false);
    }

    // Initialize ringer permissions checkbox
    CheckBox ringerPermissions = (CheckBox) findViewById(R.id.ringer_permissions_checkbox);
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Check if the API supports such permission change and check if permission is granted
    if (android.os.Build.VERSION.SDK_INT >= 24 && !nm.isNotificationPolicyAccessGranted()) {
        ringerPermissions.setChecked(false);
    } else {
        ringerPermissions.setChecked(true);
        ringerPermissions.setEnabled(false);
    }
}

From source file:de.baumann.hhsmoodle.HHS_MainScreen.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_screen_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from w ww.  j  a va  2s  .co  m*/
    helper_security.checkPin(HHS_MainScreen.this);
    helper_security.grantPermissions(HHS_MainScreen.this);
    helper_main.onStart(HHS_MainScreen.this);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putString("browserLoad", "").apply();
    class_SecurePreferences sharedPrefSec = new class_SecurePreferences(HHS_MainScreen.this, "sharedPrefSec",
            "Ywn-YM.XK$b:/:&CsL8;=L,y4", true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    View headerView = navigationView.getHeaderView(0);
    TextView nav_user = (TextView) headerView.findViewById(R.id.usernameNav);
    nav_user.setText(sharedPrefSec.getString("username"));

    TypedArray images = getResources().obtainTypedArray(R.array.splash_images);
    int choice = (int) (Math.random() * images.length());
    headerView.setBackgroundResource(images.getResourceId(choice, R.drawable.splash1));
    images.recycle();

    if (!appDir().exists()) {
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            int hasWRITE_EXTERNAL_STORAGE = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasWRITE_EXTERNAL_STORAGE == PackageManager.PERMISSION_GRANTED) {
                if (!appDir().exists()) {
                    appDir().mkdirs();
                } else {
                    helper_security.grantPermissions(HHS_MainScreen.this);
                }
            }
        } else {
            appDir().mkdirs();
        }
    }

    onNewIntent(getIntent());

    if (sharedPref.getBoolean("silent_mode", true)) {
        final NotificationManager notificationManager = (NotificationManager) HHS_MainScreen.this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                && !notificationManager.isNotificationPolicyAccessGranted()) {
            if (sharedPref.getString("show_permission_disturb", "true").equals("true")) {
                new android.app.AlertDialog.Builder(this).setTitle(R.string.app_permissions_title_dist)
                        .setMessage(helper_main.textSpannable(getString(R.string.app_permissions_dist)))
                        .setNeutralButton(R.string.toast_notAgain, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                sharedPref.edit().putString("show_permission_disturb", "false").apply();
                            }
                        }).setPositiveButton(getString(R.string.toast_yes),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                                                && !notificationManager.isNotificationPolicyAccessGranted()) {
                                            Intent intent = new Intent(
                                                    android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
                                            startActivity(intent);
                                        }
                                    }
                                })
                        .setNegativeButton(getString(R.string.toast_cancel), null).show();
            }
        }
    }
}

From source file:com.android.launcher3.Utilities.java

private static void checkPermissionForRingtone(Activity activity) {
    NotificationManager notificationManager = (NotificationManager) activity.getApplicationContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
            && !notificationManager.isNotificationPolicyAccessGranted()) {

        Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);

        activity.startActivity(intent);/*from   w ww  .ja  v  a 2s .com*/
    }
}

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 va 2 s.  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();
    }
}