这是我想要找到的答案:
使用CameraX时,EXIF数据会自动设置,但不会设置GPS EXIF标签,因为:
- 需要权限来访问位置信息
- 有多种获取位置信息的方式,不同的选项对电池寿命有不同的影响,因此有控制权是很好的。
- 获取GPS位置信息可能需要很长时间(使用辅助GPS可能需要10秒,不使用辅助GPS可能需要长达10分钟)。
这是我在onImageSaved()回调函数中调用的函数:
fun setCurrentLocationInExif(context: Context, uri : Uri, fusedLocationClient : FusedLocationProviderClient){
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {
throw(Exception("no location found"))
}
else {
val locRequest = CurrentLocationRequest.Builder().setMaxUpdateAgeMillis(60000).build()
fusedLocationClient.getCurrentLocation(locRequest, null)
.addOnSuccessListener { location: Location? ->
if (location != null){
Log.d(TAG, "latitude=${location.latitude}")
Log.d(TAG, "longitude=${location.longitude}")
val uriFd = context.contentResolver.openFileDescriptor(uri, "rw")
if (uriFd != null) {
val uriExif = ExifInterface(uriFd.fileDescriptor)
uriExif.setGpsInfo(location)
uriExif.saveAttributes()
uriFd.close()
}
else{
throw(Exception("Cannot find file for uri=$uri"))
}
}
}
}
}
在 onImageSaved 的调用中:
override fun onImageSaved(output: ImageCapture.OutputFileResults){
setCurrentLocationInExif(requireContext(), output.savedUri!!, fusedLocationClient)
}
在我的主活动的onCreate方法中定义了fusedLocationClient,它在lateinit之后(您需要在gradle.build(app)中激活Play Services/位置服务):
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)