如果開發(fā)一個(gè)自定義相冊(cè)功能. 一般而言,頂部會(huì)有3個(gè)tab,分別是"全部", "照片"和"視頻", 但是如果產(chǎn)品在文檔上隨手加上了一個(gè)"喜歡"列,就會(huì)非常的麻煩. 因?yàn)楦緵]法從媒體庫中獲取到類似這樣的一個(gè)字段.
解決思路
獲取媒體庫數(shù)據(jù), 肯定是用ContentResolver
來操作的. 這個(gè)步驟就不提.
在debug查看了Cursor
返回的所有數(shù)據(jù)列以后, 發(fā)現(xiàn)了一個(gè)字段tag
, 他雖然不是我們要的favorite
(喜歡)功能,但是可以用上.
就是將這個(gè)tag
的值寫上我們自定義的一個(gè)值, 比如favorite
, 然后下次查詢的時(shí)候, 直接查詢這個(gè)tag
的值, 如果它的值為null
就表示沒有被用戶點(diǎn)擊"喜歡", 如果等于我們自定義的字段favorite
, 則表示被標(biāo)記了喜歡.
實(shí)現(xiàn)
我們先定義一個(gè)字段,用來標(biāo)記喜歡
public static final String TAG_FAVORITE = "favorite";
再假設(shè)有一個(gè)Model類代表我們的相冊(cè)類, 定義為Album
, 然后結(jié)構(gòu)如下
public class Album {
public int id;
public boolean favorite;
public long addDate;
public String path;
public int width;
public int height;
public String mime;
public long duration;
public String displayName;
public int orientation;
public boolean isVideo;
public boolean isChecked;
// .... 省略其他的equals, 序列化之類的代碼
}
接著就可以實(shí)現(xiàn)標(biāo)記為相冊(cè)為喜歡和不喜歡的方法了. 為了支持批量操作. 所以使用了applyBatch
方法.
/**
* 標(biāo)記資源為[喜歡]或者移除此標(biāo)記
*
* @param albums 被操作的數(shù)據(jù)
* @param favorite true標(biāo)記為喜歡, false清除標(biāo)記
*/
public void markAlbumsFavorite(List<Album> albums, boolean favorite) {
final Uri queryUri = MediaStore.Files.getContentUri("external");
ContentResolver resolver = ContextProvider.get().getContext().getContentResolver();
String selection = MediaStore.Files.FileColumns._ID + " = ?";
ArrayList<ContentProviderOperation> operations =
albums.stream()
.map(album ->
ContentProviderOperation.newUpdate(queryUri)
.withSelection(
selection,
new String[] {String.valueOf(album.id)})
.withValue(
MediaStore.Video.VideoColumns.TAGS,
favorite ? TAG_FAVORITE : null)
.build())
.collect(Collectors.toCollection(ArrayList::new));
try {
resolver.applyBatch(queryUri.getAuthority(), operations);
} catch (Exception e) {
e.printStackTrace();
}
}
里面使用了Java8
的流式操作Stream
, 如果看不懂, 我覺得可以學(xué)習(xí)一波這個(gè)東西. 學(xué)完了以后, 根本不想再用for
循環(huán)了...
然后就是查詢的部分了.
在查詢數(shù)據(jù)的代碼中, 加上如下這么一段:
// ... 省略了查詢的字段設(shè)置等...
Cursor cursor =
context.getContentResolver()
.query(queryUri, projection, selection, selectionArgs, sortOrder + limit);
if (cursor == null) {
return new LinkedHashMap<>();
}
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
Album album = new Album();
album.id = cursor.getInt(cursor.getColumnIndex(MediaStore.Files.FileColumns._ID));
String favorite = null;
try {
// 個(gè)別手機(jī)在第一次設(shè)置tags之前獲取的話會(huì)出錯(cuò)
favorite =
cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.TAGS));
} catch (Exception ignored) {
}
album.favorite = TextUtils.equals(TAG_FAVORITE, favorite);
// ... 省略后續(xù)的字段設(shè)置 ...
}
大概就是這樣.