获取位置android Kotlin
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取位置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
被调用并提供更新。
此外,你已经在mylocation
中定义了GetUserLocation
,所以它也超出了范围并进一步杀死了任何机会或者你得到了更新。
你还没有展示外部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) {}
}
我知道现在已经很晚了,但现在Google已经让它变得更简单了。在开发人员网站中,它表示您需要创建客户端:
private lateinit var fusedLocationClient: FusedLocationProviderClient
然后onCreate获取提供者:
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
最后,要获取您的最后一个位置,请致电:
//Don't forget to ask for permissions for ACCESS_COARSE_LOCATION
//and ACCESS_FINE_LOCATION
@SuppressLint("MissingPermission")
private fun obtieneLocalizacion(){
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
latitude = location?.latitude
longitude = location?.longitude
}
}
*使用此实现测试位置(在您的应用程序gradle文件中设置)
implementation 'com.google.android.gms:play-services-location:15.0.1'
有关详细信息,请查看此链接:
我想帮助那些试图从头开始获取位置的人。以下是参考:Kotlin Get Current Location
代码将首先检查设备中的位置是打开还是关闭,然后将获取纬度和经度,并将不断更新它。
在build.gradle(Module:app)文件中放这个
compile 'com.google.android.gms:play-services:11.8.0'
activity_main.xml代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Latitude:"
android:textSize="18sp" />
<TextView
android:id="@+id/latitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/latitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@+id/latitude"
android:textSize="16sp" />
<TextView
android:id="@+id/longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Longitude:"
android:layout_marginTop="24dp"
android:textSize="18sp" />
<TextView
android:id="@+id/longitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/longitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@+id/longitude"
android:textSize="16sp"/>
</RelativeLayout>
我激活了。
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.model.LatLng
class MainActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private var mLatitudeTextView: TextView? = null
private var mLongitudeTextView: TextView? = null
private var mGoogleApiClient: GoogleApiClient? = null
private var mLocation: Location? = null
private var mLocationManager: LocationManager? = null
private var mLocationRequest: LocationRequest? = null
private val listener: com.google.android.gms.location.LocationListener? = null
private val UPDATE_INTERVAL = (2 * 1000).toLong() /* 10 secs */
private val FASTEST_INTERVAL: Long = 2000 /* 2 sec */
private var locationManager: LocationManager? = null
private val isLocationEnabled: Boolean
get() {
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mLatitudeTextView = findViewById(R.id.latitude_textview) as TextView
mLongitudeTextView = findViewById(R.id.longitude_textview) as TextView
mGoogleApiClient = GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build()
mLocationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
Log.d("gggg","uooo");
checkLocation() //check whether location service is enable or not in your phone
}
@SuppressLint("MissingPermission")
override fun onConnected(p0: Bundle?) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSI以上是关于获取位置android Kotlin的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin Android Studio - setContenView - 绑定(片段)
Android 上的 Kotlin:如何在片段中使用数据库中的 LiveData?