Android使用ContentResolver获取系统相册图片、音乐文件、通讯录联系人

偷懒直接使用AS的GsonFormat插件和Gson直接将所有字段解析成对应的model类。

1. ContentResolverHelper类

/**
 * Created by lykevin on 2018/4/9.
 */
public class ContentResolverHelper {
    private static final String TAG = "ContentResolverHelper";
    private static Gson gson;
    private ContentResolverHelper() {
    }

    /**
     * 从系统相册中获取图片
     *
     * @param contextWrapper
     * @return
     */
    public static List queryImagesFromExternal(ContextWrapper contextWrapper) {
        List imageModelList = new ArrayList<>();
        Cursor cursor = contextWrapper.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            gson = new Gson();
            while (cursor.moveToNext()) {
                try {
                    JSONObject json = new JSONObject();
                    String[] columnNames = cursor.getColumnNames();
                    for (String columnName : columnNames) {
                        String s = cursor.getString(cursor.getColumnIndex(columnName));
                        json.put(columnName, s);
                    }
                    ImageModel imageModel = gson.fromJson(json.toString(), ImageModel.class);
                    imageModelList.add(imageModel);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            cursor.close();
        }
        return imageModelList;
    }

    /**
     * 获取系统中的音乐文件
     *
     * @param contextWrapper
     * @return
     */
    public static List queryMusicsFromExternal(ContextWrapper contextWrapper) {
        List musicModelList = new ArrayList<>();
        Cursor cursor = contextWrapper.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            gson = new Gson();
            while (cursor.moveToNext()) {
                try {
                    JSONObject json = new JSONObject();
                    String[] columnNames = cursor.getColumnNames();
                    for (String columnName : columnNames) {
                        String s = cursor.getString(cursor.getColumnIndex(columnName));
                        json.put(columnName, s);
                    }
                    MusicModel musicModel = gson.fromJson(json.toString(), MusicModel.class);
                    musicModelList.add(musicModel);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            cursor.close();
        }
        return musicModelList;
    }

    /**
     * 获取通讯录联系人
     *
     * @param contextWrapper
     * @return
     */
    public static List queryContacts(ContextWrapper contextWrapper) {
        List contactModelList = new ArrayList<>();
        Cursor cursor = contextWrapper.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            gson = new Gson();
            while (cursor.moveToNext()) {
                try {
                    JSONObject json = new JSONObject();
                    String[] columnNames = cursor.getColumnNames();
                    for (String columnName : columnNames) {
                        String s = cursor.getString(cursor.getColumnIndex(columnName));
                        json.put(columnName, s);
                    }
                    ContactModel contactModel = gson.fromJson(json.toString(), ContactModel.class);
                    contactModelList.add(contactModel);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            cursor.close();
        }
        return contactModelList;
    }
}

2. ImageModel类

public class ImageModel implements Parcelable {

    /**
     * _id : 173463
     * _data : /storage/emulated/0/DCIM/Camera/IMG_20180409_102543_BURST1.jpg
     * _size : 5440606
     * _display_name : IMG_20180409_102543_BURST1.jpg
     * mime_type : image/jpeg
     * title : IMG_20180409_102543_BURST1
     * date_added : 1523240743
     * date_modified : 1523240743
     * latitude : 24.5044
     * longitude : 118.142
     * datetaken : 1523240743224
     * orientation : 90
     * bucket_id : -1739773001
     * bucket_display_name : Camera
     * width : 4032
     * height : 3016
     */

    @SerializedName("_id")
    private String id;
    @SerializedName("_data")
    private String path;
    @SerializedName("_size")
    private long size;
    @SerializedName("_display_name")
    private String displayName;
    @SerializedName("mime_type")
    private String mimeType;
    private String title;
    @SerializedName("date_added")
    private long dateAdded;
    @SerializedName("date_modified")
    private long dateModified;
    private double latitude;
    private double longitude;
    @SerializedName("datetaken")
    private long dateTaken;
    private int orientation;
    private long bucket_id;
    private String bucket_display_name;
    private int width;
    private int height;
    private boolean isSelected;

    protected ImageModel(Parcel in) {
        id = in.readString();
        path = in.readString();
        size = in.readLong();
        displayName = in.readString();
        mimeType = in.readString();
        title = in.readString();
        dateAdded = in.readLong();
        dateModified = in.readLong();
        latitude = in.readDouble();
        longitude = in.readDouble();
        dateTaken = in.readLong();
        orientation = in.readInt();
        bucket_id = in.readLong();
        bucket_display_name = in.readString();
        width = in.readInt();
        height = in.readInt();
        isSelected = in.readByte() != 0;
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public ImageModel createFromParcel(Parcel in) {
            return new ImageModel(in);
        }

        @Override
        public ImageModel[] newArray(int size) {
            return new ImageModel[size];
        }
    };

    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 long getSize() {
        return size;
    }

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

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getMimeType() {
        return mimeType;
    }

    public void setMimeType(String mimeType) {
        this.mimeType = mimeType;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public long getDateAdded() {
        return dateAdded;
    }

    public void setDateAdded(long dateAdded) {
        this.dateAdded = dateAdded;
    }

    public long getDateModified() {
        return dateModified;
    }

    public void setDateModified(long dateModified) {
        this.dateModified = dateModified;
    }

    public double getLatitude() {
        return latitude;
    }

    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    public long getDateTaken() {
        return dateTaken;
    }

    public void setDateTaken(long dateTaken) {
        this.dateTaken = dateTaken;
    }

    public int getOrientation() {
        return orientation;
    }

    public void setOrientation(int orientation) {
        this.orientation = orientation;
    }

    public long getBucket_id() {
        return bucket_id;
    }

    public void setBucket_id(long bucket_id) {
        this.bucket_id = bucket_id;
    }

    public String getBucket_display_name() {
        return bucket_display_name;
    }

    public void setBucket_display_name(String bucket_display_name) {
        this.bucket_display_name = bucket_display_name;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(path);
        dest.writeLong(size);
        dest.writeString(displayName);
        dest.writeString(mimeType);
        dest.writeString(title);
        dest.writeLong(dateAdded);
        dest.writeLong(dateModified);
        dest.writeDouble(latitude);
        dest.writeDouble(longitude);
        dest.writeLong(dateTaken);
        dest.writeInt(orientation);
        dest.writeLong(bucket_id);
        dest.writeString(bucket_display_name);
        dest.writeInt(width);
        dest.writeInt(height);
        dest.writeByte((byte) (isSelected ? 1 : 0));
    }
}

3. MusicModel类

public class MusicModel {

/**
 * _id : 98061
 * _data : /storage/emulated/0/MIUI/ringtone/金光布袋戏 - 初心无悔 [mqms2].mp3
 * _display_name : 金光布袋戏 - 初心无悔 [mqms2].mp3
 * _size : 8522462
 * mime_type : audio/mpeg
 * date_added : 1515629643
 * is_drm : 0
 * date_modified : 1514789096
 * title : HKC371701671-初心无悔
 * title_key :
 * duration : 213032
 * artist_id : 29
 * album_id : 45
 * track : 0
 * is_ringtone : 0
 * is_music : 1
 * is_alarm : 0
 * is_notification : 0
 * is_podcast : 0
 * artist_id:1 : 29
 * artist_key :
 * artist : 金光布袋戏
 * album_id:1 : 45
 * album_key :
 * album : 金光御九界之东皇战影 剧集原声带
 */

@SerializedName("_id")
private String id;
@SerializedName("_data")
private String path;
@SerializedName("_display_name")
private String displayName;
@SerializedName("_size")
private long size;
@SerializedName("mime_type")
private String mimeType;
@SerializedName("date_added")
private long dateAdded;
@SerializedName("is_drm")
private boolean isDrm;
@SerializedName("date_modified")
private long dateModified;
private String title;
@SerializedName("title_key")
private String titleKey;
private long duration;
@SerializedName("artist_id")
private int artistId;
@SerializedName("album_id")
private int albumId;
private String track;
@SerializedName("is_ringtone")
private boolean isRingtone;
@SerializedName("is_music")
private boolean isMusic;
@SerializedName("is_alarm")
private boolean isAlarm;
@SerializedName("is_notification")
private boolean isNotification;
@SerializedName("is_podcast")
private boolean isPodcast;
@SerializedName("artist_id:1")
private int artistId_1;
@SerializedName("artist_key")
private String artistKey;
private String artist;
@SerializedName("album_id:1")
private int albumId_1;
private String album_key;
private String album;

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 getDisplayName() {
    return displayName;
}

public void setDisplayName(String displayName) {
    this.displayName = displayName;
}

public long getSize() {
    return size;
}

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

public String getMimeType() {
    return mimeType;
}

public void setMimeType(String mimeType) {
    this.mimeType = mimeType;
}

public long getDateAdded() {
    return dateAdded;
}

public void setDateAdded(long dateAdded) {
    this.dateAdded = dateAdded;
}

public boolean isDrm() {
    return isDrm;
}

public void setIsDrm(boolean isDrm) {
    this.isDrm = isDrm;
}

public long getDateModified() {
    return dateModified;
}

public void setDateModified(long dateModified) {
    this.dateModified = dateModified;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getTitleKey() {
    return titleKey;
}

public void setTitleKey(String titleKey) {
    this.titleKey = titleKey;
}

public long getDuration() {
    return duration;
}

public void setDuration(long duration) {
    this.duration = duration;
}

public int getArtistId() {
    return artistId;
}

public void setArtistId(int artistId) {
    this.artistId = artistId;
}

public int getAlbumId() {
    return albumId;
}

public void setAlbumId(int albumId) {
    this.albumId = albumId;
}

public String getTrack() {
    return track;
}

public void setTrack(String track) {
    this.track = track;
}

public boolean isRingtone() {
    return isRingtone;
}

public void setIsRingtone(boolean isRingtone) {
    this.isRingtone = isRingtone;
}

public boolean isMusic() {
    return isMusic;
}

public void setIsMusic(boolean isMusic) {
    this.isMusic = isMusic;
}

public boolean isAlarm() {
    return isAlarm;
}

public void setIsAlarm(boolean isAlarm) {
    this.isAlarm = isAlarm;
}

public boolean isNotification() {
    return isNotification;
}

public void setIsNotification(boolean isNotification) {
    this.isNotification = isNotification;
}

public boolean isPodcast() {
    return isPodcast;
}

public void setIsPodcast(boolean isPodcast) {
    this.isPodcast = isPodcast;
}

public int getArtistId_1() {
    return artistId_1;
}

public void setArtistId_1(int artistId_1) {
    this.artistId_1 = artistId_1;
}

public String getArtistKey() {
    return artistKey;
}

public void setArtistKey(String artistKey) {
    this.artistKey = artistKey;
}

public String getArtist() {
    return artist;
}

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

public int getAlbumId_1() {
    return albumId_1;
}

public void setAlbumId_1(int albumId_1) {
    this.albumId_1 = albumId_1;
}

public String getAlbum_key() {
    return album_key;
}

public void setAlbum_key(String album_key) {
    this.album_key = album_key;
}

public String getAlbum() {
    return album;
}

public void setAlbum(String album) {
    this.album = album;
}
}

4. ContactModel类

public class ContactModel {

/**
 * account_type : com.xiaomi
 * data_version : 0
 * name_verified : 0
 * display_name_alt : 叶海
 * sort_key_alt : 叶海
 * starred : 0
 * has_phone_number : 1
 * raw_contact_id : 304
 * contact_account_type : com.xiaomi
 * carrier_presence : 0
 * contact_last_updated_timestamp : 1516769191377
 * phonebook_bucket : 25
 * display_name : 叶海
 * sort_key : 叶海
 * version : 3
 * in_default_directory : 1
 * times_contacted : 0
 * _id : 957
 * account_type_and_data_set : com.xiaomi
 * name_raw_contact_id : 304
 * phonebook_bucket_alt : 25
 * last_time_contacted : 0
 * pinned : 0
 * is_primary : 0
 * contact_id : 339
 * in_visible_group : 1
 * phonebook_label : Y
 * account_name : 412979213
 * display_name_source : 40
 * dirty : 0
 * sourceid : 32302221821509761
 * phonetic_name_style : 0
 * send_to_voicemail : 0
 * lookup : 3430i32302221821509761
 * phonebook_label_alt : Y
 * is_super_primary : 0
 * data4 : 19999999999
 * data2 : 2
 * data1 : 199 9999 9999
 * raw_contact_is_user_profile : 0
 * mimetype : vnd.android.cursor.item/phone_v2
 */

@SerializedName("account_type")
private String accountType;
@SerializedName("data_version")
private String dataVersion;
@SerializedName("name_verified")
private String nameVerified;
@SerializedName("display_name_alt")
private String displayNameAlt;
@SerializedName("sort_key_alt")
private String sortKeyAlt;
private String starred;
@SerializedName("has_phone_number")
private boolean hasPhoneNumber;
@SerializedName("raw_contact_id")
private String rawContactId;
@SerializedName("contact_account_type")
private String contactAccountType;
@SerializedName("carrier_presence")
private String carrierPresence;
@SerializedName("contact_last_updated_timestamp")
private long contactLastPpdatedTimestamp;
@SerializedName("phonebook_bucket")
private int phonebookBucket;
@SerializedName("display_name")
private String displayName;
@SerializedName("sort_key")
private String sortKey;
private String version;
@SerializedName("in_default_directory")
private boolean inDefaultdirectory;
@SerializedName("times_contacted")
private int timesContacted;
@SerializedName("_id")
private String id;
@SerializedName("account_type_and_data_set")
private String accountTypeAndDataSet;
@SerializedName("name_raw_contact_id")
private String nameRawContactId;
@SerializedName("phonebook_bucket_alt")
private String phonebookBucketAlt;
@SerializedName("last_time_contacted")
private String lastTimeContacted;
private String pinned;
@SerializedName("is_primary")
private boolean isPrimary;
@SerializedName("contact_id")
private String contactId;
@SerializedName("in_visible_group")
private boolean inVisibleGroup;
@SerializedName("phonebook_label")
private String phonebookLabel;
@SerializedName("account_name")
private String accountName;
@SerializedName("display_name_source")
private String displayNameSource;
private String dirty;
private String sourceid;
@SerializedName("phonetic_name_style")
private String phoneticNameStyle;
@SerializedName("send_to_voicemail")
private String sendToVoicemail;
private String lookup;
@SerializedName("phonebook_label_alt")
private String phonebookLabelAlt;
@SerializedName("is_super_primary")
private boolean isSuperPrimary;
private String data4;
private String data2;
private String data1;
@SerializedName("raw_contact_is_user_profile")
private String rawContactIsUserProfile;
private String mimetype;

public String getAccountType() {
    return accountType;
}

public void setAccountType(String accountType) {
    this.accountType = accountType;
}

public String getDataVersion() {
    return dataVersion;
}

public void setDataVersion(String dataVersion) {
    this.dataVersion = dataVersion;
}

public String getNameVerified() {
    return nameVerified;
}

public void setNameVerified(String nameVerified) {
    this.nameVerified = nameVerified;
}

public String getDisplayNameAlt() {
    return displayNameAlt;
}

public void setDisplayNameAlt(String displayNameAlt) {
    this.displayNameAlt = displayNameAlt;
}

public String getSortKeyAlt() {
    return sortKeyAlt;
}

public void setSortKeyAlt(String sortKeyAlt) {
    this.sortKeyAlt = sortKeyAlt;
}

public String getStarred() {
    return starred;
}

public void setStarred(String starred) {
    this.starred = starred;
}

public boolean isHasPhoneNumber() {
    return hasPhoneNumber;
}

public void setHasPhoneNumber(boolean hasPhoneNumber) {
    this.hasPhoneNumber = hasPhoneNumber;
}

public String getRawContactId() {
    return rawContactId;
}

public void setRawContactId(String rawContactId) {
    this.rawContactId = rawContactId;
}

public String getContactAccountType() {
    return contactAccountType;
}

public void setContactAccountType(String contactAccountType) {
    this.contactAccountType = contactAccountType;
}

public String getCarrierPresence() {
    return carrierPresence;
}

public void setCarrierPresence(String carrierPresence) {
    this.carrierPresence = carrierPresence;
}

public long getContactLastPpdatedTimestamp() {
    return contactLastPpdatedTimestamp;
}

public void setContactLastPpdatedTimestamp(long contactLastPpdatedTimestamp) {
    this.contactLastPpdatedTimestamp = contactLastPpdatedTimestamp;
}

public int getPhonebookBucket() {
    return phonebookBucket;
}

public void setPhonebookBucket(int phonebookBucket) {
    this.phonebookBucket = phonebookBucket;
}

public String getDisplayName() {
    return displayName;
}

public void setDisplayName(String displayName) {
    this.displayName = displayName;
}

public String getSortKey() {
    return sortKey;
}

public void setSortKey(String sortKey) {
    this.sortKey = sortKey;
}

public String getVersion() {
    return version;
}

public void setVersion(String version) {
    this.version = version;
}

public boolean isInDefaultdirectory() {
    return inDefaultdirectory;
}

public void setInDefaultdirectory(boolean inDefaultdirectory) {
    this.inDefaultdirectory = inDefaultdirectory;
}

public int getTimesContacted() {
    return timesContacted;
}

public void setTimesContacted(int timesContacted) {
    this.timesContacted = timesContacted;
}

public String getId() {
    return id;
}

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

public String getAccountTypeAndDataSet() {
    return accountTypeAndDataSet;
}

public void setAccountTypeAndDataSet(String accountTypeAndDataSet) {
    this.accountTypeAndDataSet = accountTypeAndDataSet;
}

public String getNameRawContactId() {
    return nameRawContactId;
}

public void setNameRawContactId(String nameRawContactId) {
    this.nameRawContactId = nameRawContactId;
}

public String getPhonebookBucketAlt() {
    return phonebookBucketAlt;
}

public void setPhonebookBucketAlt(String phonebookBucketAlt) {
    this.phonebookBucketAlt = phonebookBucketAlt;
}

public String getLastTimeContacted() {
    return lastTimeContacted;
}

public void setLastTimeContacted(String lastTimeContacted) {
    this.lastTimeContacted = lastTimeContacted;
}

public String getPinned() {
    return pinned;
}

public void setPinned(String pinned) {
    this.pinned = pinned;
}

public boolean isIsPrimary() {
    return isPrimary;
}

public void setIsPrimary(boolean isPrimary) {
    this.isPrimary = isPrimary;
}

public String getContactId() {
    return contactId;
}

public void setContactId(String contactId) {
    this.contactId = contactId;
}

public boolean isInVisibleGroup() {
    return inVisibleGroup;
}

public void setInVisibleGroup(boolean inVisibleGroup) {
    this.inVisibleGroup = inVisibleGroup;
}

public String getPhonebookLabel() {
    return phonebookLabel;
}

public void setPhonebookLabel(String phonebookLabel) {
    this.phonebookLabel = phonebookLabel;
}

public String getAccountName() {
    return accountName;
}

public void setAccountName(String accountName) {
    this.accountName = accountName;
}

public String getDisplayNameSource() {
    return displayNameSource;
}

public void setDisplayNameSource(String displayNameSource) {
    this.displayNameSource = displayNameSource;
}

public String getDirty() {
    return dirty;
}

public void setDirty(String dirty) {
    this.dirty = dirty;
}

public String getSourceid() {
    return sourceid;
}

public void setSourceid(String sourceid) {
    this.sourceid = sourceid;
}

public String getPhoneticNameStyle() {
    return phoneticNameStyle;
}

public void setPhoneticNameStyle(String phoneticNameStyle) {
    this.phoneticNameStyle = phoneticNameStyle;
}

public String getSendToVoicemail() {
    return sendToVoicemail;
}

public void setSendToVoicemail(String sendToVoicemail) {
    this.sendToVoicemail = sendToVoicemail;
}

public String getLookup() {
    return lookup;
}

public void setLookup(String lookup) {
    this.lookup = lookup;
}

public String getPhonebookLabelAlt() {
    return phonebookLabelAlt;
}

public void setPhonebookLabelAlt(String phonebookLabelAlt) {
    this.phonebookLabelAlt = phonebookLabelAlt;
}

public boolean isIsSuperPrimary() {
    return isSuperPrimary;
}

public void setIsSuperPrimary(boolean isSuperPrimary) {
    this.isSuperPrimary = isSuperPrimary;
}

public String getData4() {
    return data4;
}

public void setData4(String data4) {
    this.data4 = data4;
}

public String getData2() {
    return data2;
}

public void setData2(String data2) {
    this.data2 = data2;
}

public String getData1() {
    return data1;
}

public void setData1(String data1) {
    this.data1 = data1;
}

public String getRawContactIsUserProfile() {
    return rawContactIsUserProfile;
}

public void setRawContactIsUserProfile(String rawContactIsUserProfile) {
    this.rawContactIsUserProfile = rawContactIsUserProfile;
}

public String getMimetype() {
    return mimetype;
}

public void setMimetype(String mimetype) {
    this.mimetype = mimetype;
}
}

你可能感兴趣的:(Android使用ContentResolver获取系统相册图片、音乐文件、通讯录联系人)