下面提供完整的代码实现,包括定位工具类、Fragment 实现以及 ViewModel 整合方案。
在 AndroidManifest.xml
中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
import android.Manifest
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
import androidx.core.app.ActivityCompat
class NativeLocationHelper(private val context: Context) {
private val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private var locationListener: LocationListener? = null
interface OnLocationUpdateListener {
fun onLocationUpdate(location: Location)
fun onLocationError(errorMessage: String)
}
fun startLocationUpdates(
minTime: Long,
minDistance: Float,
listener: OnLocationUpdateListener
) {
if (!checkPermissions()) {
listener.onLocationError("Location permissions not granted")
return
}
locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
listener.onLocationUpdate(location)
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {
listener.onLocationError("Location provider disabled")
}
}
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
minTime,
minDistance,
locationListener!!,
Looper.getMainLooper()
)
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
minTime,
minDistance,
locationListener!!,
Looper.getMainLooper()
)
} catch (e: SecurityException) {
listener.onLocationError("SecurityException: ${e.message}")
}
}
fun stopLocationUpdates() {
locationListener?.let {
locationManager.removeUpdates(it)
}
}
fun getLastKnownLocation(): Location? {
if (!checkPermissions()) return null
return try {
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
?: locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
} catch (e: SecurityException) {
null
}
}
private fun checkPermissions(): Boolean {
return ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
}
import android.location.Location
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class LocationViewModel : ViewModel() {
private lateinit var locationHelper: NativeLocationHelper
private val _location = MutableLiveData<Location>()
val location: LiveData<Location> = _location
private val _error = MutableLiveData<String>()
val error: LiveData<String> = _error
private val _isLoading = MutableLiveData<Boolean>()
val isLoading: LiveData<Boolean> = _isLoading
fun initLocationHelper(context: Context) {
locationHelper = NativeLocationHelper(context)
}
fun startLocationUpdates() {
_isLoading.value = true
locationHelper.startLocationUpdates(
10000, // 10秒更新间隔
10f, // 10米最小距离变化
object : NativeLocationHelper.OnLocationUpdateListener {
override fun onLocationUpdate(location: Location) {
_isLoading.postValue(false)
_location.postValue(location)
}
override fun onLocationError(error: String) {
_isLoading.postValue(false)
_error.postValue(error)
}
}
)
}
fun stopLocationUpdates() {
locationHelper.stopLocationUpdates()
}
fun getLastKnownLocation(): Location? {
return locationHelper.getLastKnownLocation()
}
override fun onCleared() {
super.onCleared()
stopLocationUpdates()
}
}
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collect
class LocationFragment : Fragment() {
private val viewModel: LocationViewModel by viewModels()
// 权限请求
private val locationPermissionRequest = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
when {
permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false) -> {
viewModel.startLocationUpdates()
}
permissions.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false) -> {
viewModel.startLocationUpdates()
}
else -> {
Toast.makeText(
requireContext(),
"Location permission denied",
Toast.LENGTH_SHORT
).show()
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.fragment_location, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.initLocationHelper(requireContext())
// 检查权限
if (hasLocationPermission()) {
viewModel.startLocationUpdates()
} else {
requestLocationPermission()
}
setupObservers()
// 尝试获取最后一次已知位置
viewModel.getLastKnownLocation()?.let {
updateLocationUI(it)
}
}
private fun setupObservers() {
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.location.collect { location ->
location?.let { updateLocationUI(it) }
}
}
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.error.collect { error ->
error?.let { showError(it) }
}
}
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
viewModel.isLoading.collect { isLoading ->
// 更新加载状态UI
view?.findViewById<View>(R.id.progressBar)?.visibility =
if (isLoading) View.VISIBLE else View.GONE
}
}
}
private fun hasLocationPermission(): Boolean {
return ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
private fun requestLocationPermission() {
locationPermissionRequest.launch(
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
)
}
private fun updateLocationUI(location: Location) {
view?.findViewById<TextView>(R.id.tvLatitude)?.text =
"Latitude: ${location.latitude}"
view?.findViewById<TextView>(R.id.tvLongitude)?.text =
"Longitude: ${location.longitude}"
view?.findViewById<TextView>(R.id.tvAccuracy)?.text =
"Accuracy: ${location.accuracy} meters"
}
private fun showError(message: String) {
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
view?.findViewById<TextView>(R.id.tvError)?.text = message
}
override fun onDestroyView() {
super.onDestroyView()
viewModel.stopLocationUpdates()
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="gone"/>
<TextView
android:id="@+id/tvLatitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude: -"
android:textSize="18sp"/>
<TextView
android:id="@+id/tvLongitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude: -"
android:textSize="18sp"/>
<TextView
android:id="@+id/tvAccuracy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Accuracy: -"
android:textSize="18sp"/>
<TextView
android:id="@+id/tvError"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/error_color"
android:textSize="16sp"/>
LinearLayout>
初始化:
onViewCreated
中初始化 ViewModel 和定位工具权限处理:
位置更新:
生命周期管理:
onDestroyView
中停止位置更新viewLifecycleOwner
确保安全更新 UI错误处理:
如需添加更多功能,可以考虑:
这个完整实现提供了现代化的 Android 定位解决方案,遵循了最新的 Jetpack 组件和 Kotlin 协程最佳实践。