Android中利用ContentResolver获取本地音乐和相册

在Android中,例如图库和音乐播放器,它们能够扫描我们的系统,获取到本地的相片跟音乐,这一点是如何做到的呢?

当我们往手机上放图片或者音乐的时候,会在手机内存中某个位置上的某个database中存放图片或者音乐的信息,而我们的应用程序是能够通过ContentResolver去读取到这些数据的。

下面可以先看一下database在哪,如下:

然后在data/data/下面呢,有很多provider提供的数据库,而我们的音乐或者图片就是在一个叫做Media的库下:

external是智能手机中内置的SD卡,而internal则是机身的内存。

这两个database里面的结构是一样的,我们把external给拉到本地电脑上,如下红色框框显示的,左边就是从手机SD卡拉到电脑,右边是从电脑推到手机SD卡上。

接下来可以利用SQLiteSpy之类的工具打开我们的数据库,可以看到Images 和 Audio 相关的表和视图:

比如图片,我们可以查看images这张表,其结构如下:

音乐,可以查看audio的视图,如下:

既然知道了这些表的数据结构,那么如何在我们的应用程序中去获取到这些数据呢?答案,当然就是利用ContentResolver了。

具体看代码,下面我写的一个MusicLoader,是为了获取本地音乐,其中利用了一些过滤条件,只拿出我想要的音乐。

[java] view plaincopyprint?

  1. package com.example.nature;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.content.ContentResolver;
  5. import android.content.ContentUris;
  6. import android.database.Cursor;
  7. import android.net.Uri;
  8. import android.os.Parcel;
  9. import android.os.Parcelable;
  10. import android.provider.MediaStore.Audio.Media;
  11. import android.util.Log;
  12. public class MusicLoader {
  13. private static final String TAG = "com.example.nature.MusicLoader";
  14. private static List<MusicInfo> musicList = new ArrayList<MusicInfo>();
  15. private static MusicLoader musicLoader;
  16. private static ContentResolver contentResolver;
  17. //Uri,指向external的database
  18. private Uri contentUri = Media.EXTERNAL_CONTENT_URI;
  19. //projection:选择的列; where:过滤条件; sortOrder:排序。
  20. private String[] projection = {
  21. Media._ID,
  22. Media.DISPLAY_NAME,
  23. Media.DATA,
  24. Media.ALBUM,
  25. Media.ARTIST,
  26. Media.DURATION,
  27. Media.SIZE
  28. };
  29. private String where =  "mime_type in (‘audio/mpeg‘,‘audio/x-ms-wma‘) and bucket_display_name <> ‘audio‘ and is_music > 0 " ;
  30. private String sortOrder = Media.DATA;
  31. public static MusicLoader instance(ContentResolver pContentResolver){
  32. if(musicLoader == null){
  33. contentResolver = pContentResolver;
  34. musicLoader = new MusicLoader();
  35. }
  36. return musicLoader;
  37. }
  38. private MusicLoader(){                                                                                                             //利用ContentResolver的query函数来查询数据,然后将得到的结果放到MusicInfo对象中,最后放到数组中
  39. Cursor cursor = contentResolver.query(contentUri, projection, where, null, sortOrder);
  40. if(cursor == null){
  41. Log.v(TAG,"Line(37  )   Music Loader cursor == null.");
  42. }else if(!cursor.moveToFirst()){
  43. Log.v(TAG,"Line(39  )   Music Loader cursor.moveToFirst() returns false.");
  44. }else{
  45. int displayNameCol = cursor.getColumnIndex(Media.DISPLAY_NAME);
  46. int albumCol = cursor.getColumnIndex(Media.ALBUM);
  47. int idCol = cursor.getColumnIndex(Media._ID);
  48. int durationCol = cursor.getColumnIndex(Media.DURATION);
  49. int sizeCol = cursor.getColumnIndex(Media.SIZE);
  50. int artistCol = cursor.getColumnIndex(Media.ARTIST);
  51. int urlCol = cursor.getColumnIndex(Media.DATA);
  52. do{
  53. String title = cursor.getString(displayNameCol);
  54. String album = cursor.getString(albumCol);
  55. long id = cursor.getLong(idCol);
  56. int duration = cursor.getInt(durationCol);
  57. long size = cursor.getLong(sizeCol);
  58. String artist = cursor.getString(artistCol);
  59. String url = cursor.getString(urlCol);
  60. MusicInfo musicInfo = new MusicInfo(id, title);
  61. musicInfo.setAlbum(album);
  62. musicInfo.setDuration(duration);
  63. musicInfo.setSize(size);
  64. musicInfo.setArtist(artist);
  65. musicInfo.setUrl(url);
  66. musicList.add(musicInfo);
  67. }while(cursor.moveToNext());
  68. }
  69. }
  70. public List<MusicInfo> getMusicList(){
  71. return musicList;
  72. }
  73. public Uri getMusicUriById(long id){
  74. Uri uri = ContentUris.withAppendedId(contentUri, id);
  75. return uri;
  76. }
  77. //下面是自定义的一个MusicInfo子类,实现了Parcelable,为的是可以将整个MusicInfo的ArrayList在Activity和Service中传送,=_=!!,但其实不用
  78. static class MusicInfo implements Parcelable{
  79. private long id;
  80. private String title;
  81. private String album;
  82. private int duration;
  83. private long size;
  84. private String artist;
  85. private String url;
  86. public MusicInfo(){
  87. }
  88. public MusicInfo(long pId, String pTitle){
  89. id = pId;
  90. title = pTitle;
  91. }
  92. public String getArtist() {
  93. return artist;
  94. }
  95. public void setArtist(String artist) {
  96. this.artist = artist;
  97. }
  98. public long getSize() {
  99. return size;
  100. }
  101. public void setSize(long size) {
  102. this.size = size;
  103. }
  104. public long getId() {
  105. return id;
  106. }
  107. public void setId(long id) {
  108. this.id = id;
  109. }
  110. public String getTitle() {
  111. return title;
  112. }
  113. public void setTitle(String title) {
  114. this.title = title;
  115. }
  116. public String getAlbum() {
  117. return album;
  118. }
  119. public void setAlbum(String album) {
  120. this.album = album;
  121. }
  122. public int getDuration() {
  123. return duration;
  124. }
  125. public void setDuration(int duration) {
  126. this.duration = duration;
  127. }
  128. public String getUrl() {
  129. return url;
  130. }
  131. public void setUrl(String url) {
  132. this.url = url;
  133. }
  134. @Override
  135. public int describeContents() {
  136. return 0;
  137. }
  138. @Override
  139. public void writeToParcel(Parcel dest, int flags) {
  140. dest.writeLong(id);
  141. dest.writeString(title);
  142. dest.writeString(album);
  143. dest.writeString(artist);
  144. dest.writeString(url);
  145. dest.writeInt(duration);
  146. dest.writeLong(size);
  147. }
  148. public static final Parcelable.Creator<MusicInfo>
  149. CREATOR = new Creator<MusicLoader.MusicInfo>() {
  150. @Override
  151. public MusicInfo[] newArray(int size) {
  152. return new MusicInfo[size];
  153. }
  154. @Override
  155. public MusicInfo createFromParcel(Parcel source) {
  156. MusicInfo musicInfo = new MusicInfo();
  157. musicInfo.setId(source.readLong());
  158. musicInfo.setTitle(source.readString());
  159. musicInfo.setAlbum(source.readString());
  160. musicInfo.setArtist(source.readString());
  161. musicInfo.setUrl(source.readString());
  162. musicInfo.setDuration(source.readInt());
  163. musicInfo.setSize(source.readLong());
  164. return musicInfo;
  165. }
  166. };
  167. }
  168. }

[java] view plain copy

print?

  1. package com.example.nature;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.content.ContentResolver;
  5. import android.content.ContentUris;
  6. import android.database.Cursor;
  7. import android.net.Uri;
  8. import android.os.Parcel;
  9. import android.os.Parcelable;
  10. import android.provider.MediaStore.Audio.Media;
  11. import android.util.Log;
  12. public class MusicLoader {
  13. private static final String TAG = "com.example.nature.MusicLoader";
  14. private static List<MusicInfo> musicList = new ArrayList<MusicInfo>();
  15. private static MusicLoader musicLoader;
  16. private static ContentResolver contentResolver;
  17. //Uri,指向external的database
  18. private Uri contentUri = Media.EXTERNAL_CONTENT_URI;
  19. //projection:选择的列; where:过滤条件; sortOrder:排序。
  20. private String[] projection = {
  21. Media._ID,
  22. Media.DISPLAY_NAME,
  23. Media.DATA,
  24. Media.ALBUM,
  25. Media.ARTIST,
  26. Media.DURATION,
  27. Media.SIZE
  28. };
  29. private String where =  "mime_type in (‘audio/mpeg‘,‘audio/x-ms-wma‘) and bucket_display_name <> ‘audio‘ and is_music > 0 " ;
  30. private String sortOrder = Media.DATA;
  31. public static MusicLoader instance(ContentResolver pContentResolver){
  32. if(musicLoader == null){
  33. contentResolver = pContentResolver;
  34. musicLoader = new MusicLoader();
  35. }
  36. return musicLoader;
  37. }
  38. private MusicLoader(){                                                                                                             //利用ContentResolver的query函数来查询数据,然后将得到的结果放到MusicInfo对象中,最后放到数组中
  39. Cursor cursor = contentResolver.query(contentUri, projection, where, null, sortOrder);
  40. if(cursor == null){
  41. Log.v(TAG,"Line(37  )   Music Loader cursor == null.");
  42. }else if(!cursor.moveToFirst()){
  43. Log.v(TAG,"Line(39  )   Music Loader cursor.moveToFirst() returns false.");
  44. }else{
  45. int displayNameCol = cursor.getColumnIndex(Media.DISPLAY_NAME);
  46. int albumCol = cursor.getColumnIndex(Media.ALBUM);
  47. int idCol = cursor.getColumnIndex(Media._ID);
  48. int durationCol = cursor.getColumnIndex(Media.DURATION);
  49. int sizeCol = cursor.getColumnIndex(Media.SIZE);
  50. int artistCol = cursor.getColumnIndex(Media.ARTIST);
  51. int urlCol = cursor.getColumnIndex(Media.DATA);
  52. do{
  53. String title = cursor.getString(displayNameCol);
  54. String album = cursor.getString(albumCol);
  55. long id = cursor.getLong(idCol);
  56. int duration = cursor.getInt(durationCol);
  57. long size = cursor.getLong(sizeCol);
  58. String artist = cursor.getString(artistCol);
  59. String url = cursor.getString(urlCol);
  60. MusicInfo musicInfo = new MusicInfo(id, title);
  61. musicInfo.setAlbum(album);
  62. musicInfo.setDuration(duration);
  63. musicInfo.setSize(size);
  64. musicInfo.setArtist(artist);
  65. musicInfo.setUrl(url);
  66. musicList.add(musicInfo);
  67. }while(cursor.moveToNext());
  68. }
  69. }
  70. public List<MusicInfo> getMusicList(){
  71. return musicList;
  72. }
  73. public Uri getMusicUriById(long id){
  74. Uri uri = ContentUris.withAppendedId(contentUri, id);
  75. return uri;
  76. }
  77. //下面是自定义的一个MusicInfo子类,实现了Parcelable,为的是可以将整个MusicInfo的ArrayList在Activity和Service中传送,=_=!!,但其实不用
  78. static class MusicInfo implements Parcelable{
  79. private long id;
  80. private String title;
  81. private String album;
  82. private int duration;
  83. private long size;
  84. private String artist;
  85. private String url;
  86. public MusicInfo(){
  87. }
  88. public MusicInfo(long pId, String pTitle){
  89. id = pId;
  90. title = pTitle;
  91. }
  92. public String getArtist() {
  93. return artist;
  94. }
  95. public void setArtist(String artist) {
  96. this.artist = artist;
  97. }
  98. public long getSize() {
  99. return size;
  100. }
  101. public void setSize(long size) {
  102. this.size = size;
  103. }
  104. public long getId() {
  105. return id;
  106. }
  107. public void setId(long id) {
  108. this.id = id;
  109. }
  110. public String getTitle() {
  111. return title;
  112. }
  113. public void setTitle(String title) {
  114. this.title = title;
  115. }
  116. public String getAlbum() {
  117. return album;
  118. }
  119. public void setAlbum(String album) {
  120. this.album = album;
  121. }
  122. public int getDuration() {
  123. return duration;
  124. }
  125. public void setDuration(int duration) {
  126. this.duration = duration;
  127. }
  128. public String getUrl() {
  129. return url;
  130. }
  131. public void setUrl(String url) {
  132. this.url = url;
  133. }
  134. @Override
  135. public int describeContents() {
  136. return 0;
  137. }
  138. @Override
  139. public void writeToParcel(Parcel dest, int flags) {
  140. dest.writeLong(id);
  141. dest.writeString(title);
  142. dest.writeString(album);
  143. dest.writeString(artist);
  144. dest.writeString(url);
  145. dest.writeInt(duration);
  146. dest.writeLong(size);
  147. }
  148. public static final Parcelable.Creator<MusicInfo>
  149. CREATOR = new Creator<MusicLoader.MusicInfo>() {
  150. @Override
  151. public MusicInfo[] newArray(int size) {
  152. return new MusicInfo[size];
  153. }
  154. @Override
  155. public MusicInfo createFromParcel(Parcel source) {
  156. MusicInfo musicInfo = new MusicInfo();
  157. musicInfo.setId(source.readLong());
  158. musicInfo.setTitle(source.readString());
  159. musicInfo.setAlbum(source.readString());
  160. musicInfo.setArtist(source.readString());
  161. musicInfo.setUrl(source.readString());
  162. musicInfo.setDuration(source.readInt());
  163. musicInfo.setSize(source.readLong());
  164. return musicInfo;
  165. }
  166. };
  167. }
  168. }

package com.example.nature;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;

public class MusicLoader {

	private static final String TAG = "com.example.nature.MusicLoader";

	private static List<MusicInfo> musicList = new ArrayList<MusicInfo>();

	private static MusicLoader musicLoader;

	private static ContentResolver contentResolver;
	//Uri,指向external的database
	private Uri contentUri = Media.EXTERNAL_CONTENT_URI;
	//projection:选择的列; where:过滤条件; sortOrder:排序。
	private String[] projection = {
			Media._ID,
			Media.DISPLAY_NAME,
			Media.DATA,
			Media.ALBUM,
			Media.ARTIST,
			Media.DURATION,
			Media.SIZE
	};
	private String where =  "mime_type in (‘audio/mpeg‘,‘audio/x-ms-wma‘) and bucket_display_name <> ‘audio‘ and is_music > 0 " ;
	private String sortOrder = Media.DATA;

	public static MusicLoader instance(ContentResolver pContentResolver){
		if(musicLoader == null){
			contentResolver = pContentResolver;
			musicLoader = new MusicLoader();
		}
		return musicLoader;
	}

	private MusicLoader(){		                                                                                                       //利用ContentResolver的query函数来查询数据,然后将得到的结果放到MusicInfo对象中,最后放到数组中
		Cursor cursor = contentResolver.query(contentUri, projection, where, null, sortOrder);
		if(cursor == null){
			Log.v(TAG,"Line(37	)	Music Loader cursor == null.");
		}else if(!cursor.moveToFirst()){
			Log.v(TAG,"Line(39	)	Music Loader cursor.moveToFirst() returns false.");
		}else{
			int displayNameCol = cursor.getColumnIndex(Media.DISPLAY_NAME);
			int albumCol = cursor.getColumnIndex(Media.ALBUM);
			int idCol = cursor.getColumnIndex(Media._ID);
			int durationCol = cursor.getColumnIndex(Media.DURATION);
			int sizeCol = cursor.getColumnIndex(Media.SIZE);
			int artistCol = cursor.getColumnIndex(Media.ARTIST);
			int urlCol = cursor.getColumnIndex(Media.DATA);
			do{
				String title = cursor.getString(displayNameCol);
				String album = cursor.getString(albumCol);
				long id = cursor.getLong(idCol);
				int duration = cursor.getInt(durationCol);
				long size = cursor.getLong(sizeCol);
				String artist = cursor.getString(artistCol);
				String url = cursor.getString(urlCol);

				MusicInfo musicInfo = new MusicInfo(id, title);
				musicInfo.setAlbum(album);
				musicInfo.setDuration(duration);
				musicInfo.setSize(size);
				musicInfo.setArtist(artist);
				musicInfo.setUrl(url);
				musicList.add(musicInfo);

			}while(cursor.moveToNext());
		}
	}

	public List<MusicInfo> getMusicList(){
		return musicList;
	}

	public Uri getMusicUriById(long id){
		Uri uri = ContentUris.withAppendedId(contentUri, id);
		return uri;
	}
        //下面是自定义的一个MusicInfo子类,实现了Parcelable,为的是可以将整个MusicInfo的ArrayList在Activity和Service中传送,=_=!!,但其实不用
	static class MusicInfo implements Parcelable{
		private long id;
		private String title;
		private String album;
		private int duration;
		private long size;
		private String artist;
		private String url;		

		public MusicInfo(){

		}

		public MusicInfo(long pId, String pTitle){
			id = pId;
			title = pTitle;
		}

		public String getArtist() {
			return artist;
		}

		public void setArtist(String artist) {
			this.artist = artist;
		}

		public long getSize() {
			return size;
		}

		public void setSize(long size) {
			this.size = size;
		}		

		public long getId() {
			return id;
		}

		public void setId(long id) {
			this.id = id;
		}

		public String getTitle() {
			return title;
		}

		public void setTitle(String title) {
			this.title = title;
		}

		public String getAlbum() {
			return album;
		}

		public void setAlbum(String album) {
			this.album = album;
		}

		public int getDuration() {
			return duration;
		}

		public void setDuration(int duration) {
			this.duration = duration;
		}	

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		@Override
		public int describeContents() {
			return 0;
		}

		@Override
		public void writeToParcel(Parcel dest, int flags) {
			dest.writeLong(id);
			dest.writeString(title);
			dest.writeString(album);
			dest.writeString(artist);
			dest.writeString(url);
			dest.writeInt(duration);
			dest.writeLong(size);
		}

		public static final Parcelable.Creator<MusicInfo>
			CREATOR = new Creator<MusicLoader.MusicInfo>() {

			@Override
			public MusicInfo[] newArray(int size) {
				return new MusicInfo[size];
			}

			@Override
			public MusicInfo createFromParcel(Parcel source) {
				MusicInfo musicInfo = new MusicInfo();
				musicInfo.setId(source.readLong());
				musicInfo.setTitle(source.readString());
				musicInfo.setAlbum(source.readString());
				musicInfo.setArtist(source.readString());
				musicInfo.setUrl(source.readString());
				musicInfo.setDuration(source.readInt());
				musicInfo.setSize(source.readLong());
				return musicInfo;
			}
		};
	}
}

最后,我们就可以在我们的手机上看到我们音乐了,不过数据库中有些是乱码的,我还不知道怎么解决。。。

图片的获取也是相类似的,放上代码,具体的自行琢磨:

[java] view plaincopyprint?

  1. package com.example.hmgallery;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.content.ContentResolver;
  5. import android.database.Cursor;
  6. import android.provider.MediaStore.Images.Media;
  7. import android.provider.MediaStore.Images.Thumbnails;
  8. import android.util.SparseArray;
  9. public class Images{
  10. public static final String IMAGE_PATH = "IMAGE_PATH";
  11. public static final String IMAGE_ID = "IMAGE_ID";
  12. public static final String IMAGE_POSITION = "IMAGE_POSITION";
  13. public static final String IMAGE_COUNTS = "IMAGE_COUNTS";
  14. private static List<ImageItem> imageItems = new ArrayList<ImageItem>();
  15. private static SparseArray<ImageItem> tempArray;
  16. public static void loadImages(ContentResolver contentResolver){
  17. tempArray = new SparseArray<ImageItem>();
  18. String[] projection = {Media._ID,Media.DATA,Media.ORIENTATION};
  19. String where =  Media.BUCKET_DISPLAY_NAME + " = ‘Camera‘";
  20. String sortOrder = Media._ID + " desc";
  21. StringBuilder inImageIds = new StringBuilder(Thumbnails.IMAGE_ID);
  22. inImageIds.append(" in ( ");
  23. Cursor cursor = contentResolver.query(Media.EXTERNAL_CONTENT_URI, projection, where, null, sortOrder);
  24. if(cursor.moveToFirst()){
  25. do {
  26. int imageId = cursor.getInt(cursor.getColumnIndex(Media._ID));
  27. String imagePath = cursor.getString(cursor.getColumnIndex(Media.DATA));
  28. int orientation = cursor.getInt(cursor.getColumnIndex(Media.ORIENTATION));
  29. ImageItem imageItem = new ImageItem(imageId,imagePath,orientation);
  30. imageItems.add(imageItem);
  31. tempArray.put(imageId, imageItem);
  32. inImageIds.append(imageId).append(",");
  33. }while(cursor.moveToNext());
  34. }
  35. inImageIds.deleteCharAt(inImageIds.length() - 1);
  36. inImageIds.append(" ) ");
  37. String[] thumbnailProjection = {Thumbnails.DATA,Thumbnails.IMAGE_ID};
  38. cursor = contentResolver.query(Thumbnails.EXTERNAL_CONTENT_URI, thumbnailProjection, inImageIds.toString(), null, null);
  39. if(cursor.moveToFirst()){
  40. do {
  41. int imageId = cursor.getInt(cursor.getColumnIndex(Thumbnails.IMAGE_ID));
  42. String thumnbailPath = cursor.getString(cursor.getColumnIndex(Media.DATA));
  43. ImageItem imageItem = tempArray.get(imageId);
  44. if(imageItem != null){
  45. imageItem.setThumbnailPath(thumnbailPath);
  46. }
  47. }while(cursor.moveToNext());
  48. }
  49. tempArray = null;
  50. }
  51. public static ImageItem[] getImageItems(){
  52. return imageItems.toArray(new ImageItem[]{});
  53. }
  54. }

[java] view plain copy

print?

  1. package com.example.hmgallery;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import android.content.ContentResolver;
  5. import android.database.Cursor;
  6. import android.provider.MediaStore.Images.Media;
  7. import android.provider.MediaStore.Images.Thumbnails;
  8. import android.util.SparseArray;
  9. public class Images{
  10. public static final String IMAGE_PATH = "IMAGE_PATH";
  11. public static final String IMAGE_ID = "IMAGE_ID";
  12. public static final String IMAGE_POSITION = "IMAGE_POSITION";
  13. public static final String IMAGE_COUNTS = "IMAGE_COUNTS";
  14. private static List<ImageItem> imageItems = new ArrayList<ImageItem>();
  15. private static SparseArray<ImageItem> tempArray;
  16. public static void loadImages(ContentResolver contentResolver){
  17. tempArray = new SparseArray<ImageItem>();
  18. String[] projection = {Media._ID,Media.DATA,Media.ORIENTATION};
  19. String where =  Media.BUCKET_DISPLAY_NAME + " = ‘Camera‘";
  20. String sortOrder = Media._ID + " desc";
  21. StringBuilder inImageIds = new StringBuilder(Thumbnails.IMAGE_ID);
  22. inImageIds.append(" in ( ");
  23. Cursor cursor = contentResolver.query(Media.EXTERNAL_CONTENT_URI, projection, where, null, sortOrder);
  24. if(cursor.moveToFirst()){
  25. do {
  26. int imageId = cursor.getInt(cursor.getColumnIndex(Media._ID));
  27. String imagePath = cursor.getString(cursor.getColumnIndex(Media.DATA));
  28. int orientation = cursor.getInt(cursor.getColumnIndex(Media.ORIENTATION));
  29. ImageItem imageItem = new ImageItem(imageId,imagePath,orientation);
  30. imageItems.add(imageItem);
  31. tempArray.put(imageId, imageItem);
  32. inImageIds.append(imageId).append(",");
  33. }while(cursor.moveToNext());
  34. }
  35. inImageIds.deleteCharAt(inImageIds.length() - 1);
  36. inImageIds.append(" ) ");
  37. String[] thumbnailProjection = {Thumbnails.DATA,Thumbnails.IMAGE_ID};
  38. cursor = contentResolver.query(Thumbnails.EXTERNAL_CONTENT_URI, thumbnailProjection, inImageIds.toString(), null, null);
  39. if(cursor.moveToFirst()){
  40. do {
  41. int imageId = cursor.getInt(cursor.getColumnIndex(Thumbnails.IMAGE_ID));
  42. String thumnbailPath = cursor.getString(cursor.getColumnIndex(Media.DATA));
  43. ImageItem imageItem = tempArray.get(imageId);
  44. if(imageItem != null){
  45. imageItem.setThumbnailPath(thumnbailPath);
  46. }
  47. }while(cursor.moveToNext());
  48. }
  49. tempArray = null;
  50. }
  51. public static ImageItem[] getImageItems(){
  52. return imageItems.toArray(new ImageItem[]{});
  53. }
  54. }

package com.example.hmgallery;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.SparseArray;

public class Images{

	public static final String IMAGE_PATH = "IMAGE_PATH";
	public static final String IMAGE_ID = "IMAGE_ID";
	public static final String IMAGE_POSITION = "IMAGE_POSITION";
	public static final String IMAGE_COUNTS = "IMAGE_COUNTS";	

	private static List<ImageItem> imageItems = new ArrayList<ImageItem>();

	private static SparseArray<ImageItem> tempArray;

	public static void loadImages(ContentResolver contentResolver){
		tempArray = new SparseArray<ImageItem>();
		String[] projection = {Media._ID,Media.DATA,Media.ORIENTATION};
		String where =  Media.BUCKET_DISPLAY_NAME + " = ‘Camera‘";
		String sortOrder = Media._ID + " desc";
		StringBuilder inImageIds = new StringBuilder(Thumbnails.IMAGE_ID);
		inImageIds.append(" in ( ");
		Cursor cursor = contentResolver.query(Media.EXTERNAL_CONTENT_URI, projection, where, null, sortOrder);
		if(cursor.moveToFirst()){
			do {
				int imageId = cursor.getInt(cursor.getColumnIndex(Media._ID));
				String imagePath = cursor.getString(cursor.getColumnIndex(Media.DATA));
				int orientation = cursor.getInt(cursor.getColumnIndex(Media.ORIENTATION));
				ImageItem imageItem = new ImageItem(imageId,imagePath,orientation);
				imageItems.add(imageItem);
				tempArray.put(imageId, imageItem);
				inImageIds.append(imageId).append(",");
			}while(cursor.moveToNext());
		}		

		inImageIds.deleteCharAt(inImageIds.length() - 1);
		inImageIds.append(" ) "); 

		String[] thumbnailProjection = {Thumbnails.DATA,Thumbnails.IMAGE_ID};
		cursor = contentResolver.query(Thumbnails.EXTERNAL_CONTENT_URI, thumbnailProjection, inImageIds.toString(), null, null);
		if(cursor.moveToFirst()){
			do {
				int imageId = cursor.getInt(cursor.getColumnIndex(Thumbnails.IMAGE_ID));
				String thumnbailPath = cursor.getString(cursor.getColumnIndex(Media.DATA));
				ImageItem imageItem = tempArray.get(imageId);
				if(imageItem != null){
					imageItem.setThumbnailPath(thumnbailPath);
				}
			}while(cursor.moveToNext());
		}
		tempArray = null;
	}

	public static ImageItem[] getImageItems(){
		return imageItems.toArray(new ImageItem[]{});
	}
}
时间: 2024-10-29 21:32:30

Android中利用ContentResolver获取本地音乐和相册的相关文章

Android中利用OpenMax 编程的基本流程

最近由于公司在做数字电视,播放器和模块由供应商打包一起卖,驱动调通了,可是播放器要硬件解码,和平台差异,原厂又没有相关文档,就自己试着看了一个系统的播放器流程,顺便整理了一下,也方便以后查询,希望对播放器硬解码的开发能起到点作用.由于对视频也不了解,所以难免有不少错误,欢迎高手指导. 1: 由文件或者设备来创建一个dataSource(DataSource) (其中可以是文件描述符fd, uri ,http) 2:  通过dataSource来创建一个MediaExtractor(即视频的分流器

Android中利用SharedPreferences保存信息

package com.example.sharepreferen; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.vi

如何在android中利用Theme设置application 的所有listview的style?~

今天看VLC的源代码,发现一个很神奇的东西 所有listview的点击效果背景色都是橘黄色 花了点时间找了一下看看怎么实现的. 首先,定义一个<selector> like this: <selector> <item android:state_pressed="true"> <shape android:shape="rectangle"> <solid android:color="@color/

Android中利用命令行进行截屏并导出到电脑上

声明:本博客为原创博客,未经允许,不得转载!原文链接为http://blog.csdn.net/bettarwang/article/details/27819525 大多数人最常用的截屏方法可能就是利用手机的快捷按键了,但是那样如果要导入到电脑中效率会比较低.实际上有更好的截屏方式,最简单的当然就是利用Eclipse中的DDMS进行截屏了,点击"Screen Capture"按钮后等待10多秒,然后就可直接利用Save按钮保存到电脑中. 显然,由于要进行图片显示的原因,在DDMS中会

Android中利用Handler实现消息的分发机制(三)

在第二篇文章<Android中利用Handler实现消息的分发机制(一)>中,我们讲到主线程的Looper是Android系统在启动App的时候,已经帮我们创建好了,而如果在子线程中需要去使用Handler的时候,我们就需要显式地去调用Looper的 prepare方法和loop方法,从而为子线程创建其唯一的Looper. 具体代码如下: class LooperThread extends Thread { public Handler mHandler; public void run()

Firefox中利用javascript调用本地程序

http://blog.csdn.net/jensonhjt/article/details/1765557 script>function hello () {  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  var file = Components.classes["@mozilla.org/file/local;1"].createInstance(

Android中利用ant进行多渠道循环批量打包

公司负责Android开发的小伙伴学习能力稍微偏弱,交代给他的自动化打包的任务,弄了好久依然没有成效.无奈只好亲自出手. 没有想到过程很顺利,我完全按照如下文章的步骤进行: 主要参考: Android中利用ant进行多渠道循环批量打包(一) Android中利用ant进行多渠道循环批量打包(二) 次要参考:?? Mac中用Ant实现Android的批量打包碰到的一些问题以及解决方法 Android Ant 批量多渠道打包实例.md [Android分享]?最新的Android Sdk 使用Ant

Android 中利用WebViewJavascriptBridge 实现js和java的交互(一)

此文出自:http://blog.csdn.net/sk719887916/article/details/47189607 ,skay 博客 按安卓开发目前现状来说,开发者大部分时间还是花在UI的屏幕适配上,使用原生控件开发成本已不是那么理想,鉴于很多项目和ios基于一致的ui界面,至使安卓UI开发成本花费更大的代价,因此目前结合Html5和原生控件是解决UI适配的一种很好的选择,处于APP性能也会用java和native层进行结合.不管是哪种结合,其实原理都差不多,只要按照它的协议来,是很容

在Android中利用SQLite实现对数据的增删查改

停更了一天,I'm back again~~当我们需要操作大量的数据时,我们首先想到的当然是数据库,因为可以通过简单的语句实现数据的增删改查,在Android中,我们不使用SQL或者ORACLE,我们使用SQLite,因为它占用资源更少,而语句格式与SQL语句一样. 首先,我们来在Android中实现数据库的创建与增删改查,引用数据库的类时,不再继承常用的Activity类,而是继承Android中的SQLiteOpenHelper,创建一个构造方法,四个参数分别是(Context contex