Android:从图库中获取图像,无需用户交互
我想从图库中获取图片(如果存在),而无需用户从图库中选择图片。我想以编程方式执行此操作。我尝试过以下方法:
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = new Activity().managedQuery( MediaStore.Images.Media.INTERNAL_CONTENT_URI, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
BitmapFactory.Options options = new BitmapFactory.Options();;
options.inSampleSize = 1;
Bitmap bm = BitmapFactory.decodeFile(
cursor.getString(column_index),options);
remoteView.setImageViewBitmap(R.id.image,bm);
我从工作线程而不是主 UI 线程调用这段代码。这种做法正确吗?如果不是,那么在没有用户交互的情况下从图库获取图像的更好方法是什么?
谢谢。
I want to fetch a picture, if present, from the gallery without having user to select picture from the gallery. I want to do this programmatically. I have tried following approach:
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = new Activity().managedQuery( MediaStore.Images.Media.INTERNAL_CONTENT_URI, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
BitmapFactory.Options options = new BitmapFactory.Options();;
options.inSampleSize = 1;
Bitmap bm = BitmapFactory.decodeFile(
cursor.getString(column_index),options);
remoteView.setImageViewBitmap(R.id.image,bm);
I'am calling this piece of code from a worker thread and not main UI thread. Is this approach correct? if not then what can be a better approach to get an image from gallery without user interaction?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这个问题有两个部分:从手机图库获取图像和更新用户界面。
看来您从图库中获取图像的方法是正确的。另一种方法详述如下: http://developer.android.com /guide/topics/data/data-storage.html#filesExternal。
您看到的 RuntimeException 是因为您尝试更新工作线程上的 UI。 Android 框架要求所有 UI 更改都发生在 UI 线程上。运行查询后,您必须调用
Activity.runOnUiThread()
来更新 UI。I think that there are two parts to this question: getting the image from the phone gallery and updating the UI.
It seems that your method is correct for getting the images from the gallery. Another method is detailed here: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal.
The RuntimeException you're seeing is because you're trying to update the UI on a worker thread. The Android framework requires all UI changes happen on the UI thread. You'll have to call
Activity.runOnUiThread()
after running the query to update the UI.