kotlin+gps
时间: 2023-12-22 19:29:05 浏览: 128
3、使用 Kotlin 进行高级 Android 开发(Codelab).pdf
以下是使用Kotlin实现系统GPS位置信息变化监听的示例代码:
```kotlin
import android.Manifest
import android.content.pm.PackageManager
import android.location.Location
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
class MainActivity : AppCompatActivity() {
private val LOCATION_PERMISSION_REQUEST_CODE = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 检查定位权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)
} else {
startLocationUpdates()
}
}
private fun startLocationUpdates() {
// 创建LocationListener
val locationListener = object : android.location.LocationListener {
override fun onLocationChanged(location: Location) {
// 处理位置变化
// 在这里可以根据需要进行相应的操作,比如更新UI或发送位置信息到服务器等
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
override fun onProviderEnabled(provider: String?) {}
override fun onProviderDisabled(provider: String?) {}
}
// 注册LocationListener
val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0f, locationListener)
// 添加LifecycleObserver,当Activity处于非活动状态时停止位置更新
lifecycle.addObserver(object : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
locationManager.removeUpdates(locationListener)
}
})
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates()
}
}
}
```
请注意,上述代码中的`R.layout.activity_main`是一个占位符,你需要将其替换为你自己的布局文件。
阅读全文