2
我已經實現的方法,可以節約資源音頻到SD卡,但如果我以同樣的資源使用2次,我在音樂播放器中看到2個等於文件... 如何覆蓋文件?或者是玩家掃描有問題?Android的保存/重寫文件到SD卡
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;
}
你可以檢查該文件是否已經存在。如果是,則刪除該文件並重新創建一個。 – 2012-01-08 01:20:07
我試圖做 如果(mediaFile.exists()){ mediaFile.delete(); },但它並沒有幫助,我仍然有2個文件 – Funtime 2012-01-08 01:54:33