如何在 Marshmallow 中授予更改屏幕亮度的权限

How to give permission for changing screen brightness in Marshmallow

我正在使用以下代码来增加亮度。它在棉花糖以下的设备中正常工作。它在 Marshmallow 中崩溃了,我没有找到任何可以为写入设置提供动态权限的东西。任何人有想法请帮助我。

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);

错误日志:

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)

From API 23 您应该使用 Settings.System.canWrite(context) 动态询问用户是否拥有 WRITE_SETTINGS 权限。如果您希望用户批准该设置,您应该使用操作 ACTION_MANAGE_WRITE_SETTINGS 启动一个意图。您可能需要的代码如下:

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);
}