2

I am trying to provide Notification Access to my app, for that I have added below permission in Manifest

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

Also I have registered listener as below on activity.

IntentFilter notlist = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                notlist = new IntentFilter(ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED);
            }
            Intent notlistch = registerReceiver(null,notlist);

Now when user clicks on button I have below code

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                            startActivity(new Intent(ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
                                        }

Now If I click on button with above code in it, this will always take me to notification settings, so if my app has got access during first click, how can I check it before throwing intent for opening settings.

I read to use ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED, but did not understand how to use it. Can anyone help me.

ideally I should check access status first and then on getting false, I should call intent to open notification settings.

Panache
  • 1,701
  • 3
  • 19
  • 33
  • ref this https://stackoverflow.com/questions/39732880/android-n-checking-for-dnd-state-changed-before-updating-checkbox-preference. – Panache Jul 01 '17 at 05:16

2 Answers2

0

You can check it in a way like this:

 if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NOTIFICATION_POLICY) != PackageManager.PERMISSION_GRANTED) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_NOTIFICATION_POLICY)) {

    } else {
           ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_NOTIFICATION_POLICY}, RC_ACCESS_NOTIFICATION_POLICY);

   }
}

RC_ACCESS_NOTIFICATION_POLICY is the key that you can get the result by this in this way with onPermissionGranted

Meikiem
  • 1,876
  • 2
  • 11
  • 19
0

if anyone still looking for a solution this is my solution

 private boolean isNotificationServiceEnabled() {
    String pkgName = getPackageName();
    final String flat = Settings.Secure.getString(getContentResolver(),
            ENABLED_NOTIFICATION_LISTENERS);
    if (!TextUtils.isEmpty(flat)) {
        final String[] names = flat.split(":");
        for (String name : names) {
            final ComponentName cn = ComponentName.unflattenFromString(name);
            if (cn != null) {
                if (TextUtils.equals(pkgName, cn.getPackageName())) {
                    return true;
                }
            }
        }
    }
    return false;
}