【发布时间】:2011-04-10 11:17:09
【问题描述】:
我正在尝试提供一个应用内 Activity,它在 设备的媒体存储,并允许用户选择一个。用户制作后 选择时,应用程序会读取原始的全尺寸图像并对其进行处理。
我正在使用以下代码在外部的所有图像上创建一个Cursor
存储:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.image_select );
mGridView = (GridView) findViewById( R.id.image_select_grid );
// Query for all images on external storage
String[] projection = { MediaStore.Images.Media._ID };
String selection = "";
String [] selectionArgs = null;
mImageCursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, selection, selectionArgs, null );
// Initialize an adapter to display images in grid
if ( mImageCursor != null ) {
mImageCursor.moveToFirst();
mAdapter = new LazyCursorAdapter(this, mImageCursor, R.drawable.image_select_default);
mGridView.setAdapter( mAdapter );
} else {
Log.i(TAG, "System media store is empty.");
}
}
以下代码加载缩略图(Android 2.x 代码显示):
// ...
// Build URI to the main image from the cursor
int imageID = cursor.getInt( cursor.getColumnIndex(MediaStore.Images.Media._ID) );
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
Integer.toString(imageID) );
loadThumbnailImage( uri.toString() );
// ...
protected Bitmap loadThumbnailImage( String url ) {
// Get original image ID
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
// Get (or create upon demand) the micro thumbnail for the original image.
return MediaStore.Images.Thumbnails.getThumbnail(mContext.getContentResolver(),
originalImageId, MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
一旦用户做出选择,下面的代码就会从 URL 中加载原始图像:
public Bitmap loadFullImage( Context context, Uri photoUri ) {
Cursor photoCursor = null;
try {
// Attempt to fetch asset filename for image
String[] projection = { MediaStore.Images.Media.DATA };
photoCursor = context.getContentResolver().query( photoUri,
projection, null, null, null );
if ( photoCursor != null && photoCursor.getCount() == 1 ) {
photoCursor.moveToFirst();
String photoFilePath = photoCursor.getString(
photoCursor.getColumnIndex(MediaStore.Images.Media.DATA) );
// Load image from path
return BitmapFactory.decodeFile( photoFilePath, null );
}
} finally {
if ( photoCursor != null ) {
photoCursor.close();
}
}
return null;
}
我在某些 Android 设备(包括我自己的个人手机)上看到的问题是
我从onCreate() 的查询中获得的光标包含一些缺少实际全尺寸图像文件(JPG 或PNG)的条目。 (就我的手机而言,图像已被导入并随后被 iPhoto 删除)。
孤立的条目可能有也可能没有缩略图,这取决于 AWOL 时缩略图是否在实际媒体文件之前生成。最终结果是应用显示实际不存在的图像的缩略图。
我有几个问题:
- 我是否可以向
MediaStore内容提供者查询以过滤掉 返回的Cursor中缺少媒体的图片? - 是否有强制
MediaStore重新扫描并消除孤立条目的方法或API?在我的手机上,我安装了 USB,然后卸载了外部媒体,这应该会触发重新扫描。但孤立条目仍然存在。 - 或者是我的方法有什么根本性的问题导致了这个问题?
谢谢。
【问题讨论】:
标签: android image media android-contentprovider