获取位置Android Kotlin

我最近添加了获取位置功能。 当我尝试显示经度和纬度时,它返回零。

这是我的LocationListener类:

inner class MylocationListener: LocationListener { constructor():super(){ mylocation= Location("me") mylocation!!.longitude mylocation!!.latitude } override fun onLocationChanged(location: Location?) { mylocation=location } override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {} override fun onProviderEnabled(p0: String?) {} override fun onProviderDisabled(p0: String?) {} } 

而这个我的GetUserLocation函数:

 fun GetUserLocation(){ var mylocation= MylocationListener() var locationManager=getSystemService(Context.LOCATION_SERVICE) as LocationManager locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0.1f,mylocation) } 

而这个函数返回我的经度和纬度:

 fun getLoction (view: View){ prgDialog!!.show(); GetUserLocation() button.setTextColor(getResources().getColor(R.color.green)); textView.text = mylocation!!.latitude.toFloat().toString() Toast.makeText(this, mylocation!!.latitude.toFloat().toString(), Toast.LENGTH_LONG).show() Toast.makeText(this, mylocation!!.longitude.toFloat().toString(), Toast.LENGTH_LONG).show() prgDialog!!.hide() } 

GetUserLocation返回时, locationManager超出范围,可能会被销毁,从而阻止onLocationChanged被调用并提供更新。

另外,你已经在GetUserLocation定义了mylocation ,所以它也超出了范围,进一步杀死了任何机会或者获得更新。

你没有显示在何处以及如何声明外部mylocation (在GetUserLocation之外),但是它是如何声明的,它被GetUserLocation内部映射。 所以你没有太多。

这里是你如何做的一个例子。 ( thetext变量在布局xml中定义,并通过Kotlin扩展进行访问。)

 // in the android manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> // allow these through Appliation Manager if necessary // inside a basic activity private var locationManager : LocationManager? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) // Create persistent LocationManager reference locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?; fab.setOnClickListener { view -> try { // Request location updates locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener); } catch(ex: SecurityException) { Log.d("myTag", "Security Exception, no location available"); } } } //define the listener private val locationListener: LocationListener = object : LocationListener { override fun onLocationChanged(location: Location) { thetext.setText("" + location.longitude + ":" + location.latitude); } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {} } 
Interesting Posts