Android媒体数据库操作

1.获取媒体数据所有的图片、音频、视频、文件;
2.分页获取媒体数据的图片、音频、视频、文件;
3.删除媒体数据的图片、音频、视频、文件;
4.检查媒体数据的图片、音频、视频、文件是否存在;(文件删除需要_Data字段;
5.获取媒音乐对应的封面(第三方音乐软件下载到本地的歌曲,获取不到,媒体数据中不保存该封面,只有自己的服务器下载的带封面的歌曲能够保存在媒体数据库中);
6.媒体数据库更新的方法;

package xxx;
/**
 * 本地资源获取接口.
 */
public class MediaOptionManager {
    private static final float RADIUS = 30;
    private static final int ZERO = 0;
    private static MediaOptionManager mMediaOptionManager;
    public static final String IMAGE = "picture";
    public static final String VIDEO = "video";
    public static final String AUDIO = "audio";
    public static final String FILE = "file";
    private static final int PAGE_COUNT = 20;
    private static final int INDEX = 6;
    private static final String TAG = "MediaOptionManager";
    public static DateFormat formatAll = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static DateFormat YMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private DateFormat formatYms = new SimpleDateFormat("yyyy-MM-dd");//把long转成String
    public static SimpleDateFormat formatNyr = new SimpleDateFormat("yyyy年MM月dd日");
    private static final Uri ARTWORKURI = Uri.parse("content://media/external/audio/albumart");
    private static final BitmapFactory.Options BITMAPOPTIONS = new BitmapFactory.Options();
    private static Bitmap mCachedBit = null;
    private static final String[] IMAGE_PROJECTION = {
        MediaStore.Images.ImageColumns._ID,
        MediaStore.Images.ImageColumns.DATA,
        MediaStore.Images.ImageColumns.DISPLAY_NAME,
        MediaStore.Images.ImageColumns.DATE_TAKEN,
        MediaStore.Images.ImageColumns.SIZE};

    private static final String[] VIDEO_PROJECTION = {
        MediaStore.Video.VideoColumns._ID,
        MediaStore.Video.VideoColumns.DATA,
        MediaStore.Video.VideoColumns.DISPLAY_NAME,
        MediaStore.Video.VideoColumns.DATE_TAKEN,
        MediaStore.Video.VideoColumns.SIZE};

    private static final String[] AUDIO_PROJECTION = {
        MediaStore.Audio.Media._ID,
        MediaStore.Audio.AudioColumns.DATA,
        MediaStore.Audio.AudioColumns.DISPLAY_NAME,
        MediaStore.Audio.AudioColumns.DATE_MODIFIED,
        MediaStore.Audio.AudioColumns.SIZE,
        MediaStore.Audio.Media.ALBUM_ID,
        MediaStore.Audio.Media.ARTIST
    };

    private static final String[] FILE_PROJECTION = {
        MediaStore.Files.FileColumns._ID,
        MediaStore.Files.FileColumns.DATA,
        MediaStore.Files.FileColumns.DISPLAY_NAME,
        MediaStore.Files.FileColumns.DATE_MODIFIED,
        MediaStore.Files.FileColumns.MIME_TYPE,
        MediaStore.Files.FileColumns.SIZE};

    private MediaOptionManager() {
    }

    /**
     * MediaOptionManager单例.
     *
     * @return MediaOptionManager
     */
    public static MediaOptionManager getInstance() {
        if (mMediaOptionManager == null) {
            mMediaOptionManager = new MediaOptionManager();
        }
        return mMediaOptionManager;
    }

    /**
     * 获取所有的图片.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllImage(Context context) {
        ArrayList<GridItem> GirdList = new ArrayList();
        String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " desc";
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                null, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "count=" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String id = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    LogUtils.dTag(TAG, "fileName=" + fileName);
                    GridItem item = new GridItem(id, fileName, path, "", sDate, false,
                            false, String.valueOf(date), size, false);
                    GirdList.add(item);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return GirdList;
    }

    /**
     * 获取所有的图片.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllImageName(Context context) {
        ArrayList<String> list = new ArrayList();
        String orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " desc";
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                null, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "count=" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                    list.add(fileName);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 分页获取Image.
     *
     * @param context 上下文
     * @param pageNum 页码
     * @return list
     */
    public static ArrayList getImagesByPage(Context context, int pageNum) {
        ArrayList<GridItem> GirdList = new ArrayList();
        int offset = (pageNum - 1) * PAGE_COUNT;
        int max = pageNum * PAGE_COUNT;
        LogUtils.dTag(TAG, "offset=" + offset + ";max=" + max);
        // limit start, every time get the num of records
        String orderBy = MediaStore.Images.ImageColumns.DATE_MODIFIED + " desc limit " + offset + "," + PAGE_COUNT;
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                null, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "count=" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String id = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                    if (size == 0) {
                        continue;
                    }
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    LogUtils.dTag(TAG, "fileName=" + fileName);
                    GridItem item = new GridItem(id, fileName, path, "", sDate, false,
                            false, String.valueOf(date), size, false);
                    GirdList.add(item);
                } while (cursor.moveToNext());
            }
            cursor.close();
            cursor = null;
        }
        return GirdList;
    }


    /**
     * 获取所有的Video.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllVideo(Context context) {
        ArrayList<GridItem> GirdList = new ArrayList();
//        int offset = (pageNum - 1) * PAGE_COUNT;
//        int max = pageNum * PAGE_COUNT;
//         LogUtils.dTag(TAG, "offset=" + offset + ";max=" + max);
//        String orderBy = MediaStore.Video.VideoColumns.DATE_MODIFIED +
//                " desc  limit " + offset + "," + max;
        String orderBy = MediaStore.Video.VideoColumns.DATE_MODIFIED + " desc";
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION,
                null, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(VIDEO_PROJECTION[1]));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(VIDEO_PROJECTION[2]));
                    LogUtils.dTag(TAG, "-fileName->" + fileName);
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    LogUtils.dTag(TAG, "fileName=" + fileName);
                    GridItem mGridItem = new GridItem(fileName, path, sDate, true, false, String.valueOf(date), size);
                    GirdList.add(mGridItem);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return GirdList;
    }

    /**
     * 获取所有的Video.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllVideoName(Context context) {
        ArrayList<String> list = new ArrayList();
        String orderBy = MediaStore.Video.VideoColumns.DATE_MODIFIED + " desc";
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION,
                null, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(VIDEO_PROJECTION[2]));
                    list.add(fileName);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 分页获取videos.
     *
     * @param context 上下文
     * @param pageNum 页码
     * @return list
     */
    public static ArrayList getVideosByPage(Context context, int pageNum) {
        ArrayList<GridItem> GirdList = new ArrayList();
        int offset = (pageNum - 1) * PAGE_COUNT;
        int max = pageNum * PAGE_COUNT;
        LogUtils.dTag(TAG, "offset=" + offset + ";max=" + max);
        String orderBy = MediaStore.Video.VideoColumns.DATE_MODIFIED + " desc  limit " + offset + "," + PAGE_COUNT;
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION,
                null, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String id = cursor.getString(cursor.getColumnIndexOrThrow(VIDEO_PROJECTION[0]));
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(VIDEO_PROJECTION[1]));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(VIDEO_PROJECTION[2]));
                    // LogUtils.dTag(TAG, "-fileName->" + fileName);
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                    if (size == 0) {
                        continue;
                    }
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    //LogUtils.dTag(TAG, "fileName=" + fileName);
                    GridItem item = new GridItem(id, fileName, path, "", sDate, true,
                            false, String.valueOf(date), size, false);
                    GirdList.add(item);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return GirdList;
    }

    /**
     * 获取所有的audio.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllAudio(Context context) {
        ArrayList<GridItem> GirdList = new ArrayList();
        String orderBy = MediaStore.Audio.AudioColumns.DATE_MODIFIED + " desc ";
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, AUDIO_PROJECTION,
                null, null, orderBy);
        LogUtils.dTag(TAG, "-cursor->" + cursor.getCount());
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[1]));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[2]));
                    LogUtils.dTag(TAG, "-fileName->" + fileName);
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[4]));
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    LogUtils.dTag(TAG, "fileName=" + fileName);
                    GridItem mGridItem = new GridItem(fileName, path, sDate, false, false, String.valueOf(date), size);
                    GirdList.add(mGridItem);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return GirdList;
    }

    /**
     * 获取所有的audio.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllAudioName(Context context) {
        ArrayList<String> list = new ArrayList();
        String orderBy = MediaStore.Audio.AudioColumns.DATE_MODIFIED + " desc ";
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, AUDIO_PROJECTION,
                null, null, orderBy);
        LogUtils.dTag(TAG, "-cursor->" + cursor.getCount());
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[2]));
                    list.add(fileName);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 分页获取audios.
     *
     * @param context 上下文
     * @param pageNum 页码
     * @return List
     */
    public static ArrayList getAudiosByPage(Context context, int pageNum) {
        ArrayList<GridItem> GirdList = new ArrayList();
        int offset = (pageNum - 1) * PAGE_COUNT;
        int max = pageNum * PAGE_COUNT;
        LogUtils.dTag(TAG, "offset=" + offset + ";max=" + max);
        String orderBy = MediaStore.Audio.AudioColumns.DATE_MODIFIED + " desc  limit " + offset + "," + PAGE_COUNT;
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, AUDIO_PROJECTION,
                null, null, orderBy);
        LogUtils.dTag(TAG, "-cursor->" + cursor.getCount());
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String id = cursor.getString(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[0]));
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[1]));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[2]));
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[4]));
                    if (size == 0) {
                        continue;
                    }
                    int albumId = cursor.getInt(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[5]));
                    String artist = cursor.getString(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[INDEX]));
                    long songId = cursor.getInt(cursor.getColumnIndexOrThrow(AUDIO_PROJECTION[0]));
                    Bitmap albumArt = getArtwork(context, songId, albumId, true);
                    //Bitmap albumArt = null;
                    String cover = "";
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    String lrcPath = path.substring(0, path.lastIndexOf("."))
                            + ".lrc";
                    GridItem gridItem = new GridItem(songId + "", fileName, path, sDate, false,
                            false, String.valueOf(date), size, getRoundedCornerBitmap(albumArt,
                            RADIUS), artist, lrcPath, false);
                    GirdList.add(gridItem);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return GirdList;
    }

    /**
     * 获取所有的file.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllFile(Context context) {
        ArrayList<GridItem> GirdList = new ArrayList();
        String orderBy = MediaStore.Files.FileColumns.DATE_MODIFIED + " desc ";
        String selection = MediaStore.Files.FileColumns.MIME_TYPE + "= ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? ";
        String select = "(_data LIKE '%.pdf')"
                + " or (_data LIKE '%.docx')"
                + " or (_data LIKE '%.doc')"
                + " or (_data LIKE '%.xls')"
                + " or (_data LIKE '%.xlsx')"
                + " or (_data LIKE '%.ppt')"
                + " or (_data LIKE '%.pptx')"
                + " or (_data LIKE '%.txt')";
        String[] selectionArgs = {
                "text/plain",
                "application/msword",
                "application/pdf",
                "application/vnd.ms-powerpoint",
                "application/vnd.ms-excel"};
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Files.getContentUri("external"), FILE_PROJECTION,
                select, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PROJECTION[1]));
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PROJECTION[2]));
                    LogUtils.dTag(TAG, "-fileName->" + fileName);
                    LogUtils.dTag(TAG, "-path->" + path);
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(FILE_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(FILE_PROJECTION[5]));
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    LogUtils.dTag(TAG, "fileName=" + fileName);
                    GridItem mGridItem = new GridItem(fileName, path, sDate, false, false, String.valueOf(date), size);
                    GirdList.add(mGridItem);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return GirdList;
    }

    /**
     * 获取所有的file.
     *
     * @param context 上下文
     * @return list
     */
    public static ArrayList getAllFileName(Context context) {
        ArrayList<String> list = new ArrayList();
        String orderBy = MediaStore.Files.FileColumns.DATE_MODIFIED + " desc ";
        String select = "(_data LIKE '%.pdf')"
                + " or (_data LIKE '%.docx')"
                + " or (_data LIKE '%.doc')"
                + " or (_data LIKE '%.xls')"
                + " or (_data LIKE '%.xlsx')"
                + " or (_data LIKE '%.ppt')"
                + " or (_data LIKE '%.pptx')"
                + " or (_data LIKE '%.txt')";
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Files.getContentUri("external"), FILE_PROJECTION,
                select, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String fileName = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PROJECTION[2]));
                    list.add(fileName);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 分页获取Files.
     *
     * @param context 上下文
     * @param pageNum 页码
     * @return list
     */
    public static ArrayList getFilesByPage(Context context, int pageNum) {
        ArrayList<GridItem> GirdList = new ArrayList();
        int offset = (pageNum - 1) * PAGE_COUNT;
        int max = pageNum * PAGE_COUNT;
        LogUtils.dTag(TAG, "offset=" + offset + ";max=" + max);
        String orderBy = MediaStore.Files.FileColumns.DATE_MODIFIED + " desc  limit " + offset + "," + PAGE_COUNT;
        String selection = MediaStore.Files.FileColumns.MIME_TYPE + "= ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? "
                + " or " + MediaStore.Files.FileColumns.MIME_TYPE + " = ? ";

        String select = "(_data LIKE '%.pdf')"
                + " or (_data LIKE '%.docx')"
                + " or (_data LIKE '%.doc')"
                + " or (_data LIKE '%.xls')"
                + " or (_data LIKE '%.xlsx')"
                + " or (_data LIKE '%.ppt')"
                + " or (_data LIKE '%.pptx')"
                + " or (_data LIKE '%.txt')";
        String[] selectionArgs = {
                "text/plain",
                "application/msword",
                "application/pdf",
                "application/vnd.ms-powerpoint",
                "application/vnd.ms-excel",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "application/x-excel",
                "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                "application/x-zip-compressed",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Files.getContentUri("external"), FILE_PROJECTION,
                select, null, orderBy);

        if (cursor != null) {
            if (cursor.getCount() > 0) {
                LogUtils.dTag(TAG, "-count->" + cursor.getCount());
                cursor.moveToFirst();
                do {
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PROJECTION[1]));
                    LogUtils.dTag(TAG, "-path->" + path);
                    //String fileName = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PROJECTION[2]));
                    String fileName = path.substring(path.lastIndexOf("/") + 1);
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(FILE_PROJECTION[3]));
                    long size = cursor.getLong(cursor.getColumnIndexOrThrow(FILE_PROJECTION[5]));
                    if (size == 0) {
                        continue;
                    }
                    Date dt = new Date(date);
                    String sDate = formatNyr.format(dt);//将long变stri
                    String id = cursor.getString(cursor.getColumnIndexOrThrow(FILE_PROJECTION[0]));
                    GridItem item = new GridItem(id, fileName, path, "", sDate, false,
                            false, String.valueOf(date), size, false);
                    GirdList.add(item);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return GirdList;
    }


    /**
     * 删除文件.
     *
     * @param context   上下文
     * @param gridItem  item
     * @param mediaType mediaType
     */
    public static void deleteFileFromDatabase(Context context, GridItem gridItem, String mediaType) {
        ContentResolver mContentResolver = context.getContentResolver();
        Uri uri;
        String where;
        if (mediaType.equals(VIDEO)) {
            uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            where = MediaStore.Video.Media.DATA + "='" + gridItem.getPath() + "'";
        } else if (mediaType.equals(IMAGE)) {
            uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            where = MediaStore.Images.Media.DATA + "='" + gridItem.getPath() + "'";
        } else if (mediaType.equals(AUDIO)) {
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            where = MediaStore.Audio.Media.DATA + "='" + gridItem.getPath() + "'";
        } else {
            //mMediaType.equals(FILE
            uri = MediaStore.Files.getContentUri("external");
            where = MediaStore.Files.FileColumns.DATA + "='" + gridItem.getPath() + "'";
        }
        mContentResolver.delete(uri, where, null);
    }

    /**
     * check File是否存在.
     *
     * @param context   context
     * @param mediaType mediaType
     * @param fileName  fileName
     * @return 是否存在该文件
     */
    public static boolean checkFile(Context context, String mediaType, String fileName) {
        Uri uri;
        String where;
        if (mediaType.equals(VIDEO)) {
            uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            where = MediaStore.Video.Media.DISPLAY_NAME + "='" + fileName + "'";
        } else if (mediaType.equals(IMAGE)) {
            uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            where = MediaStore.Images.Media.DISPLAY_NAME + "='" + fileName + "'";
        } else if (mediaType.equals(AUDIO)) {
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            where = MediaStore.Audio.Media.DISPLAY_NAME + "='" + fileName + "'";
        } else {
            //mMediaType.equals(FILE
            uri = MediaStore.Files.getContentUri("external");
            //DATA 的原因是因为DISPLAY_NAME可能为null,查询不到
            where = MediaStore.Files.FileColumns.DATA + "='" + LocalStoragePath.getBaseSavePath() + fileName + "'";
        }
        Cursor cursor = context.getContentResolver().query(uri, null,
                where, null, null);
        if (cursor != null) {
            if (cursor.getCount() > 0) {
                return true;
            }
            cursor.close();
        }
        return false;
    }

    /**
     * getArtwork.
     *
     * @param context      context
     * @param songId       songId
     * @param albumId      albumId
     * @param allowdefault allowdefault
     * @return bm
     */
    public static Bitmap getArtwork(Context context, long songId, long albumId,
                                    boolean allowdefault) {
        if (albumId < 0) {
            // This is something that is not in the database, so get the album art directly
            // from the file.
            if (songId >= 0) {
                Bitmap bm = getArtworkFromFile(context, songId, -1);
                if (bm != null) {
                    return bm;
                }
            }
            if (allowdefault) {
                return getDefaultArtwork(context);
            }
            return null;
        }
        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(ARTWORKURI, albumId);
        if (uri != null) {
            InputStream in = null;
            try {
                in = res.openInputStream(uri);
                return BitmapFactory.decodeStream(in, null, BITMAPOPTIONS);
            } catch (FileNotFoundException ex) {
                // The album art thumbnail does not actually exist. Maybe the user deleted it, or
                // maybe it never existed to begin with.
                Bitmap bm = getArtworkFromFile(context, songId, albumId);
                if (bm != null) {
                    if (bm.getConfig() == null) {
                        bm = bm.copy(Bitmap.Config.RGB_565, false);
                        if (bm == null && allowdefault) {
                            return getDefaultArtwork(context);
                        }
                    }
                } else if (allowdefault) {
                    bm = getDefaultArtwork(context);
                }
                return bm;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

            }
        }

        return null;
    }

    private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
        Bitmap bm = null;
        byte[] art = null;
        String path = null;
        if (albumid < 0 && songid < 0) {
            throw new IllegalArgumentException("Must specify an album or a song id");
        }
        try {
            if (albumid < 0) {
                Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd);
                }
            } else {
                Uri uri = ContentUris.withAppendedId(ARTWORKURI, albumid);
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    FileDescriptor fd = pfd.getFileDescriptor();
                    bm = BitmapFactory.decodeFileDescriptor(fd);
                }
            }
        } catch (FileNotFoundException ex) {

        }
        if (bm != null) {
            mCachedBit = bm;
        }
        return bm;
    }

    @SuppressLint("ResourceType")
    private static Bitmap getDefaultArtwork(Context context) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeStream(
                context.getResources().openRawResource(R.drawable.shape_019ea1_12), null, opts);
    }

    /**
     * getRoundedCornerBitmap.
     *
     * @param bitmap  bitmap
     * @param roundPx roundPx
     * @return bm
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        if (bitmap == null) {
            return null;
        }
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(ZERO, ZERO, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(ZERO, ZERO, ZERO, ZERO);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
}

资源实体类

package xxx;
import android.graphics.Bitmap;
import java.io.Serializable;
public class GridItem implements Serializable {
    private String id;
    private String path;
    private String thumb;
    private String name;
    private String time;
    private boolean isVedio;
    private int section;
    private boolean isChecked;
    private String lastModified;
    private long size;
    private String cover;//音乐专辑图片
    private Bitmap bitmap;//音乐专辑图片bitmap
    private String categoryName; //聚合照片类名
    private String categoryId;
    private boolean isCloud;
    private String artist;
    private String lyric;

    /**
     * GridItem 实体.
     *
     * @param name         name
     * @param path         path
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     */
    public GridItem(String name, String path, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size) {
        super();
        this.name = name;
        this.path = path;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
    }

    /**
     * GridItem 实体.
     *
     * @param id           id
     * @param name         name
     * @param path         path
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     */
    public GridItem(String id, String name, String path, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size) {
        super();
        this.id = id;
        this.name = name;
        this.path = path;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
    }

    /**
     * GridItem 实体.
     *
     * @param id           id
     * @param name         name
     * @param path         path
     * @param thumb        thumb
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     * @param categoryId   categoryId
     * @param cloud        cloud
     */
    public GridItem(String id, String name, String path,String thumb, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size, String categoryId, boolean cloud) {
        super();
        this.id = id;
        this.name = name;
        this.path = path;
        this.thumb = thumb;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
        this.categoryId = categoryId;
        this.isCloud = cloud;
    }

    /**
     * GridItem 实体.
     *
     * @param id           id
     * @param name         name
     * @param path         path
     * @param thumb        thumb
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     * @param cloud        cloud
     */
    public GridItem(String id, String name, String path, String thumb, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size, boolean cloud) {
        super();
        this.id = id;
        this.name = name;
        this.path = path;
        this.thumb = thumb;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
        this.isCloud = cloud;
    }

    /**
     * GridItem 实体.
     *
     * @param name         name
     * @param path         path
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     * @param categoryName categoryName
     */
    public GridItem(String name, String path, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size, String categoryName) {
        super();
        this.name = name;
        this.path = path;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
        this.categoryName = categoryName;
    }

    /**
     * GridItem 实体.
     *
     * @param id           id
     * @param name         name
     * @param path         path
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     * @param cover        cover
     * @param artist       artist
     * @param lyric        lyric
     * @param cloud        cloud
     */
    public GridItem(String id, String name, String path, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size, String cover,
                    String artist, String lyric, boolean cloud) {
        super();
        this.id = id;
        this.name = name;
        this.path = path;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
        this.cover = cover;
        this.artist = artist;
        this.lyric = lyric;
        this.isCloud = cloud;
    }

    /**
     * GridItem 实体.
     *
     * @param id           id
     * @param name         name
     * @param path         path
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     * @param bitmap       bitmap
     * @param artist       artist
     * @param lyric        lyric
     * @param cloud        cloud
     */
    public GridItem(String id, String name, String path, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size, Bitmap bitmap,
                    String artist, String lyric, boolean cloud) {
        super();
        this.id = id;
        this.name = name;
        this.path = path;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
        this.bitmap = bitmap;
        this.artist = artist;
        this.lyric = lyric;
        this.isCloud = cloud;
    }

    /**
     * GridItem 实体.
     *
     * @param id           id
     * @param name         name
     * @param path         path
     * @param thumb        thumb
     * @param time         time
     * @param isVedio      isVedio
     * @param isChecked    isChecked
     * @param lastModified lastModified
     * @param size         size
     * @param cover        cover
     * @param artist       artist
     * @param lyric        lyric
     * @param cloud        cloud
     */
    public GridItem(String id, String name, String path, String thumb, String time, boolean isVedio,
                    boolean isChecked, String lastModified, long size, String cover,
                    String artist, String lyric, boolean cloud) {
        super();
        this.id = id;
        this.name = name;
        this.path = path;
        this.thumb = thumb;
        this.time = time;
        this.isVedio = isVedio;
        this.lastModified = lastModified;
        this.size = size;
        this.cover = cover;
        this.artist = artist;
        this.lyric = lyric;
        this.isCloud = cloud;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public boolean isVedio() {
        return isVedio;
    }

    public void setVedio(boolean vedio) {
        isVedio = vedio;
    }

    public int getSection() {
        return section;
    }

    public void setSection(int section) {
        this.section = section;
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        isChecked = checked;
    }

    public String getLastModified() {
        return lastModified;
    }

    public void setLastModified(String lastModified) {
        this.lastModified = lastModified;
    }

    public long getSize() {
        return size;
    }

    public void setSize(long size) {
        this.size = size;
    }

    public String getCover() {
        return cover;
    }

    public void setCover(String cover) {
        this.cover = cover;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public boolean isCloud() {
        return isCloud;
    }

    public void setCloud(boolean cloud) {
        isCloud = cloud;
    }

    public String getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getLyric() {
        return lyric;
    }

    public void setLyric(String lyric) {
        this.lyric = lyric;
    }

    public String getThumb() {
        return thumb;
    }

    public void setThumb(String thumb) {
        this.thumb = thumb;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
}

媒体数据库更新的方法
方法一:扫描某一个目录

sendBroadcast(new Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.parse(filePath));

方法二:扫描摸一个文件

 String path = LocalStoragePath.getBaseSavePath() + fileName;
        new SingleMediaScanner(this.mContext, new File(path));

SingleMediaScanner:

package xxx;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import java.io.File;
/**
 * 媒体数据库刷新.
 */
public class SingleMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {

    private MediaScannerConnection mMs;
    private File mFile;
    /**
     * SingleMediaScanner.
     *
     * @param context context
     * @param file    file
     */
    public SingleMediaScanner(Context context, File file) {
        mFile = file;
        mMs = new MediaScannerConnection(context, this);
        mMs.connect();
    }
    @Override
    public void onMediaScannerConnected() {
        mMs.scanFile(mFile.getAbsolutePath(), null);
    }
    @Override
    public void onScanCompleted(String path, Uri uri) {
        mMs.disconnect();
        Log.d("TAG", "Finished scanning " + path);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,377评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,390评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,967评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,344评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,441评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,492评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,497评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,274评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,732评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,008评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,184评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,837评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,520评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,156评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,407评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,056评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,074评论 2 352