如何在Android应用中设置手机铃声?

46

我正在尝试从我的Android活动中编写代码来设置新的默认铃声。

我已经将铃声下载到bytearray中。

13个回答

0
我从 Android 的媒体应用程序中找到了这段代码。
Settings.System.putString(resolver, 
Settings.System.RINGTONE, ringUri.toString());

这个对我有效。


0

我已经尝试了这些代码,它们很有帮助

  private void setRingtone(Context context, String path) {
    if (path == null) {
        return;
    }
    File file = new File(path);
    ContentValues contentValues = new ContentValues();
    contentValues.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
    String filterName = path.substring(path.lastIndexOf("/") + 1);
    contentValues.put(MediaStore.MediaColumns.TITLE, filterName);
    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
    contentValues.put(MediaStore.MediaColumns.SIZE, file.length());
    contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(path);
    Cursor cursor = context.getContentResolver().query(uri, null, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
    if (cursor != null && cursor.moveToFirst() && cursor.getCount() > 0) {
        String id = cursor.getString(0);
        contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        context.getContentResolver().update(uri, contentValues, MediaStore.MediaColumns.DATA + "=?", new String[]{path});
        Uri newuri = ContentUris.withAppendedId(uri, Long.valueOf(id));
        try {
            RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newuri);
            Toast.makeText(context, "Set as Ringtone Successfully.", Toast.LENGTH_SHORT).show();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        cursor.close();
    }
}

0

如果您通过bytearray创建文件,您可以使用此函数设置铃声:

public void setRingtone(String filePath) {
        try {
            File f = new File(filePath);
            f.setReadable(true);
            Uri newUri = Uri.parse(f.toString());
            Settings.System.putString(getContentResolver(), Settings.System.RINGTONE,
                    newUri.toString());

        } catch (Exception t) {
        }
    }

参考Settings.System.putString()方法设置铃声的链接:https://android.googlesource.com/platform/frameworks/base/+/master/media/java/android/media/RingtoneManager.java#828


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