我的应用程序未获得 android.permission.WRITE_SETTINGS 授权时出现 java.lang.SecurityException。即使我已将它添加到我的 list xml 文件中
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SoundActivity1"></activity>
</application>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
编辑 1:好的,所以我有这段代码必须在 Activity 之外的类中运行,我将如何请求用户许可,然后如果他们授予它,运行这段代码,全部在一个类中 Activity 之外? -
Uri newRingtone = Uri.parse("android.resource://com.example.myapp/" + soundID);
RingtoneManager.setActualDefaultRingtoneUri(context,RingtoneManager.TYPE_RINGTONE,newRingtone);
在任何人问之前,是的,它需要在我设置我的应用程序的 Activity 之外
最佳答案
根据 WRITE_SETTINGS
documentation :
Note: If the app targets API level 23 or higher, the app user must explicitly grant this permission to the app through a permission management screen. The app requests the user's approval by sending an intent with action
ACTION_MANAGE_WRITE_SETTINGS
. The app can check whether it has this authorization by callingSettings.System.canWrite()
.
因此您应该使用如下代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
!Settings.System.canWrite(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData("package:"+getPackageName());
startActivityForResult(intent);
// now wait for onActivityResult()
}
关于android - 尽管已授予权限,但仍获得安全异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41581970/