我從我的應用程序啓動相機拍攝照片。它也可在畫廊中找到。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