问题
My App downloads some mp3 files to sdcard. I want to play them with other music players installed on the device. But the other music players don't automatically find my downloaded files. How can I force the MediaScanner to run so that my media files will be playable from the stock Music application?
I download the files using this code
public void run() {
loaded = 0;
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0 && !stop){
loaded += x;
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}catch(Exception e){
}
}
回答1:
You can force the scan of media file with a broadcast:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
回答2:
Make sure the folder that your files are in do not have a file called ".nomedia" in them. That file tells the MediaScanner not to check there.
(note: there is a "." in front of nomedia, which means it may be hidden)
回答3:
Here is an easy 'single file based solution':
Whenever you add or remove a file, let MediaStore Content Provider knows about it using
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageAddedOrDeleted)));
Main advantage: work with any mime type supported by MediaStore
Note:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
is too expensive and scan everything. My advice: if you can, use the 'per file' approach.
来源:https://stackoverflow.com/questions/6144402/how-to-make-the-standard-music-player-find-my-files