注意,操作后需要调用cursor.close()将cursor关闭.
例子:
1.
/** * 获取sd卡指定格式的音频文件url * * @return * @throws Exception */ public static ArrayListgetAllAudios(Context context) { ArrayList audios = new ArrayList (); Uri audioUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; String[] projection = {MediaStore.Audio.Media.DATA}; String[] extension = {"audio/x-mpegurl", "audio/mp4a-latm","audio/mp4a-latm","audio/mp4a-latm","audio/x-mpeg","audio/x-mpeg","audio/mpeg","audio/ogg","audio/x-pn-realaudio","audio/x-wav","audio/x-ms-wma","audio/x-ms-wmv" }; //构造筛选语句 String selection = ""; for (int i = 0; i < extension.length; i++) { if (i != 0) { selection = selection + " OR "; } selection = selection + MediaStore.Audio.Media.MIME_TYPE + "='" + extension[i] + "'"; } //按时间递增顺序对结果进行排序;待会从后往前移动游标就可实现时间递减 String sortOrder = MediaStore.Audio.Media.DATE_MODIFIED; Cursor cursor = context.getContentResolver().query( audioUri, projection, selection, null, sortOrder); if (cursor.moveToFirst()) { do{ //输出文件的完整路径 String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); Log.d("tag", data); audios.add(data); } while (cursor.moveToNext()); cursor.close(); } return audios; }
2.
/** * 根据文件后缀名称 获取手机上所有的文件的url路径 * @param context * @param extension 后缀名 .doc 等字符串数组 * @return 文件url路径 */ public static ListgetSpecificTypeOfFile(Context context, String[] extension) { List paths = new ArrayList<>(); //从外存中获取 Uri fileUri = MediaStore.Files.getContentUri("external"); //筛选列,这里只筛选了:文件路径和不含后缀的文件名 String[] projection = new String[]{ MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.TITLE }; //构造筛选语句 String selection = ""; for (int i = 0; i < extension.length; i++) { if (i != 0) { selection = selection + " OR "; } selection = selection + MediaStore.Files.FileColumns.DATA + " LIKE '%" + extension[i] + "'"; } //按时间递增顺序对结果进行排序;待会从后往前移动游标就可实现时间递减 String sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED; //获取内容解析器对象 ContentResolver resolver = context.getContentResolver(); //获取游标 Cursor cursor = resolver.query(fileUri, projection, selection, null, sortOrder); if (cursor == null) return paths; //游标从最后开始往前递减,以此实现时间递减顺序(最近访问的文件,优先显示) if (cursor.moveToLast()) { do { //输出文件的完整路径 // String data = cursor.getString(0); String data = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)); Log.d("tag", data); paths.add(data); } while (cursor.moveToPrevious()); } cursor.close(); return paths; }