feat: GPS location

This commit is contained in:
zhoubinjia committed 2026-03-02 17:56:32 +08:00
1 parent 381a63927e
commit 8f03256f1e
11 files changed
+237 -9

No files matched your search

+2
View File
@@ -7,6 +7,8 @@
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
@@ -2189,7 +2189,9 @@ class Camera2Controller(private val context: Context) {
fun rebuildCaptureInfo(
result: TotalCaptureResult?,
imageWidth: Int,
imageHeight: Int
imageHeight: Int,
latitude: Double? = null,
longitude: Double? = null
): CaptureInfo {
val cameraId = _state.value.currentCameraId
val zoomRatio = _state.value.zoomRatio
@@ -2250,6 +2252,8 @@ class Camera2Controller(private val context: Context) {
imageWidth = imageWidth,
imageHeight = imageHeight,
captureTime = System.currentTimeMillis(),
latitude = latitude,
longitude = longitude
)
}
@@ -2349,7 +2353,7 @@ class Camera2Controller(private val context: Context) {
// PLog.d(TAG, "Matching Image and CaptureResult found for timestamp ${image.timestamp}")
// 构建 CaptureInfo
val captureInfo = rebuildCaptureInfo(result, width, height)
val captureInfo = rebuildCaptureInfo(result, width, height, _state.value.latitude, _state.value.longitude)
// 传递完整的 Image 对象、CaptureInfo、CameraCharacteristics 和 CaptureResult
val callback = onImageCaptured
@@ -2389,6 +2393,11 @@ class Camera2Controller(private val context: Context) {
_state.value = _state.value.copy(useP010 = enabled)
}
fun setLocation(latitude: Double?, longitude: Double?) {
PLog.d(TAG, "setLocation: $latitude, $longitude")
_state.value = _state.value.copy(latitude = latitude, longitude = longitude)
}
/**
* 执行 Live Photo 快照(在按下快门时尽早调用,以确定“之前”的时间范围)
*/
@@ -187,6 +187,8 @@ data class CameraState(
val useP010: Boolean = false,
val isP010Supported: Boolean = false,
val burstCapturing: Boolean = false,
val latitude: Double? = null,
val longitude: Double? = null,
) {
/**
* 是否全自动曝光
@@ -78,6 +78,7 @@ data class UserPreferences(
val launchCameraOnPhantomMode: Boolean = false,
val mirrorFrontCamera: Boolean = true,
val widgetTheme: WidgetTheme = WidgetTheme.FOLLOW_SYSTEM,
val saveLocation: Boolean = false,
)
/**
@@ -136,6 +137,7 @@ class UserPreferencesRepository(private val context: Context) {
private val LAUNCH_CAMERA_ON_PHANTOM_MODE = booleanPreferencesKey("launch_camera_on_phantom_mode")
private val MIRROR_FRONT_CAMERA = booleanPreferencesKey("mirror_front_camera")
private val WIDGET_THEME = stringPreferencesKey("widget_theme")
private val SAVE_LOCATION = booleanPreferencesKey("save_location")
}
/**
@@ -188,6 +190,7 @@ class UserPreferencesRepository(private val context: Context) {
launchCameraOnPhantomMode = preferences[LAUNCH_CAMERA_ON_PHANTOM_MODE] ?: false,
mirrorFrontCamera = preferences[MIRROR_FRONT_CAMERA] ?: true,
widgetTheme = WidgetTheme.valueOf(preferences[WIDGET_THEME] ?: WidgetTheme.FOLLOW_SYSTEM.name),
saveLocation = preferences[SAVE_LOCATION] ?: false,
)
}
@@ -616,4 +619,13 @@ class UserPreferencesRepository(private val context: Context) {
preferences[WIDGET_THEME] = theme.name
}
}
/**
* 保存是否记录地理位置
*/
suspend fun saveSaveLocation(enabled: Boolean) {
context.dataStore.edit { preferences ->
preferences[SAVE_LOCATION] = enabled
}
}
}
@@ -41,6 +41,10 @@ data class PhotoMetadata(
val brand: String? = null,
val dateTaken: Long? = null,
val location: String? = null,
// GPS(可选)
val latitude: Double? = null,
val longitude: Double? = null,
val altitude: Double? = null,
val iso: Int? = null,
val shutterSpeed: String? = null,
val focalLength: String? = null,
@@ -75,7 +79,10 @@ data class PhotoMetadata(
focalLength = focalLength?.substringBefore("mm")?.toFloatOrNull(),
focalLength35mm = focalLength35mm?.substringBefore("mm")?.toIntOrNull(),
exposureTime = parseExposureTime(shutterSpeed),
software = software ?: "PhotonCamera"
software = software ?: "PhotonCamera",
latitude = latitude,
longitude = longitude,
altitude = altitude
)
}
@@ -162,6 +169,9 @@ data class PhotoMetadata(
put("brand", brand ?: JSONObject.NULL)
put("dateTaken", dateTaken ?: JSONObject.NULL)
put("location", location ?: JSONObject.NULL)
put("latitude", latitude ?: JSONObject.NULL)
put("longitude", longitude ?: JSONObject.NULL)
put("altitude", altitude ?: JSONObject.NULL)
put("iso", iso ?: JSONObject.NULL)
put("shutterSpeed", shutterSpeed ?: JSONObject.NULL)
put("focalLength", focalLength ?: JSONObject.NULL)
@@ -251,6 +261,9 @@ data class PhotoMetadata(
brand = if (obj.isNull("brand")) null else obj.optString("brand"),
dateTaken = if (obj.isNull("dateTaken")) null else obj.optLong("dateTaken"),
location = if (obj.isNull("location")) null else obj.optString("location"),
latitude = if (obj.isNull("latitude")) null else obj.optDouble("latitude"),
longitude = if (obj.isNull("longitude")) null else obj.optDouble("longitude"),
altitude = if (obj.isNull("altitude")) null else obj.optDouble("altitude"),
iso = if (obj.isNull("iso")) null else obj.optInt("iso"),
shutterSpeed = if (obj.isNull("shutterSpeed")) null else obj.optString("shutterSpeed"),
focalLength = if (obj.isNull("focalLength")) null else obj.optString("focalLength"),
@@ -123,9 +123,19 @@ fun SettingsScreen(
val launchCameraOnPhantomMode by viewModel.launchCameraOnPhantomMode.collectAsState()
val mirrorFrontCamera by viewModel.mirrorFrontCamera.collectAsState(initial = true)
val widgetTheme by viewModel.widgetTheme.collectAsState()
val saveLocation by viewModel.saveLocationEnabled.collectAsState(initial = false)
val context = androidx.compose.ui.platform.LocalContext.current
val locationPermissionLauncher = androidx.activity.compose.rememberLauncherForActivityResult(
androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
val granted = permissions.values.all { it }
if (granted) {
viewModel.setSaveLocation(true)
}
}
// 日志查看器弹窗状态
var showLogViewerDialog by remember { mutableStateOf(false) }
var softwareProcessingExpanded by remember { mutableStateOf(false) }
@@ -513,6 +523,42 @@ fun SettingsScreen(
modifier = Modifier.padding(vertical = 8.dp)
)
SwitchSettingItem(
title = stringResource(R.string.settings_save_location),
description = stringResource(R.string.settings_save_location_description),
checked = saveLocation,
onCheckedChange = { checked ->
if (checked) {
val fineLocation = androidx.core.content.ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == android.content.pm.PackageManager.PERMISSION_GRANTED
val coarseLocation = androidx.core.content.ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (fineLocation || coarseLocation) {
viewModel.setSaveLocation(true)
} else {
locationPermissionLauncher.launch(
arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION
)
)
}
} else {
viewModel.setSaveLocation(false)
}
}
)
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
modifier = Modifier.padding(vertical = 8.dp)
)
QualityLevelSetting(
title = stringResource(R.string.settings_multi_frame_count),
description = stringResource(R.string.settings_multi_frame_count_description),
@@ -0,0 +1,54 @@
package com.hinnka.mycamera.utils
import kotlin.math.*
/**
* 坐标转换工具类
* WGS-84: 国际标准,GPS 原始坐标
* GCJ-02: 中国国测局标准,又称火星坐标系
*/
object CoordinateConverter {
private const val a = 6378245.0
private const val ee = 0.00669342162296594323
/**
* WGS-84 转 GCJ-02
*/
fun wgs84ToGcj02(lat: Double, lon: Double): DoubleArray {
if (outOfChina(lat, lon)) {
return doubleArrayOf(lat, lon)
}
var dLat = transformLat(lon - 105.0, lat - 35.0)
var dLon = transformLon(lon - 105.0, lat - 35.0)
val radLat = lat / 180.0 * PI
var magic = sin(radLat)
magic = 1 - ee * magic * magic
val sqrtMagic = sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI)
dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * PI)
val mgLat = lat + dLat
val mgLon = lon + dLon
return doubleArrayOf(mgLat, mgLon)
}
private fun outOfChina(lat: Double, lon: Double): Boolean {
return lon < 72.004 || lon > 137.8347 || lat < 0.8293 || lat > 55.8271
}
private fun transformLat(x: Double, y: Double): Double {
var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * PI) + 20.0 * sin(2.0 * x * PI)) * 2.0 / 3.0
ret += (20.0 * sin(y * PI) + 40.0 * sin(y / 3.0 * PI)) * 2.0 / 3.0
ret += (160.0 * sin(y / 12.0 * PI) + 320 * sin(y * PI / 30.0)) * 2.0 / 3.0
return ret
}
private fun transformLon(x: Double, y: Double): Double {
var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * PI) + 20.0 * sin(2.0 * x * PI)) * 2.0 / 3.0
ret += (20.0 * sin(x * PI) + 40.0 * sin(x / 3.0 * PI)) * 2.0 / 3.0
ret += (150.0 * sin(x / 12.0 * PI) + 300.0 * sin(x / 30.0 * PI)) * 2.0 / 3.0
return ret
}
}
@@ -0,0 +1,62 @@
package com.hinnka.mycamera.utils
import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import com.hinnka.mycamera.utils.PLog
class LocationManager(private val context: Context) {
private val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private var currentLocation: Location? = null
@SuppressLint("MissingPermission")
fun updateLocation() {
if (!hasLocationPermission()) {
return
}
try {
val providers = locationManager.getProviders(true)
var bestLocation: Location? = null
for (provider in providers) {
val l = locationManager.getLastKnownLocation(provider) ?: continue
if (bestLocation == null || l.accuracy < bestLocation.accuracy) {
bestLocation = l
}
}
currentLocation = bestLocation
} catch (e: Exception) {
PLog.e(TAG, "Failed to get last known location", e)
}
}
fun getCurrentLocation(): Location? {
updateLocation()
val location = currentLocation ?: return null
if (DeviceUtil.isChinaFlavor) {
val converted = CoordinateConverter.wgs84ToGcj02(location.latitude, location.longitude)
location.latitude = converted[0]
location.longitude = converted[1]
}
return location
}
private fun hasLocationPermission(): Boolean {
val fineLocation = androidx.core.content.ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_FINE_LOCATION
) == android.content.pm.PackageManager.PERMISSION_GRANTED
val coarseLocation = androidx.core.content.ContextCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) == android.content.pm.PackageManager.PERMISSION_GRANTED
return fineLocation || coarseLocation
}
companion object {
private const val TAG = "LocationManager"
}
}
@@ -68,6 +68,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// 震动辅助类
private val vibrationHelper = VibrationHelper(application)
private val locationManager = LocationManager(application)
val state: StateFlow<CameraState> = cameraController.state
val livePhotoRecorder get() = cameraController.livePhotoRecorder
@@ -137,6 +139,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val photoQuality: Flow<Int> = userPreferencesRepository.userPreferences.map { it.photoQuality }
val defaultFocalLength: Flow<Float> = userPreferencesRepository.userPreferences.map { it.defaultFocalLength }
val userPreferences: StateFlow<com.hinnka.mycamera.data.UserPreferences> = userPreferencesRepository.userPreferences
.stateIn(viewModelScope, SharingStarted.Eagerly, com.hinnka.mycamera.data.UserPreferences())
val useMultiFrame: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.useMultiFrame }
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
@@ -192,6 +196,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val widgetTheme: StateFlow<com.hinnka.mycamera.data.WidgetTheme> = userPreferencesRepository.userPreferences
.map { it.widgetTheme }
.stateIn(viewModelScope, SharingStarted.Eagerly, com.hinnka.mycamera.data.WidgetTheme.FOLLOW_SYSTEM)
val saveLocationEnabled: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.saveLocation }
// 软件处理参数 Flow
val sharpening: Flow<Float> = userPreferencesRepository.userPreferences.map { it.sharpening }
@@ -434,10 +439,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
/**
* 拍照(带延时拍摄支持)
*/
fun capture() {
if (userPreferences.value.saveLocation) {
val location = locationManager.getCurrentLocation()
cameraController.setLocation(location?.latitude, location?.longitude)
} else {
cameraController.setLocation(null, null)
}
val timerSeconds = state.value.timerSeconds
// 检查 VIP 权限
@@ -799,6 +808,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
fun setSaveLocation(enabled: Boolean) {
viewModelScope.launch {
userPreferencesRepository.saveSaveLocation(enabled)
}
}
/**
* 设置是否启用 P010
*/
@@ -1404,8 +1419,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
ratio = aspectRatio,
rotation = rotation,
deviceModel = captureInfo.model,
brand = captureInfo.make.replaceFirstChar { it.uppercase() },
brand = captureInfo.make,
dateTaken = captureInfo.captureTime,
latitude = captureInfo.latitude,
longitude = captureInfo.longitude,
altitude = captureInfo.altitude,
iso = captureInfo.iso,
shutterSpeed = captureInfo.formatExposureTime(),
focalLength = captureInfo.formatFocalLength(),
@@ -1523,8 +1541,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
ratio = aspectRatio,
rotation = rotation,
deviceModel = captureInfo.model,
brand = captureInfo.make.replaceFirstChar { it.uppercase() },
brand = captureInfo.make,
dateTaken = captureInfo.captureTime,
latitude = captureInfo.latitude,
longitude = captureInfo.longitude,
altitude = captureInfo.altitude,
iso = captureInfo.iso,
shutterSpeed = captureInfo.formatExposureTime(),
focalLength = captureInfo.formatFocalLength(),
@@ -1630,8 +1651,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
ratio = aspectRatio,
rotation = rotation,
deviceModel = captureInfo.model,
brand = captureInfo.make.replaceFirstChar { it.uppercase() },
brand = captureInfo.make,
dateTaken = captureInfo.captureTime,
latitude = captureInfo.latitude,
longitude = captureInfo.longitude,
altitude = captureInfo.altitude,
iso = captureInfo.iso,
shutterSpeed = captureInfo.formatExposureTime(),
focalLength = captureInfo.formatFocalLength(),
+2
View File
@@ -142,6 +142,8 @@
<string name="settings_volume_key_action_zoom">焦距切换</string>
<string name="settings_auto_save">拍摄后自动保存</string>
<string name="settings_auto_save_description">拍摄后自动保存照片,否则需要手动确认</string>
<string name="settings_save_location">保存地理位置</string>
<string name="settings_save_location_description">开启后在照片 EXIF 信息中记录经纬度</string>
<string name="settings_nr_level">降噪等级</string>
<string name="settings_nr_level_description">调整系统硬件降噪模式。“关闭”常用于配合软件算法以获得更多细节。</string>
<string name="settings_nr_level_off">关闭</string>
+2
View File
@@ -144,6 +144,8 @@
<string name="settings_volume_key_action_zoom">Focal Switch</string>
<string name="settings_auto_save">Auto Save</string>
<string name="settings_auto_save_description">Automatically save photos after capture</string>
<string name="settings_save_location">Save Location</string>
<string name="settings_save_location_description">Save location info (GPS) in photo metadata</string>
<string name="settings_nr_level">Noise Reduction Level</string>
<string name="settings_nr_level_description">Adjust the hardware noise reduction mode. "Off" helps preserve details when using software processing.</string>
<string name="settings_nr_level_off">Off</string>