不幸的是,mediastore.images.media.latitude和mediastore.images.media.longitude是
deprecated in Android Q
.
The work around
因为这是用来
ExifInterface
这样地:
Cursor cursor = null;
try {
String[] projection = {
MediaStore.Files.FileColumns._ID,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.WIDTH,
MediaStore.Images.Media.HEIGHT,
MediaStore.MediaColumns.TITLE,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.LATITUDE,
MediaStore.Images.Media.LONGITUDE
};
cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
MediaStore.Images.Media.DATE_TAKEN + " DESC");
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID);
int titleColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.TITLE);
int latColumn = BuildCompat.isAtLeastQ() ? -1
: cursor.getColumnIndexOrThrow(MediaStore.Images.Media.LATITUDE);
int longColumn = BuildCompat.isAtLeastQ() ? -1
: cursor.getColumnIndexOrThrow(MediaStore.Images.Media.LONGITUDE);
while (cursor.moveToNext()) {
Uri photoUri = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
cursor.getString(idColumn));
String title = cursor.getString(titleColumn);
final double[] latLong;
if (BuildCompat.isAtLeastQ()) {
photoUri = MediaStore.setRequireOriginal(photoUri);
InputStream stream = getContentResolver().openInputStream(photoUri);
if (stream == null) {
Log.w(TAG, "Got a null input stream for " + photoUri);
continue;
}
ExifInterface exifInterface = new ExifInterface(stream);
double[] returnedLatLong = exifInterface.getLatLong();
latLong = returnedLatLong != null ? returnedLatLong : new double[2];
stream.close();
} else {
latLong = new double[]{
cursor.getFloat(latColumn),
cursor.getFloat(longColumn)
};
}
Log.i(TAG, title + " | lat: " + latLong[0] + " | lng: " + latLong[1]);
}
} catch (NullPointerException | IOException ex) {
Log.e(TAG, "Caught exception", ex);
} finally {
if (cursor != null) {
cursor.close();
}
}
这是目前在Android Q上获取照片经纬度的唯一方法。
这需要保持
ACCESS_MEDIA_LOCATION
许可。