I have implemented method which can save audio resource to sd card, but if i use it 2 times with equal resource i see in Music Player 2 equal files... How to overwrite file? Or it is problem with player scanning?
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;
}
It could be that you're sending your broadcast to the media scanner regardless of whether the file already exists or not.
What happens if you put a check for !exists
around your sendBroadcast
line as follows?
if (!exists) {
activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, auri));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.