在物理设备中,呼叫花费太多时间。但是在avd中,它运行得很好。我在redmi note 4和zuk z2 plus中测试了此代码。两个设备的位置都在HIGH_ACCURACY
上设置。我想快速获取位置。但是执行需要太多时间。
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0f,wcLoactionListener)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0f,wcLoactionListener)
但是如果我删除了这一行
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0f,wcLoactionListener)
然后onLocationChanged()不调用。
这是我的位置监听器
class MyListener:LocationListener {
override fun onLocationChanged(location: Location?) {
Log.d("Loc","*************************************************** "+ location)
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
}
override fun onProviderEnabled(provider: String?) {
}
override fun onProviderDisabled(provider: String?) {
}
}
主要活动:-
class MainActivity : AppCompatActivity() {
val LOCATION_CODE = 212
private lateinit var locationManager: LocationManager
private lateinit var cwcLoactionListener:MyListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
cwcLoactionListener = MyListener()
checkLocationPermission()
}
@SuppressLint("MissingPermission")
fun fechLOc(){
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0f,cwcLoactionListener)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,500,0f,cwcLoactionListener)
}
private fun checkLocationPermission() {
if(Build.VERSION.SDK_INT>=23){
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED ){
requestPermissions(arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_CODE)
return
}
}
fechLOc()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
LOCATION_CODE->{
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"Accept this permission", Toast.LENGTH_LONG).show()
}else{
fechLOc()
}
}
else ->{
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
}
}
清单
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>