平時(shí)選擇圖片框架用得多了,自然對背后的實(shí)現(xiàn)原理感興趣衙解。
那么鸥跟,最基本的應(yīng)該時(shí)遍歷圖庫的文件了吧,在不用任何第三方庫的前提下枫匾,怎么實(shí)現(xiàn)干茉?用到哪些類?具體怎么寫很泊?
1. ContentResolver
2. Cursor
其實(shí)就是跨應(yīng)用共享數(shù)據(jù)角虫,這里只需要用到這兩個(gè)類就可以遍歷圖庫文件了戳鹅,在此之前順便復(fù)習(xí)一下四大組件之一的內(nèi)容提供者
ContentProvider簡介
- ContentProvider內(nèi)容提供者(四大組件之一)主要用于在不同的應(yīng)用程序之間實(shí)現(xiàn)數(shù)據(jù)共享的功能。
平時(shí)只知其一不知其二枫虏,實(shí)際上內(nèi)容提供者除了提供內(nèi)容的provider以外還有一個(gè)解釋內(nèi)容的resolver,當(dāng)別的應(yīng)用想對某 ContentProvider 增刪改查的操作時(shí)腾它,可以通過 ContentResolver 類來完成瞒滴。
掃描文件
我們的目標(biāo)就是拿到以上的數(shù)據(jù),至于之后怎么顯示在控件上怎么操作就隨自由發(fā)揮了赞警。ok, talk is cheap, show me the code
public void scanImages(){
String[] IMAGES = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.SIZE};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,IMAGES,null,null,null);
if(cursor != null){
while(cursor.moveToNext()){
String path = cursor.getString(0);
String bucketName = cursor.getString(1);
String mimeType = cursor.getString(2);
long size = cursor.getLong(3);
Log.i("-->file",path+","+bucketName+","+mimeType+","+size);
}
cursor.close();
}
}
如果你在跑這段代碼拋了異常妓忍,而且是permissions異常,那么要學(xué)會自己處理了仅颇。這里通過上下文就可以獲得 ContentResolver 對象了单默,緊接著是執(zhí)行了 query 方法,方法里面有5個(gè)參數(shù)忘瓦。分別是
query(
Uri: using the content:// scheme, for the content to retrieve.
projection: A list of which columns to return. Passing null will return all columns, which is inefficient.
selection: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.
selectionArgs: You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.
sortOrder: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
)
這里Uri是必須傳搁廓,因?yàn)椴樵兊酶嬖V在哪里查起嘛,接下來得幾個(gè)參數(shù)就是根據(jù)什么條件來查耕皮,一般看情況自己選擇境蜕,我在這里自定義了一個(gè) IMAGES 傳給了第二個(gè)參數(shù),意思就是只返回這四個(gè)屬性回來就好了.