Android保存/重写文件到SD卡

时间:2012-01-08 00:47:33

标签: java android

我已经实现了可以将音频资源保存到SD卡的方法,但如果我使用相同资源2次,我会在音乐播放器2中看到相同的文件... 如何覆盖文件?或者是玩家扫描的问题?

    public Uri saveToSdCard(String name, int audioResourceId) {

    String path = "/sdcard/media/audio/ringtones/";
    String resourceEntryName = activity.getApplicationContext().getResources().getResourceEntryName(audioResourceId);
    String filename = resourceEntryName + ".ogg";

    byte[] buffer = null;
    try {
        InputStream inputStream = activity.getBaseContext().getResources().openRawResource(audioResourceId);
        int size = inputStream.available();
        buffer = new byte[size];
        inputStream.read(buffer);
        inputStream.close();
    } catch (IOException e) {
        Toast.makeText(activity, R.string.oops_message, Toast.LENGTH_LONG).show();
    }

    boolean exists = (new File(path)).exists();
    if (!exists) {
        new File(path).mkdirs();
    }

    FileOutputStream save;
    try {
        save = new FileOutputStream(path + filename);
        save.write(buffer);
        save.flush();
        save.close();
    } catch (FileNotFoundException e) {
        Toast.makeText(activity, R.string.ex_message, Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(activity, R.string.ex_message, Toast.LENGTH_SHORT).show();
    }

    File mediaFile = new File(path, filename);

    ContentValues values = new ContentValues();
    values.put(MediaStore.MediaColumns.DATA, mediaFile.getAbsolutePath());
    values.put(MediaStore.MediaColumns.TITLE, resourceEntryName);
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
    values.put(MediaStore.Audio.Media.ARTIST, name);
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
    values.put(MediaStore.Audio.Media.IS_ALARM, true);
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);

    Uri uri = MediaStore.Audio.Media.getContentUriForPath(mediaFile.getAbsolutePath());
    Uri auri = activity.getContentResolver().insert(uri, values);
    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, auri));
    return auri;
}

1 个答案:

答案 0 :(得分:0)

无论文件是否已存在,都可能是您将广播发送到媒体扫描仪。

如果您在!exists行周围检查sendBroadcast,会发生什么情况?

if (!exists) {
    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, auri));
}