我试图制作一个MP3播放器应用程序,当我从手机上运行它时,它只能读取SD卡上的MP3。它不会从卡中存在的子文件夹中读取任何MP3。我想让它显示SD卡中的所有MP3(包括子文件夹)。
public class SongsManager {
// SDCard Path
final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath());
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Constructor
public SongsManager(){
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
* */
public ArrayList<HashMap<String, String>> getPlayList(){
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which are having .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
} }
答案 0 :(得分:3)
Android SDK中有MusicRetriever示例。它使用ContentResolver。
答案 1 :(得分:1)
File home = new File(MEDIA_PATH);
然后
walkdir(home);
WalkDir方法
public void walkdir(File dir) {
String Pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(Pattern)){
//Do what ever u want
// add the path to hash map
}
}
}
}
}
更好地使用增强的for循环,如blackbelt @
所示Delete only .jpg files from folder in android
而不是删除添加hahsmap的路径