前言

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

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

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

 图1-2

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

Android源码之Gallery专题研究(1)的更多相关文章

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

    引言 上一篇文章已经讲解了数据加载过程,接下来我们来看一看数据加载后的处理过程.按照正常的思维逻辑,当数据加载之后,接下来就应该考虑数据的显示逻辑. MVC显示逻辑 大家可能对J2EE的MVC架构比较 ...

  2. Android底层有一定的认识,研究过相关的Android源码

    一.系统架构: 一).系统分层:(由下向上)[如图] 1.安卓系统分为四层,分别是Linux内核层.Libraries层.FrameWork层,以及Applications层: 其中Linux内核层包 ...

  3. android源码地址及下载介绍

      git clone https://android.googlesource.com/device/common.git  git clone https://android.googlesour ...

  4. Eclipse与Android源码中ProGuard工具的使用

    由于工作需要,这两天和同事在研究android下面的ProGuard工具的使用,通过查看android官网对该工具的介绍以及网络上其它相关资料,再加上自己的亲手实践,算是有了一个基本了解.下面将自己的 ...

  5. android源码的目录结构

    android源码的目录结构 [以下网络摘抄] |-- Makefile ! l/ a5 n% S% @- `0 d# z# a$ P4 V3 o7 R|-- bionic              ...

  6. Android源码-学习随笔

    在线代码网站1:http://grepcode.com/project/repository.grepcode.com/java/ext/com.google.android/android/ 书籍: ...

  7. Android拓展系列(11)--打造Windows下便携的Android源码阅读环境

    因为EXT和NTFS格式的差异,我一直对于windows下阅读Android源码感到不满. 前几天,想把最新的android5.0的源码下下来研究一下,而平时日常使用的又是windows环境,于是专门 ...

  8. [安卓]windows下如何安装Android源码

    本文改写于:http://www.cnblogs.com/skyme/archive/2011/05/14/2046040.html 1.下载并安装git: 在git-scm.com上下载并安装git ...

  9. Android源码分析-全面理解Context

    前言 Context在android中的作用不言而喻,当我们访问当前应用的资源,启动一个新的activity的时候都需要提供Context,而这个Context到底是什么呢,这个问题好像很好回答又好像 ...

随机推荐

  1. 如何创建自定义ASP.NET MVC5脚手架模板?

    I'm using ASP.NET MVC5 and VS2013 I've tried to copy CodeTemplates folder from C:\Program Files (x86 ...

  2. 循环ip段 转载 出处不明

    public struct IP         {             public byte A;             public byte B;             public  ...

  3. windows的DOS窗口如何修改大小

    关于这个问题,其实很简单.不知道为什么网上的资料乱遭的.故自己写下来,方便有不明白的童鞋参考. 左键点击左上角的区域会弹出一个菜单,选择属性. 如下图就能轻松的修改窗口的大小了.

  4. sed用法小结

    简介: sed 是一种在线编辑器,它一次处理一行内容.处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区 ...

  5. Dominating Patterns

    Dominating Patterns Time Limit:3000MS   Memory Limit:Unknown   64bit IO Format:%lld & %llu Descr ...

  6. GCD应用场景

    1.计算文件大小放在子线程中中计算,计算完了,回到主线程更新UI

  7. JAVA-面向对象--封装

    1. 如果一个类中没有定义构造函数,会自动加上一个空参的默认构造函数 如果定义了一个构造函数,默认的空参构造函数就没有了. 2. this 当成员变量与局部变量重名的时候,可以使用this来区分.th ...

  8. linux 命令--sed

    简介 sed 是一种在线编辑器,它一次处理一行内容.处理时,把当前处理的行存储在临时缓冲区中,称为"模式空间"(pattern space),接着用sed命令处理缓冲区中的内容,处 ...

  9. Block 实现 浅析

    前言 这里 有关于 block 的 5 道测试题,建议你阅读本文之前先做一下测试. 先介绍一下什么是闭包.在 wikipedia 上,闭包的定义) 是: In programming language ...

  10. RACSignal的Subscription深入

    ReactiveCocoa是一个FRP的思想在Objective-C中的实现框架,目前在美团的项目中被广泛使用.对于ReactiveCocoa的基本用法,网上有很多相关的资料,本文不再讨论.RACSi ...