我正在尝试提供一个应用内活动,它在设备的媒体商店中显示照片的缩略图,并允许用户选择一个。在用户做出选择后,应用程序会读取原始的全尺寸图像并对其进行处理。
我正在使用以下代码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
? - 是否有一种方法或 API 可以强制
MediaStore
重新扫描并消除孤儿条目?在我的手机上,我安装了 USB,然后卸载了外部媒体,这应该会触发重新扫描。但是孤儿条目仍然存在。 - 或者我的方法有什么根本错误导致这个问题?
谢谢。