我的代码如下。它在我的外部SD卡存储中找到所有mp3。我需要从内部存储中读取所有mp3文件。 MediaStore对我来说很复杂。我设法在一年前做到了,但丢失了文件。如果有人可以帮助我,那就太好了。我无法轻易找到我需要的信息,我在这里搜索。这将对我有很大帮助,所以回答或建议将得到很好的赞赏。谢谢。
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
public class SongsManager {
final String MEDIA_PATH = MediaStore.Audio.Media.IS_MUSIC + " != 0";
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private String mp3Pattern = ".mp3";
// Constructor
public SongsManager() {
}
/**
* Function to read all mp3 files from sdcard
* and store the details in ArrayList
*/
public ArrayList<HashMap<String, String>> getPlayList() {
System.out.println(MEDIA_PATH);
if (MEDIA_PATH != null) {
File home = new File(MEDIA_PATH);
File[] listFiles = home.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
System.out.println(file.getAbsolutePath());
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
// return songs list array
return songsList;
}
private void scanDirectory(File directory) {
if (directory != null) {
File[] listFiles = directory.listFiles();
if (listFiles != null && listFiles.length > 0) {
for (File file : listFiles) {
if (file.isDirectory()) {
scanDirectory(file);
} else {
addSongToList(file);
}
}
}
}
}
private void addSongToList(File song) {
if (song.getName().endsWith(mp3Pattern)) {
HashMap<String, String> songMap = new HashMap<String, String>();
songMap.put("songTitle",
song.getName().substring(0, (song.getName().length() - 4)));
songMap.put("songPath", song.getPath());
// Adding each song to SongList
songsList.add(songMap);
}
}
/**
* 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"));
}
}
}