makisang / android

0 stars 0 forks source link

MediaStore获取手机里面的文件 #19

Open makisang opened 8 years ago

makisang commented 8 years ago

之前是通过递归来获取手机里面的 .txt 文件的,速度非常慢,后来发现通过 MediaStore 类可以非常方便地实现这个功能

    public static ArrayList<BookData> getFilesFromMediaStore(ContentResolver cr) {
        // 获取ContentProvider的Uri
        Uri externalUri = MediaStore.Files.getContentUri("external");
        Cursor cursor = cr.query(externalUri, null,
                MediaStore.Files.FileColumns.MIME_TYPE + "=?",
                new String[]{"text/plain"},
                MediaStore.Files.FileColumns.DATE_MODIFIED + " desc");
        Log.d(TAG, "MediaStore text/plain count: " + cursor.getCount());
        while (cursor.moveToNext()) {
            // 绝对路径
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
            // 不包含扩展名的文件名称
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE));
            // 文件大小
            long size = Long.parseLong(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE)));
            BookData book = new BookData(title, path, size);
            books.add(book);
        }
        cursor.close();
        ArrayList<BookData> anotherList = new ArrayList<>(books.size());
        anotherList.addAll(books);
        books.clear();
        return anotherList;
    }

MediaStore 的数据库文件位于/data/data/com.android.providers/databases