2012-01-08 10 views
2

私はsdカードにオーディオリソースを保存できる方法を実装しましたが、同じリソースで2回使用するとMusic Player 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; 
} 
+0

ファイルが既に存在するかどうかを確認できます。そうであれば、ファイルを削除して新しいファイルを再作成します。 –

+0

私は何をしようとしました if(mediaFile.exists()){ mediaFile.delete(); }しかし、それは助けにはなりません、私はまだ2つのファイルがあります – Funtime

答えて

0

ファイルが既に存在するかどうかにかかわらず、ブロードキャストをメディアスキャナに送信している可能性があります。

あなたのsendBroadcast行の周りに!existsの小切手を置くとどうなりますか?

if (!exists) { 
    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, auri)); 
} 
関連する問題