我尝试获取片段中设备的最后一个已知位置:
清单
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
定义
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var mLocationRequest: LocationRequest
private var location: Location? = null
OnCreate
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context as MainActivity)
mLocationRequest = LocationRequest()
mLocationRequest.interval = 120000
mLocationRequest.fastestInterval = 120000
mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
mLocationRequest.numUpdates = 1
}
请求位置
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
{
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_product_add, container, false)
view.button_add_product.setOnClickListener(this)
view.button_photo.setOnClickListener(this)
if (ContextCompat.checkSelfPermission(view.context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
fusedLocationClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper())
}
else
{
ActivityCompat.requestPermissions(this.context as MainActivity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_LOCATION_PERMISSION)
}
return view
}
获取位置
private val locationCallback: LocationCallback? = object : LocationCallback()
{
override fun onLocationResult(loc: LocationResult?)
{
super.onLocationResult(loc)
val locations = loc?.locations
if (locations != null)
{
val lastLocation = locations[locations.size - 1]
location = lastLocation
product_coordinates.setText("Lat:${location?.latitude} Lon:${location?.longitude}")
fusedLocationClient.removeLocationUpdates(this)
}
}
}
locationCallback中的代码永远不会执行。
我也尝试使用以下代码,但是location
始终是null
:
fusedLocationClient.lastLocation.addOnSuccessListener(context as MainActivity) { location ->
if (location != null) {
product_coordinates.setText("Lat:${location.latitude} Lon:${location.longitude}")
}
}