• Android源码之Gallery专题研究(1)


    前言

    时光飞逝,从事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数据,具体代码如下所示:

    [java] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. package com.android.gallery3d.data;  
    2.   
    3. import android.annotation.TargetApi;  
    4. import android.content.ContentResolver;  
    5. import android.database.Cursor;  
    6. import android.net.Uri;  
    7. import android.provider.MediaStore.Files;  
    8. import android.provider.MediaStore.Files.FileColumns;  
    9. import android.provider.MediaStore.Images;  
    10. import android.provider.MediaStore.Images.ImageColumns;  
    11. import android.provider.MediaStore.Video;  
    12. import android.util.Log;  
    13.   
    14. import com.android.gallery3d.common.ApiHelper;  
    15. import com.android.gallery3d.common.Utils;  
    16. import com.android.gallery3d.util.ThreadPool.JobContext;  
    17.   
    18. import java.util.ArrayList;  
    19. import java.util.Arrays;  
    20. import java.util.Comparator;  
    21. import java.util.HashMap;  
    22.   
    23. class BucketHelper {  
    24.   
    25.     private static final String TAG = "BucketHelper";  
    26.     private static final String EXTERNAL_MEDIA = "external";  
    27.   
    28.     // BUCKET_DISPLAY_NAME is a string like "Camera" which is the directory  
    29.     // name of where an image or video is in. BUCKET_ID is a hash of the path  
    30.     // name of that directory (see computeBucketValues() in MediaProvider for  
    31.     // details). MEDIA_TYPE is video, image, audio, etc.  
    32.     // BUCKET_DISPLAY_NAME字段为文件目录名称 BUCKET_ID字段为目录路径(path)的HASH值  
    33.     // The "albums" are not explicitly recorded in the database, but each image  
    34.     // or video has the two columns (BUCKET_ID, MEDIA_TYPE). We define an  
    35.     // "album" to be the collection of images/videos which have the same value  
    36.     // for the two columns.  
    37.     // "专辑"的划分方式为:当文件具有相同的目录(BUCKET_ID)和多媒体类型(MEDIA_TYPE)即属于同一专辑  
    38.     // The goal of the query (used in loadSubMediaSetsFromFilesTable()) is to  
    39.     // find all albums, that is, all unique values for (BUCKET_ID, MEDIA_TYPE).  
    40.     // In the meantime sort them by the timestamp of the latest image/video in  
    41.     // each of the album.  
    42.     //  
    43.     // The order of columns below is important: it must match to the index in  
    44.     // MediaStore.  
    45.     private static final String[] PROJECTION_BUCKET = {  
    46.             ImageColumns.BUCKET_ID,  
    47.             FileColumns.MEDIA_TYPE,  
    48.             ImageColumns.BUCKET_DISPLAY_NAME};  
    49.   
    50.     // The indices should match the above projections.  
    51.     private static final int INDEX_BUCKET_ID = 0;  
    52.     private static final int INDEX_MEDIA_TYPE = 1;  
    53.     private static final int INDEX_BUCKET_NAME = 2;  
    54.   
    55.     // We want to order the albums by reverse chronological order. We abuse the  
    56.     // "WHERE" parameter to insert a "GROUP BY" clause into the SQL statement.  
    57.     // The template for "WHERE" parameter is like:  
    58.     //    SELECT ... FROM ... WHERE (%s)  
    59.     // and we make it look like:  
    60.     //    SELECT ... FROM ... WHERE (1) GROUP BY 1,(2)  
    61.     // The "(1)" means true. The "1,(2)" means the first two columns specified  
    62.     // after SELECT. Note that because there is a ")" in the template, we use  
    63.     // "(2" to match it.  
    64.     private static final String BUCKET_GROUP_BY = "1) GROUP BY 1,(2";  
    65.   
    66.     private static final String BUCKET_ORDER_BY = "MAX(datetaken) DESC";  
    67.   
    68.     // Before HoneyComb there is no Files table. Thus, we need to query the  
    69.     // bucket info from the Images and Video tables and then merge them  
    70.     // together.  
    71.     //  
    72.     // A bucket can exist in both tables. In this case, we need to find the  
    73.     // latest timestamp from the two tables and sort ourselves. So we add the  
    74.     // MAX(date_taken) to the projection and remove the media_type since we  
    75.     // already know the media type from the table we query from.  
    76.     private static final String[] PROJECTION_BUCKET_IN_ONE_TABLE = {  
    77.             ImageColumns.BUCKET_ID,  
    78.             "MAX(datetaken)",  
    79.             ImageColumns.BUCKET_DISPLAY_NAME};  
    80.   
    81.     // We keep the INDEX_BUCKET_ID and INDEX_BUCKET_NAME the same as  
    82.     // PROJECTION_BUCKET so we can reuse the values defined before.  
    83.     private static final int INDEX_DATE_TAKEN = 1;  
    84.   
    85.     // When query from the Images or Video tables, we only need to group by BUCKET_ID.  
    86.     private static final String BUCKET_GROUP_BY_IN_ONE_TABLE = "1) GROUP BY (1";  
    87.   
    88.     public static BucketEntry[] loadBucketEntries(  
    89.             JobContext jc, ContentResolver resolver, int type) {  
    90.         if (ApiHelper.HAS_MEDIA_PROVIDER_FILES_TABLE) {//当API1>= 11(即Android3.0版本之后)  
    91.             return loadBucketEntriesFromFilesTable(jc, resolver, type);//获取MediaScanner数据库中多媒体文件(图片和视频)的目录路径和目录名称  
    92.         } else {//Android3.0之前版本  
    93.             return loadBucketEntriesFromImagesAndVideoTable(jc, resolver, type);  
    94.         }  
    95.     }  
    96.   
    97.     private static void updateBucketEntriesFromTable(JobContext jc,  
    98.             ContentResolver resolver, Uri tableUri, HashMap<Integer, BucketEntry> buckets) {  
    99.         Cursor cursor = resolver.query(tableUri, PROJECTION_BUCKET_IN_ONE_TABLE,  
    100.                 BUCKET_GROUP_BY_IN_ONE_TABLE, null, null);  
    101.         if (cursor == null) {  
    102.             Log.w(TAG, "cannot open media database: " + tableUri);  
    103.             return;  
    104.         }  
    105.         try {  
    106.             while (cursor.moveToNext()) {  
    107.                 int bucketId = cursor.getInt(INDEX_BUCKET_ID);  
    108.                 int dateTaken = cursor.getInt(INDEX_DATE_TAKEN);  
    109.                 BucketEntry entry = buckets.get(bucketId);  
    110.                 if (entry == null) {  
    111.                     entry = new BucketEntry(bucketId, cursor.getString(INDEX_BUCKET_NAME));  
    112.                     buckets.put(bucketId, entry);  
    113.                     entry.dateTaken = dateTaken;  
    114.                 } else {  
    115.                     entry.dateTaken = Math.max(entry.dateTaken, dateTaken);  
    116.                 }  
    117.             }  
    118.         } finally {  
    119.             Utils.closeSilently(cursor);  
    120.         }  
    121.     }  
    122.   
    123.     private static BucketEntry[] loadBucketEntriesFromImagesAndVideoTable(  
    124.             JobContext jc, ContentResolver resolver, int type) {  
    125.         HashMap<Integer, BucketEntry> buckets = new HashMap<Integer, BucketEntry>(64);  
    126.         if ((type & MediaObject.MEDIA_TYPE_IMAGE) != 0) {  
    127.             updateBucketEntriesFromTable(  
    128.                     jc, resolver, Images.Media.EXTERNAL_CONTENT_URI, buckets);  
    129.         }  
    130.         if ((type & MediaObject.MEDIA_TYPE_VIDEO) != 0) {  
    131.             updateBucketEntriesFromTable(  
    132.                     jc, resolver, Video.Media.EXTERNAL_CONTENT_URI, buckets);  
    133.         }  
    134.         BucketEntry[] entries = buckets.values().toArray(new BucketEntry[buckets.size()]);  
    135.         Arrays.sort(entries, new Comparator<BucketEntry>() {  
    136.             @Override  
    137.             public int compare(BucketEntry a, BucketEntry b) {  
    138.                 // sorted by dateTaken in descending order  
    139.                 return b.dateTaken - a.dateTaken;  
    140.             }  
    141.         });  
    142.         return entries;  
    143.     }  
    144.   
    145.     private static BucketEntry[] loadBucketEntriesFromFilesTable(  
    146.             JobContext jc, ContentResolver resolver, int type) {  
    147.         Uri uri = getFilesContentUri();  
    148.   
    149.         Cursor cursor = resolver.query(uri,  
    150.                 PROJECTION_BUCKET, BUCKET_GROUP_BY,  
    151.                 null, BUCKET_ORDER_BY);  
    152.         if (cursor == null) {  
    153.             Log.w(TAG, "cannot open local database: " + uri);  
    154.             return new BucketEntry[0];  
    155.         }  
    156.         ArrayList<BucketEntry> buffer = new ArrayList<BucketEntry>();  
    157.         int typeBits = 0;  
    158.         if ((type & MediaObject.MEDIA_TYPE_IMAGE) != 0) {  
    159.             typeBits |= (1 << FileColumns.MEDIA_TYPE_IMAGE);  
    160.         }  
    161.         if ((type & MediaObject.MEDIA_TYPE_VIDEO) != 0) {  
    162.             typeBits |= (1 << FileColumns.MEDIA_TYPE_VIDEO);  
    163.         }  
    164.         try {  
    165.             while (cursor.moveToNext()) {  
    166.                 if ((typeBits & (1 << cursor.getInt(INDEX_MEDIA_TYPE))) != 0) {  
    167.                     BucketEntry entry = new BucketEntry(  
    168.                             cursor.getInt(INDEX_BUCKET_ID),  
    169.                             cursor.getString(INDEX_BUCKET_NAME));//构造元数据BucketEntry  
    170.   
    171.                     if (!buffer.contains(entry)) {  
    172.                         buffer.add(entry);//添加数据信息  
    173.                     }  
    174.                 }  
    175.                 if (jc.isCancelled()) return null;  
    176.             }  
    177.         } finally {  
    178.             Utils.closeSilently(cursor);  
    179.         }  
    180.         return buffer.toArray(new BucketEntry[buffer.size()]);  
    181.     }  
    182.   
    183.     private static String getBucketNameInTable(  
    184.             ContentResolver resolver, Uri tableUri, int bucketId) {  
    185.         String selectionArgs[] = new String[] {String.valueOf(bucketId)};  
    186.         Uri uri = tableUri.buildUpon()  
    187.                 .appendQueryParameter("limit", "1")  
    188.                 .build();  
    189.         Cursor cursor = resolver.query(uri, PROJECTION_BUCKET_IN_ONE_TABLE,  
    190.                 "bucket_id = ?", selectionArgs, null);  
    191.         try {  
    192.             if (cursor != null && cursor.moveToNext()) {  
    193.                 return cursor.getString(INDEX_BUCKET_NAME);  
    194.             }  
    195.         } finally {  
    196.             Utils.closeSilently(cursor);  
    197.         }  
    198.         return null;  
    199.     }  
    200.   
    201.     @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)  
    202.     private static Uri getFilesContentUri() {  
    203.         return Files.getContentUri(EXTERNAL_MEDIA);  
    204.     }  
    205.   
    206.     public static String getBucketName(ContentResolver resolver, int bucketId) {  
    207.         if (ApiHelper.HAS_MEDIA_PROVIDER_FILES_TABLE) {  
    208.             String result = getBucketNameInTable(resolver, getFilesContentUri(), bucketId);  
    209.             return result == null ? "" : result;  
    210.         } else {  
    211.             String result = getBucketNameInTable(  
    212.                     resolver, Images.Media.EXTERNAL_CONTENT_URI, bucketId);  
    213.             if (result != null) return result;  
    214.             result = getBucketNameInTable(  
    215.                     resolver, Video.Media.EXTERNAL_CONTENT_URI, bucketId);  
    216.             return result == null ? "" : result;  
    217.         }  
    218.     }  
    219.   
    220.     public static class BucketEntry {  
    221.         public String bucketName;  
    222.         public int bucketId;  
    223.         public int dateTaken;  
    224.   
    225.         public BucketEntry(int id, String name) {  
    226.             bucketId = id;  
    227.             bucketName = Utils.ensureNotNull(name);  
    228.         }  
    229.   
    230.         @Override  
    231.         public int hashCode() {  
    232.             return bucketId;  
    233.         }  
    234.   
    235.         @Override  
    236.         public boolean equals(Object object) {  
    237.             if (!(object instanceof BucketEntry)) return false;  
    238.             BucketEntry entry = (BucketEntry) object;  
    239.             return bucketId == entry.bucketId;  
    240.         }  
    241.     }  
    242. }  

    接下来我们再来看看BucketHelper类的调用关系的时序图,具体如1-2所示:

        

     图1-2

    到目前为止我们大致了解了Gallery数据加载的一个大体流程,接下来的文章将分析Album数据的读取以及数据封装。

  • 相关阅读:
    GridView中实现可收缩的面板
    android之xml数据解析(Pull)
    android之xml数据解析(DOM)
    android intent 传递list或者对象
    Android之单元测试
    Directx11教程(48) depth/stencil buffer的作用
    Directx11教程(47) alpha blend(4)雾的实现
    Directx11教程41 纹理映射(11)
    Directx11教程40 纹理映射(10)
    Directx11教程(46) alpha blend(3)
  • 原文地址:https://www.cnblogs.com/senior-engineer/p/4853687.html
Copyright © 2020-2023  润新知