如何在Oreo 8.0中以编程方式设置铃声

时间:2018-08-25 05:20:48

标签: android android-8.0-oreo ringtone android-8.1-oreo

我可以通过编程方式在4.0到6.0(棉花糖)之间设置铃声,但在6.0(棉花糖)之后无法设置。

能否让我知道如何解决此问题,以便我也可以将铃声设置为Android Oreo 8.0和8.1版本设备?

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

谢谢。

1 个答案:

答案 0 :(得分:-1)

在您的项目中添加URI权限

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>
res

创建 xml 文件夹,并在 res / XML 中创建 provider_path.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>

希望有帮助