MediaStore里有个file表,里面有个列提供文件所在目录的索引号(见官网http://developer.android.com/reference/android/provider/MediaStore.Files.FileColumns.html#PARENT ),
虽然不知道这个索引号是来干什么的,但它却是目录的唯一标示,可以用它来统计信息。
以检索音频为例,使用这条select语句即可满足要求: select _data,count(parent) as num_of_songs from file_table where ( media_type = 2) group by (parent); 换成变量名就是: select FileColumns.DATA,count(FileColumns.PARENT) as num_of_songs where (FileColumns.MEDIA_TYPE = FileColumns.MEDIA_TYPE_AUDIO) group by (FileColumns.PARENT);
然后用ContentResolver来query一下,获得cursor,用cursor获取到_data和num_of_songs列 _data就是文件的路径,截取一下就获得到了所在文件夹的路径及其名称,num_of_songs 就是文件夹里包含的歌曲数目
1 private String num_of_songs = "num_of_songs"; 2 3 /** 要从MediaStore检索的列 */ 4 private final String[] mProjection = new String[] { 5 MediaStore.Files.FileColumns.DATA, 6 "count(" + MediaStore.Files.FileColumns.PARENT + ") as " 7 + num_of_songs }; 8 /** where子句 */ 9 private String mSelection = MediaStore.Files.FileColumns.MEDIA_TYPE + " = " 10 + MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO + " ) " 11 + " group by ( " + MediaStore.Files.FileColumns.PARENT; 12 @Override 13 public List<FolderInfo> loadInBackground() { 14 Log.i(TAG, "loadInBackground"); 15 String filepath, folderpath, foldername; 16 int song_num = 0; 17 18 Cursor cursor = mContentResolver.query( 19 MediaStore.Files.getContentUri("external"), mProjection, 20 mSelection, null, null); 21 int index_data = cursor 22 .getColumnIndex(MediaStore.Files.FileColumns.DATA); 23 int index_num_of_songs = cursor.getColumnIndex(num_of_songs); 24 25 List<FolderInfo> itemsList = new ArrayList<FolderInfo>(); 26 27 // 将数据库查询结果保存到一个List集合中(存放在RAM) 28 if (cursor != null) { 29 while (cursor.moveToNext()) { 30 FolderInfo item = new FolderInfo(); 31 32 // 获取每个目录下的歌曲数量 33 song_num = cursor.getInt(index_num_of_songs); 34 item.setNumOfTracks(song_num); 35 36 // 获取文件的路径,如/storage/sdcard0/MIUI/music/Baby.mp3 37 filepath = cursor.getString(index_data); 38 39 // 获取文件所属文件夹的路径,如/storage/sdcard0/MIUI/music 40 folderpath = filepath.substring(0, 41 filepath.lastIndexOf(File.separator)); 42 43 // 获取文件所属文件夹的名称,如music 44 foldername = folderpath.substring(folderpath 45 .lastIndexOf(File.separator) + 1); 46 item.setFolderName(foldername); 47 item.setFolderPath(folderpath); 48 49 itemsList.add(item); 50 } 51 } 52 // 如果没有扫描到媒体文件,itemsList的size为0,因为上面new过了 53 return itemsList; 54 }