我从我的应用程序启动相机拍摄照片。它也可在画廊中找到。Android获取最新拍摄照片的路径
与此有关的常见问题是如何知道照片的路径。所提出的解决方案是:
- 保存路径自己,并使用
EXTRA_OUTPUT
- 采取从画廊中的最后拍摄的照片的路径发送。
解决方案1 isn't reliable。
我努力使解决方案2的工作,有了这个代码:
public static String getTakenPhotoPath(Context context) {
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
return cursor.getString(column_index_data);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
这不返回的最新照片的路径;它返回前一个。询问最新照片的路径之前,我这样做:
private void addToGallery(Uri urlType, String path) {
if (!Strings.isNullOrEmpty(path)) {
ContentValues values = new ContentValues();
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.MediaColumns.DATA, path);
getContentResolver().insert(urlType, values);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(new File(path));
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
}
解决方案2比解决方案1的可靠性差很多。没有相机应用程序要求'MediaStore'索引的图像,更不用说及时这样做了。查看[这个答案](https://stackoverflow.com/a/41945392/115145)为我推荐的'ACTION_IMAGE_CAPTURE'分类。 – CommonsWare
解决方案1是可靠的。我从来没有见过它失败。 – greenapps
@greenapps:您还没有看到来自各种相机应用程序的Stack Overflow报告问题的所有人员。 'ACTION_IMAGE_CAPTURE'只是没有经过太多的测试,有些开发人员并没有阅读关于'ACTION_IMAGE_CAPTURE'应该如何工作的文档。看到[从2015年的这个咆哮](https://commonsware.com/blog/2015/06/08/action-image-capture-fallacy.html)了解更多。 – CommonsWare