3

I'm getting a java.lang.SecurityException for my app not having been granted android.permission.WRITE_SETTINGS. even though I have added it into my manifests xml file

<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"/>

Edit 1: Alright so I have this code that has to be run in a class outside of the activity, How would I go about asking for a users permission, then if they grant it, run this code, all in a class outside of the activity? -

Uri newRingtone = Uri.parse("android.resource://com.example.myapp/" + soundID); 
RingtoneManager.setActualDefaultRingtoneUri(context,RingtoneManager.TYPE_RINGTONE,newRingtone);

And before anyone asks, yes, it needs to be outside of the activity with they way I set up my app

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
CarbonZonda
  • 167
  • 2
  • 11

1 Answers1

4

Per the 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 calling Settings.System.canWrite().

Therefore you should use code such as:

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()
}
ianhanniballake
  • 191,609
  • 30
  • 470
  • 443