如何在Marshmallow系统中给予更改屏幕亮度的权限

4
我正在使用以下代码来增加亮度。在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)

1
请提供您的错误日志。 - Sayem
尝试一下,它可能有效。https://dev59.com/J1wX5IYBdhLWcg3w-Thv#41221852 - Bipin Bharti
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接