获取当前位置 Android Kotlin

Get current location Android Kotlin

我尝试在我的应用程序中使用 GM API 获取当前位置(使用 Android Studio)。但是,如果我单击触发 getLocation() 功能的按钮,我总是会在 catch{} 块中结束,我不知道为什么。 我的移动设备已连接进行测试。

这是 getLocation() 函数:

fun getLocation() {

    var locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?

    var locationListener = object : LocationListener{
        override fun onLocationChanged(location: Location?) {
            var latitute = location!!.latitude
            var longitute = location!!.longitude

            Log.i("test", "Latitute: $latitute ; Longitute: $longitute")

        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
        }

        override fun onProviderEnabled(provider: String?) {
        }

        override fun onProviderDisabled(provider: String?) {
        }

    }

    try {
        locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener)
    } catch (ex:SecurityException) {
        Toast.makeText(applicationContext, "Fehler bei der Erfassung!", Toast.LENGTH_SHORT).show()
    }
}

这是 onCreate 函数:

class CurrentLocationActivity : AppCompatActivity() {


lateinit var mapFragment : SupportMapFragment
lateinit var googleMap : GoogleMap

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_current_location)

    //Karte erstellen
    mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(OnMapReadyCallback {
        googleMap = it
    })



    //OnClickListener um Location zu speichern
    btnGetCurrentLocation.setOnClickListener {
        getLocation()
    }
}

如果未授予位置权限,LocationManager 将抛出 SecurityException。

可以找到有关向您的应用添加位置权限的信息here

尝试如下

步骤 1. 穿上你的 AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com....">

    <!-- This line -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application ... />

</manifest>

第 2 步将其放在您的位置请求上方

import android.Manifest
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat

...

fun getLocation() {

    ...

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
        return
    }
    locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == PERMISSION_REQUEST_ACCESS_FINE_LOCATION) {
        when (grantResults[0]) {
            PackageManager.PERMISSION_GRANTED -> getLocation()
            PackageManager.PERMISSION_DENIED -> //Tell to user the need of grant permission
        }
    }
}

companion object {
    private const val PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 100
}