完整实现:在 Android Fragment 中使用定位功能
下面提供完整的代码实现,包括定位工具类、Fragment 实现以及 ViewModel 整合方案。
1. 添加权限声明
在 AndroidManifest.xml
中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 如果需要后台定位,Android 10+ 需要添加 -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
1. 定位工具类 (NativeLocationHelper.kt)
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
}
}
2. ViewModel (LocationViewModel.kt)
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()
}
}
3. Fragment 实现 (LocationFragment.kt)
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()
}
}
4. 布局文件 (fragment_location.xml)
<?xml version="1.0" encoding="utf-8"?>
<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>
5. 使用说明
-
初始化:
- 在 Fragment 的
onViewCreated
中初始化 ViewModel 和定位工具 - 自动检查权限并开始定位
- 在 Fragment 的
-
权限处理:
- 使用新的 Activity Result API 处理权限请求
- 优雅处理权限被拒绝的情况
-
位置更新:
- 通过 LiveData 观察位置变化
- 自动更新 UI 显示位置信息
-
生命周期管理:
- 在
onDestroyView
中停止位置更新 - 使用
viewLifecycleOwner
确保安全更新 UI
- 在
-
错误处理:
- 捕获并显示定位错误
- 显示加载状态
6. 高级功能扩展
如需添加更多功能,可以考虑:
- 地理围栏:在特定位置设置提醒
- 位置轨迹记录:持续记录用户移动路径
- 位置过滤:使用低通滤波算法平滑位置数据
- 能耗优化:根据应用状态调整定位精度
这个完整实现提供了现代化的 Android 定位解决方案,遵循了最新的 Jetpack 组件和 Kotlin 协程最佳实践。