How to make the standard music player find my files

走远了吗. 提交于 2019-12-25 01:44:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!