FusedLocation 不会触发 android api <= 21 的 locationcallback
Posted
技术标签:
【中文标题】FusedLocation 不会触发 android api <= 21 的 locationcallback【英文标题】:FusedLocation not trigger locationcallback for android api <= 21 【发布时间】:2020-10-16 22:27:24 【问题描述】:所以我想从设备获取纬度和经度,但是当我在 android Lollipop 或 API 22 上构建我的应用程序时,我没有得到当前的纬度和经度。这是因为android许可还是什么?这是我的代码
我正在使用播放服务位置版本:
实现 'com.google.android.gms:play-services-location:17.0.0'
LocationUser.kt
class LocationUser(context: Context)
private var fusedLocation: FusedLocationProviderClient? = null
private val INTERVAL: Long = 300000
private val FASTEST_INTERVAL: Long = 300000
private val REQUEST_LOCATION_PERMISSION = 1
lateinit var locationRequest: LocationRequest
private lateinit var lastLocation: Location
fun startLocationUpdates(context: Context)
Log.d("LOCATION UPDATE", "started location update")
locationRequest = LocationRequest()
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = INTERVAL
locationRequest.fastestInterval = FASTEST_INTERVAL
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(locationRequest)
val locationSettingsRequest = builder.build()
val settingsClient = LocationServices.getSettingsClient(context)
settingsClient.checkLocationSettings(locationSettingsRequest)
fusedLocation = LocationServices.getFusedLocationProviderClient(context)
if (ActivityCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
context,
android.Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
)
return
fusedLocation!!.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
Log.d("LOCATION UPDATE", "end location update")
fun isPermissionGranted(context: Context): Boolean
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (context.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
)
true
else
ActivityCompat.requestPermissions(
context as Activity, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_LOCATION_PERMISSION
)
false
else
true
private val locationCallback = object : LocationCallback()
override fun onLocationResult(locationResult: LocationResult)
locationResult.lastLocation
onLocationChanged(context, locationResult.lastLocation)
super.onLocationResult(locationResult)
fun onLocationChanged(context: Context, location: Location)
Log.d("UWUWU", "location changed")
lastLocation = location
val geocoder = Geocoder(context, Locale.getDefault())
val latitude = lastLocation.latitude
val longitude = lastLocation.longitude
val sharedPref = SharedPref(context)
Log.d("latitude", latitude.toString())
Log.d("longitude", longitude.toString())
sharedPref.saveStringPref("latitude_user", latitude.toString())
sharedPref.saveStringPref("longitude_user", longitude.toString())
try
val addresses: List<Address> = geocoder.getFromLocation(latitude, longitude, 1)
val namaKota = addresses[0].subAdminArea
val namaKecamatan = addresses[0].locality
sharedPref.saveStringPref("alamat_user", "$namaKecamatan, $namaKota")
catch (e: Exception)
e.localizedMessage
Log.d("UWUWU", "location changed")
在活动中,我这样称呼班级
MainActivity.kt
class MainActivity : AppCompatActivity()
private val REQUEST_LOCATION_PERMISSION = 1
private val REQUESTING_LOCATION_UPDATES_KEY = "requesting_location_update"
private val requestingLocationUpdates = true
val locationUser = LocationUser(this)
@SuppressLint("SimpleDateFormat", "SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
../
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
checkUserGPS()
if(locationUser.isPermissionGranted(this))
locationUser.startLocationUpdates(this)
Log.d("GRANTED ?", locationUser.isPermissionGranted(this).toString())
override fun onCreateOptionsMenu(menu: Menu?): Boolean
menuInflater.inflate(R.menu.menu_setting, menu)
return true
override fun onOptionsItemSelected(item: MenuItem): Boolean
if (item.itemId == R.id.menu_settings)
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
return true
return super.onOptionsItemSelected(item)
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
)
if (requestCode == REQUEST_LOCATION_PERMISSION)
if (grantResults.contains(PackageManager.PERMISSION_GRANTED))
Toast.makeText(this, "permission granted", Toast.LENGTH_SHORT).show()
private fun checkUserGPS()
val dialog = AlertDialog.Builder(this)
dialog.setMessage("GPS tidak aktif, apakah kamu ingin megaktifkannya?")
.setCancelable(false)
.setPositiveButton("iya") _, which ->
startActivityForResult(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 11)
.setNegativeButton("tidak") dialog, _ ->
dialog.cancel()
finish()
.create()
.show()
override fun onResume()
locationUser.startLocationUpdates(this)
super.onResume()
当我看到日志时,我注意到在调用函数 startLocationUpdates 函数时未调用 onLocationChange 函数。这是因为许可还是什么,我正在遭受 *** 并得到这个问题,反之亦然,我注意到同样的事情是 locationcallback 没有被触发
FusedLocationProviderClient requestLocationUpdates doesn't trigger LocationCallBack for API 23 above
我现在很困惑
【问题讨论】:
【参考方案1】:如果至少有一个客户端连接到融合的位置提供程序,它将只维护后台位置。现在只打开定位服务并不能保证存储最后一个已知位置。
一旦第一个客户端连接,它将立即尝试获取位置。如果您的活动是第一个连接的客户端,并且在 onConnected() 中立即调用 getLastLocation(),则可能没有足够的时间让第一个位置到达..
我建议你先启动地图应用,这样至少有一些确认的位置,然后测试你的应用。
【讨论】:
以上是关于FusedLocation 不会触发 android api <= 21 的 locationcallback的主要内容,如果未能解决你的问题,请参考以下文章
Flutter ios 设备不会从 FCM 通知触发 onMessage。实施 APN 时 Sendtodevice 失败
FusedLocation Pending Intent 有时在没有位置的情况下调用
当我在谷歌设置android中关闭和打开位置时,FusedLocation 不起作用