18

I'm building my app for android 6.0 Marshmallow, it needs WRITE_SETTTINGS permission. After searching from here I came to know that calling this:

requestPermissions(new String[]{Manifest.permission.WRITE_SETTINGS},
              101);

won't show dialog permission. So, based on CommonsWare solution, we should check if Settings.System.canWrite() returns true or false. So, I should call Activity with ACTION_MANAGE_WRITE_SETTINGS as action.

But the issue is when I call this activity, it shows my app has already been granted permission though the method Settings.System.canWrite() returns false.

Am I missing something here or I have to disable it then enable it again.

5
  • 1
    Before requesting for permission have you check is permission is already granted or not. If it is already granted you don't need to ask for grant the permission again. Because on marshmallow onward user have control to decline the permission by manually in settings.
    – VikasGoyal
    Commented Jan 28, 2016 at 6:07
  • If you need code how to check the permission is already granted or not we can provide it.
    – VikasGoyal
    Commented Jan 28, 2016 at 6:08
  • @Pankaj stackoverflow.com/a/32083622/1168654 CommonsWare he already explain if Settings.System.canWrite() return false then start activity ACTION_MANAGE_WRITE_SETTINGS then user have to allow permission Commented Jan 28, 2016 at 6:09
  • System.canWrite() returns false but permission page shows that it has already been granted @DhawalSodhaParmar
    – Pankaj
    Commented Jan 28, 2016 at 6:13
  • Read this for better understanding - Read this
    – Tombstone
    Commented Aug 9, 2022 at 11:16

5 Answers 5

11

On my Nexus 6 using Android 6.0.1 (MMB29S) this code:

if (!Settings.System.canWrite(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
    intent.setData(Uri.parse("package:dummy"));
    startActivity(intent);
}

opens the Settings only if Allow modify system settings is set to disabled. For instance, at first launch after fresh install (i.e. not reinstall)

Edit (see comments): Some device may be bugged with respect to this code, in those canWrite() always returns false, whatever the value of the setting.

10
  • Have you tried: 1) adb install 2) Enable in settings 3) first launch. BTW, which device and version of Android are you using?
    – cuihtlauac
    Commented Feb 6, 2016 at 8:23
  • 1
    Hi, do you guys reached any conclusion? I'm right now having the same issue @Pankaj had, canWrite() always returns false besides the "ACTION_MANAGE_WRITE_SETTINGS" screen show the switch as ON. The only workaround i found was to click twice in the switch, so the value is reset and the canWrite() starts returning true instead, but this is terrible for the user manage. Commented Feb 25, 2016 at 14:12
  • 2
    I had similar conclusion, on a Moto X 2nd Gen 6.0 everything works perfectly, but Galaxy Note 5 and Galaxy S6 (both 6.0.1) are reproducing the issue. Commented Feb 25, 2016 at 14:50
  • 2
    Samsung enables write system settings by default, but returns false when call Settings.System.canWrite(this). It's only returns true if you disable and enable the setting again. Yup, another Samsung bug. developer.samsung.com/forum/thread/…
    – Thiago
    Commented Jun 8, 2016 at 22:05
  • 1
    The improper switch display appears to be an Android bug: code.google.com/p/android/issues/detail?id=204610
    – mike47
    Commented Jan 2, 2017 at 17:11
8
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (Settings.System.canWrite(context)) {
            
            //Write code to feature for eg. set brightness or vibrate device 
           /* ContentResolver cResolver = context.getContentResolver();
            Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS,brightness);*/
        }
        else {
            showBrightnessPermissionDialog(context);
        }

Dialog :-

 private  static  void showBrightnessPermissionDialog(final Context context) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    final AlertDialog alert = builder.create();
    builder.setMessage("Please give the permission to change brightness. \n Thanks ")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                    intent.setData(Uri.parse("package:" + context.getPackageName()));
                   // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    alert.dismiss();
                }
            });
    alert.show();
}

for eg. complete code for Brightness .

 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.net.Uri;
 import android.os.Build;
 import android.provider.Settings;
 import android.support.v7.app.AlertDialog;

  public class BrightnessHelper {

  public static void  setBrightness(Context context, int brightness){

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (Settings.System.canWrite(context)) {

      //Write code to feature for eg. set brightness or vibrate device
            ContentResolver cResolver = context.getContentResolver();  Settings.System.putInt(cResolver,  Settings.System.SCREEN_BRIGHTNESS,brightness);
        }
        else {
            showBrightnessPermissionDialog(context);
        }
    }

}

public static int getBrightness(Context context) {
    ContentResolver cResolver = context.getContentResolver();
    try {
        return Settings.System.getInt(cResolver,  Settings.System.SCREEN_BRIGHTNESS);
    } catch (Settings.SettingNotFoundException e) {
        return 0;
    }
}

private  static  void showBrightnessPermissionDialog(final Context context) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setCancelable(true);
    final AlertDialog alert = builder.create();
    builder.setMessage("Please give the permission to change brightness. \n Thanks ")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                    intent.setData(Uri.parse("package:" + context.getPackageName()));
                   // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    alert.dismiss();
                }
            });
    alert.show();
}


/*
    private boolean checkSystemWritePermission(Activity activity) {
        boolean retVal = true;
        if (Build.VERSION.SDK_INT >= activity.Build.VERSION_CODES.M) {
            retVal = Settings.System.canWrite(activity.getApplicationContext());
           // Log.d(TAG, "Can Write Settings: " + retVal);
            if(retVal){
                Toast.makeText(activity, "Write allowed :-)", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(this, "Write not allowed :-(", Toast.LENGTH_LONG).show();
                FragmentManager fm = getFragmentManager();
                PopupWritePermission dialogFragment = new PopupWritePermission();
                dialogFragment.show(fm, getString(R.string.popup_writesettings_title));
            }
        }
        return retVal;
    }*/
}
4

write this method as follows:

public void writePermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getApplicationContext())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 200);

        }
    }
}

then call the method (writePermission) just before you call your dialog

I hope this helps

2

It turns out that if you have CHANGE_NETWORK_STATE declared in your manifest, the toggle to allow WRITE_SETTINGS will default to the on position even though the permission is not granted. You don't even need to declare WRITE_SETTINGS to encounter this bug.

2
  • Thank you. This should be the right answer. Any workaround? I need to use also CHANGE_NETWORK_STATE in my app? can I ask for it at runtime so the switch shows the right position? All this stuff is terrible for my downloads. App will not even start if the permission is not granted :-(
    – Ton
    Commented Feb 24, 2017 at 9:05
  • @Ton no CHANGE_NETWORK_STATE does not require runtime permission. It only needs to be declared in manifest Commented Mar 28, 2017 at 4:50
1

I encountered a similar issue while developing for android 6. This is because, now the devs have to ask for permissions at runtime. My solution is here-

In your onCreate, show a permissions dialog. Lets say the method's name is showPermissionsDialog().

//Global variable request code
private static final int WRITE_PERMISSION_REQUEST = 5000;

private void showPermissionsDialog() {
    if (Build.VERSION.SDK_INT == 23) {

      int hasWriteSettingsPermission = checkSelfPermission(Manifest.permission.WRITE_SETTINGS);
      if (hasWriteSettingsPermission != PackageManager.PERMISSION_GRANTED) {
        //You can skip the next if block. I use it to explain to user why I wan his permission.
        if (!ActivityCompat.shouldShowRequestPermissionRationale(HomeActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
          showMessageOKCancel("You need to allow write settings",
              new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  ActivityCompat.requestPermissions(HomeActivity.this, new String[]{Manifest.permission.WRITE_SETTINGS}, WRITE_PERMISSION_REQUEST);
                }
              });
          return;
        }
//The next line causes a dialog to popup, asking the user to allow or deny us write permission
        ActivityCompat.requestPermissions(HomeActivity.this, new String[]{Manifest.permission.WRITE_SETTINGS}, WRITE_PERMISSION_REQUEST);
        return;
      } else {
        //Permissions have already been granted. Do whatever you want :) 
      }
    }
}

//Now you only need this if you want to show the rationale behind  
//requesting the permission.      
    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(HomeActivity.this).setMessage(message).setPositiveButton("OK", okListener)
        .setNegativeButton("Cancel", null).show();
  }

//This method is called immediately after the user makes his decision to either allow 
  // or disallow us permision.
  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
      case WRITE_PERMISSION_REQUEST:
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          //User pressed the allowed button
          //Do what you want :)
        } else {
          //User denied the permission
          //Come up with how to hand the requested permission
        }
      default:
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
  }
2
  • I'm asking the reason for wrong behavior of Settings.System.canWrite().
    – Pankaj
    Commented Jan 31, 2016 at 5:00
  • See the user won't be shown a dialog if the user had done the following- 1. Already allowed you permission. 2. Denied you permission. But if the user is installing this application for the first time, then the user will be shown this. If the user has denied you permission he can still explicitly give it to you by going to app permissions in settings and selecting the relevant permission. So you can make an intent to go over there. I am yet to explore the intent part but I think it is possible. Commented Jan 31, 2016 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.