-2

I can set ringtone programmatically between 4.0 to 6.0(Marshmallow) but not able to set after 6.0 (Marshmallow).

Can you please let me know how to fix this issue so that i can set ringtone to an Android Oreo 8.0 and 8.1 version device too?

  public void setRingtone(String filepath) {
        File ringtoneFile = new File(filepath);
        ContentValues content = new ContentValues();
        content.put(MediaStore.MediaColumns.DATA, ringtoneFile.getAbsolutePath());
        content.put(MediaStore.MediaColumns.TITLE, "Ring");
        content.put(MediaStore.MediaColumns.SIZE, ringtoneFile.length());
        content.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
        //  content.put(MediaStore.Audio.Media.ARTIST, "Madonna");
        content.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        content.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        content.put(MediaStore.Audio.Media.IS_ALARM, false);
        content.put(MediaStore.Audio.Media.IS_MUSIC, true);

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(ringtoneFile.getAbsolutePath());

        getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + ringtoneFile.getAbsolutePath() + "\"", null);
        Uri newUri = getContentResolver().insert(uri, content);
        System.out.println("uri==" + uri);
        Log.i("TAG", "the ringtone uri is :" + newUri);
        RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE, newUri);

        Toast.makeText(this, "Ringtone set success!", Toast.LENGTH_SHORT).show();
    }

Thank You.

Sumuu2211
  • 11
  • 4

1 Answers1

-1

Add URI permission on your project

AndroidManifest.xml

 <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

create xml folder in res and acreate provider_path.xml in res/XML like this

provider_paths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
    </paths>

Hope it helps