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数据,具体代码如下所示:
- 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<Integer, BucketEntry> 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<Integer, BucketEntry> buckets = new HashMap<Integer, BucketEntry>(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<BucketEntry>() {
- @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<BucketEntry> buffer = new ArrayList<BucketEntry>();
- 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所示:
到目前为止我们大致了解了Gallery数据加载的一个大体流程,接下来的文章将分析Album数据的读取以及数据封装。
Android源码之Gallery专题研究(1)的更多相关文章
- Android源码之Gallery专题研究(2)
引言 上一篇文章已经讲解了数据加载过程,接下来我们来看一看数据加载后的处理过程.按照正常的思维逻辑,当数据加载之后,接下来就应该考虑数据的显示逻辑. MVC显示逻辑 大家可能对J2EE的MVC架构比较 ...
- Android底层有一定的认识,研究过相关的Android源码
一.系统架构: 一).系统分层:(由下向上)[如图] 1.安卓系统分为四层,分别是Linux内核层.Libraries层.FrameWork层,以及Applications层: 其中Linux内核层包 ...
- android源码地址及下载介绍
git clone https://android.googlesource.com/device/common.git git clone https://android.googlesour ...
- Eclipse与Android源码中ProGuard工具的使用
由于工作需要,这两天和同事在研究android下面的ProGuard工具的使用,通过查看android官网对该工具的介绍以及网络上其它相关资料,再加上自己的亲手实践,算是有了一个基本了解.下面将自己的 ...
- android源码的目录结构
android源码的目录结构 [以下网络摘抄] |-- Makefile ! l/ a5 n% S% @- `0 d# z# a$ P4 V3 o7 R|-- bionic ...
- Android源码-学习随笔
在线代码网站1:http://grepcode.com/project/repository.grepcode.com/java/ext/com.google.android/android/ 书籍: ...
- Android拓展系列(11)--打造Windows下便携的Android源码阅读环境
因为EXT和NTFS格式的差异,我一直对于windows下阅读Android源码感到不满. 前几天,想把最新的android5.0的源码下下来研究一下,而平时日常使用的又是windows环境,于是专门 ...
- [安卓]windows下如何安装Android源码
本文改写于:http://www.cnblogs.com/skyme/archive/2011/05/14/2046040.html 1.下载并安装git: 在git-scm.com上下载并安装git ...
- Android源码分析-全面理解Context
前言 Context在android中的作用不言而喻,当我们访问当前应用的资源,启动一个新的activity的时候都需要提供Context,而这个Context到底是什么呢,这个问题好像很好回答又好像 ...
随机推荐
- could not perform addBatch
在执行存数据到数据库的操作时,由于增加的ID值小于或等于对应的索引值时会报这个错误
- PHP的抽象类、接口类的区别和选择【转载】
本文转自:http://blog.csdn.net/fanteathy/article/details/7309966 区别: 1.对接口的使用是通过关键字implements.对抽象类的使用是通过关 ...
- libc.so.6重做链接,删除导致的缺失问题(后期需要深入研究),未能成功升级
中间件启动,提示/lib64/libc.so.6版本过低,升级glibc后,修改临时环境变量,结果导致sgment fault错误,根据报错 ll /lib64/ |grep libc -rwxr-x ...
- servlet多次跳转报IllegalStateException异常
当发生在如下错误的时候,有一个方案可行, "java.lang.IllegalStateException: Cannot forward after response has been c ...
- 字符函数库 cctype
<cctype> (ctype.h) Character handling functions This header declares a set of functions to cla ...
- CSS Day04 css核心基础
1.在HTML中引入CSS的方法 (1)行内式 行内式即在标记的style属性中设定CSS样式,这种方式本质上没有体现出CSS的优势,因此不推荐使用. 例如: <h1 style=“colo ...
- centos7如何关闭防火墙
1.centos7自带了firewall,而不是iptables: 关闭firewall: service firewalld stop 或者: systemctl stop firewalld 禁止 ...
- ReactiveX--响应式编程の相关概念 浅析
在许多软件编程任务中,你或多或少期待你的指令将会按照你已经写好的顺序,依次增量执行和完成.但在ReactiveX,很多指令可以通过“观察者”并行执行,其结果将以任意顺序被捕获.你定义了一种“可观察的形 ...
- Swift - UIPasteboard剪贴板的使用详解(复制、粘贴文字和图片)
转载自:http://www.hangge.com/blog/cache/detail_1085.html UITextField.UITextView组件系统原生就支持文字的复制,但有时我们需要让其 ...
- Android 使用存放在存assets文件夹下的SQLite数据库
因为这次的项目需要自带数据,所以就就把数据都放到一个SQLite的数据库文件中了,之后把该文件放到了assets文件夹下面.一开始打算每次都从assets文件夹下面把该文件夹拷贝到手机的SD卡或者手机 ...