前言
時光飛逝,從事Android系統開發已經兩年了,總想寫點什麼來安慰自己。思考了很久總是無法下筆,覺得沒什麼好寫的。現在終於決定寫一些符合大多數人需求的東西,想必使用過Android手機的人們一定對“圖庫”(以下簡稱Gallery)這個應用非常熟悉。在Android市場裡面有各種關於圖庫的應用,他們的最初原型其實就是Android系統原生“圖庫”,只是做了不同的差異化而已(UI差異化)。在研究Gallery源碼之前,我們需要對設計模式有一定的瞭解,根據自己對Gallery的瞭解,Gallery的設計就好比是一座設計精良的並且高效運轉的機器(32個攢)。毫不誇張地說,在Android市場裡,沒有一款“圖庫”應用的設計設計能夠和Gallery媲美。接下來的一段時間,就讓我們共同來揭開Gallery的神秘面紗。
資料載入
在研究Gallery之前,我們還是來欣賞一下Gallery的整體效果,具體見圖1-1所示:
圖1-1
首先我們先來看一下Gallery的發展曆史,在Android2.3之前Android系統的“圖庫”名為Gallery3D,在Android2.3之後系統將之前的Gallery3D更改為Gallery2,一直沿用到目前最新版本(4.4),Gallery2在UI和功能上面做了質的飛躍,是目前Android源碼中非常優秀的模組,對於Android應用開發人員來說是非常好的開源項目,其中的設計新思想和設計模式都值得我們借鑒。
現在回到我們研究的主題-資料載入,我們先來看一下Gallery2在源碼中的路徑(package/app/Gallery2/),在該路徑下包含了“圖庫”使用的資源和源碼。我們在設計一款軟體的時候首先考慮的是資料的儲存和訪問,因此我們也按照這樣的設計思路來探究Gallery2的資料載入過程。說到這兒稍微提一下我分析源碼的方式,可能大家對Android源碼稍微有一點瞭解的同學應該知道,Android源碼是非常龐大的,因此選擇剖析器的切入點大致可以分為兩類:第一種是按照操程式操作步驟分析源碼——適用於介面跳轉清晰的程式;第二種是根據列印的Log資訊剖析器的運行邏輯——適用於複雜的操作邏輯。
首先我們先來看一下BucketHelper.java類(/src/com/android/gallery3d/data/BucketHelper.java),該類主要是負責讀取MediaProvider資料庫中Image和Video資料,具體代碼如下所示:
package com.android.gallery3d.data;import android.annotation.TargetApi;import android.content.ContentResolver;import android.database.Cursor;import android.net.Uri;import android.provider.MediaStore.Files;import android.provider.MediaStore.Files.FileColumns;import android.provider.MediaStore.Images;import android.provider.MediaStore.Images.ImageColumns;import android.provider.MediaStore.Video;import android.util.Log;import com.android.gallery3d.common.ApiHelper;import com.android.gallery3d.common.Utils;import com.android.gallery3d.util.ThreadPool.JobContext;import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.HashMap;class BucketHelper { private static final String TAG = "BucketHelper"; private static final String EXTERNAL_MEDIA = "external"; // BUCKET_DISPLAY_NAME is a string like "Camera" which is the directory // name of where an image or video is in. BUCKET_ID is a hash of the path // name of that directory (see computeBucketValues() in MediaProvider for // details). MEDIA_TYPE is video, image, audio, etc. // BUCKET_DISPLAY_NAME欄位為檔案目錄名稱 BUCKET_ID欄位為目錄路徑(path)的HASH值 // The "albums" are not explicitly recorded in the database, but each image // or video has the two columns (BUCKET_ID, MEDIA_TYPE). We define an // "album" to be the collection of images/videos which have the same value // for the two columns. // "專輯"的劃分方式為:當檔案具有相同的目錄(BUCKET_ID)和多媒體類型(MEDIA_TYPE)即屬於同一專輯 // The goal of the query (used in loadSubMediaSetsFromFilesTable()) is to // find all albums, that is, all unique values for (BUCKET_ID, MEDIA_TYPE). // In the meantime sort them by the timestamp of the latest image/video in // each of the album. // // The order of columns below is important: it must match to the index in // MediaStore. private static final String[] PROJECTION_BUCKET = { ImageColumns.BUCKET_ID, FileColumns.MEDIA_TYPE, ImageColumns.BUCKET_DISPLAY_NAME}; // The indices should match the above projections. private static final int INDEX_BUCKET_ID = 0; private static final int INDEX_MEDIA_TYPE = 1; private static final int INDEX_BUCKET_NAME = 2; // We want to order the albums by reverse chronological order. We abuse the // "WHERE" parameter to insert a "GROUP BY" clause into the SQL statement. // The template for "WHERE" parameter is like: // SELECT ... FROM ... WHERE (%s) // and we make it look like: // SELECT ... FROM ... WHERE (1) GROUP BY 1,(2) // The "(1)" means true. The "1,(2)" means the first two columns specified // after SELECT. Note that because there is a ")" in the template, we use // "(2" to match it. private static final String BUCKET_GROUP_BY = "1) GROUP BY 1,(2"; private static final String BUCKET_ORDER_BY = "MAX(datetaken) DESC"; // Before HoneyComb there is no Files table. Thus, we need to query the // bucket info from the Images and Video tables and then merge them // together. // // A bucket can exist in both tables. In this case, we need to find the // latest timestamp from the two tables and sort ourselves. So we add the // MAX(date_taken) to the projection and remove the media_type since we // already know the media type from the table we query from. private static final String[] PROJECTION_BUCKET_IN_ONE_TABLE = { ImageColumns.BUCKET_ID, "MAX(datetaken)", ImageColumns.BUCKET_DISPLAY_NAME}; // We keep the INDEX_BUCKET_ID and INDEX_BUCKET_NAME the same as // PROJECTION_BUCKET so we can reuse the values defined before. private static final int INDEX_DATE_TAKEN = 1; // When query from the Images or Video tables, we only need to group by BUCKET_ID. private static final String BUCKET_GROUP_BY_IN_ONE_TABLE = "1) GROUP BY (1"; public static BucketEntry[] loadBucketEntries( JobContext jc, ContentResolver resolver, int type) { if (ApiHelper.HAS_MEDIA_PROVIDER_FILES_TABLE) {//當API1>= 11(即Android3.0版本之後) return loadBucketEntriesFromFilesTable(jc, resolver, type);//擷取MediaScanner資料庫中多媒體檔案(圖片和視頻)的目錄路徑和目錄名稱 } else {//Android3.0之前版本 return loadBucketEntriesFromImagesAndVideoTable(jc, resolver, type); } } private static void updateBucketEntriesFromTable(JobContext jc, ContentResolver resolver, Uri tableUri, HashMap buckets) { Cursor cursor = resolver.query(tableUri, PROJECTION_BUCKET_IN_ONE_TABLE, BUCKET_GROUP_BY_IN_ONE_TABLE, null, null); if (cursor == null) { Log.w(TAG, "cannot open media database: " + tableUri); return; } try { while (cursor.moveToNext()) { int bucketId = cursor.getInt(INDEX_BUCKET_ID); int dateTaken = cursor.getInt(INDEX_DATE_TAKEN); BucketEntry entry = buckets.get(bucketId); if (entry == null) { entry = new BucketEntry(bucketId, cursor.getString(INDEX_BUCKET_NAME)); buckets.put(bucketId, entry); entry.dateTaken = dateTaken; } else { entry.dateTaken = Math.max(entry.dateTaken, dateTaken); } } } finally { Utils.closeSilently(cursor); } } private static BucketEntry[] loadBucketEntriesFromImagesAndVideoTable( JobContext jc, ContentResolver resolver, int type) { HashMap buckets = new HashMap(64); if ((type & MediaObject.MEDIA_TYPE_IMAGE) != 0) { updateBucketEntriesFromTable( jc, resolver, Images.Media.EXTERNAL_CONTENT_URI, buckets); } if ((type & MediaObject.MEDIA_TYPE_VIDEO) != 0) { updateBucketEntriesFromTable( jc, resolver, Video.Media.EXTERNAL_CONTENT_URI, buckets); } BucketEntry[] entries = buckets.values().toArray(new BucketEntry[buckets.size()]); Arrays.sort(entries, new Comparator() { @Override public int compare(BucketEntry a, BucketEntry b) { // sorted by dateTaken in descending order return b.dateTaken - a.dateTaken; } }); return entries; } private static BucketEntry[] loadBucketEntriesFromFilesTable( JobContext jc, ContentResolver resolver, int type) { Uri uri = getFilesContentUri(); Cursor cursor = resolver.query(uri, PROJECTION_BUCKET, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY); if (cursor == null) { Log.w(TAG, "cannot open local database: " + uri); return new BucketEntry[0]; } ArrayList buffer = new ArrayList(); int typeBits = 0; if ((type & MediaObject.MEDIA_TYPE_IMAGE) != 0) { typeBits |= (1 << FileColumns.MEDIA_TYPE_IMAGE); } if ((type & MediaObject.MEDIA_TYPE_VIDEO) != 0) { typeBits |= (1 << FileColumns.MEDIA_TYPE_VIDEO); } try { while (cursor.moveToNext()) { if ((typeBits & (1 << cursor.getInt(INDEX_MEDIA_TYPE))) != 0) { BucketEntry entry = new BucketEntry( cursor.getInt(INDEX_BUCKET_ID), cursor.getString(INDEX_BUCKET_NAME));//構造中繼資料BucketEntry if (!buffer.contains(entry)) { buffer.add(entry);//添加資料資訊 } } if (jc.isCancelled()) return null; } } finally { Utils.closeSilently(cursor); } return buffer.toArray(new BucketEntry[buffer.size()]); } private static String getBucketNameInTable( ContentResolver resolver, Uri tableUri, int bucketId) { String selectionArgs[] = new String[] {String.valueOf(bucketId)}; Uri uri = tableUri.buildUpon() .appendQueryParameter("limit", "1") .build(); Cursor cursor = resolver.query(uri, PROJECTION_BUCKET_IN_ONE_TABLE, "bucket_id = ?", selectionArgs, null); try { if (cursor != null && cursor.moveToNext()) { return cursor.getString(INDEX_BUCKET_NAME); } } finally { Utils.closeSilently(cursor); } return null; } @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) private static Uri getFilesContentUri() { return Files.getContentUri(EXTERNAL_MEDIA); } public static String getBucketName(ContentResolver resolver, int bucketId) { if (ApiHelper.HAS_MEDIA_PROVIDER_FILES_TABLE) { String result = getBucketNameInTable(resolver, getFilesContentUri(), bucketId); return result == null ? "" : result; } else { String result = getBucketNameInTable( resolver, Images.Media.EXTERNAL_CONTENT_URI, bucketId); if (result != null) return result; result = getBucketNameInTable( resolver, Video.Media.EXTERNAL_CONTENT_URI, bucketId); return result == null ? "" : result; } } public static class BucketEntry { public String bucketName; public int bucketId; public int dateTaken; public BucketEntry(int id, String name) { bucketId = id; bucketName = Utils.ensureNotNull(name); } @Override public int hashCode() { return bucketId; } @Override public boolean equals(Object object) { if (!(object instanceof BucketEntry)) return false; BucketEntry entry = (BucketEntry) object; return bucketId == entry.bucketId; } }}
接下來我們再來看看BucketHelper類的調用關係的時序圖,具體如1-2所示:
圖1-2
到目前為止我們大致瞭解了Gallery資料載入的一個大體流程,接下來的文章將分析Album資料的讀取以及資料封裝。