How to give permission for changing screen brightness in Marshmallow

与世无争的帅哥 提交于 2019-12-06 04:36:21

问题


I am using following code to increase brightness. It is properly working in devices which are below Marshmallow. It is crashing in Marshmallow, and I did not find anything to give dynamic permission for Write-settings. Anybody has idea please help me.

Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); 
    Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 255);

int br = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.screenBrightness = (float) br / 255;
    getWindow().setAttributes(lp);

Error Log:

java.lang.SecurityException: com.package was not granted  this permission: android.permission.WRITE_SETTINGS.
   at                 android.provider.Settings.isCallingPackageAllowedToPerformAppOpsProtectedOperation(Settings.java:8465)
   at    android.provider.Settings.checkAndNoteWriteSettingsOperation(Settings.java:8338)
at com.android.providers.settings.SettingsProvider.mutateSystemSetting(SettingsProvider.java:899)
at com.android.providers.settings.SettingsProvider.insertSystemSetting(SettingsProvider.java:874)
at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:257)
at android.content.ContentProvider$Transport.call(ContentProvider.java:398)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:283)
at android.os.Binder.execTransact(Binder.java:453)

回答1:


From API 23 you should ask dynamically from the user if they have the WRITE_SETTINGS permission by using Settings.System.canWrite(context). If you want the user approve the setting, you should start an intent with action ACTION_MANAGE_WRITE_SETTINGS. The code you probably need is something like follows:

if (Settings.System.canWrite(context))
{
    // perform your actions
}
else
{
    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS)
    .setData(Uri.parse("package:" + getActivity().getPackageName()))
    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}


来源:https://stackoverflow.com/questions/36674453/how-to-give-permission-for-changing-screen-brightness-in-marshmallow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!