如何在 Kotlin 中获取 API 23 的位置?

How to get the location for API 23 in Kotlin?

项目 API 要求:API 23+. 提供位置详细信息,它们适用于 API 26 岁以上,但不适用于 API 23 岁。

我刚看完这篇文章

然而,尝试了不同的解决方案,仍然没有结果。可能是什么原因?

class TabFragment1 : Fragment() {
    var lat: Double = 0.0
    var long: Double = 0.0

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    activity?.let {}
}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    super.onCreate(savedInstanceState)

    val v: View = inflater.inflate(R.layout.fragment_tab1, container, false)
    val spinner1 = v.spinnerCategory as Spinner
    val buttonSearch = v.buttonSearch as Button

    // Search button
    buttonSearch.setOnClickListener {

        // GET LOCATION
        val g = this.activity?.let {
                it1 -> geo(it1)
        }

        if (g != null) {
            activity?.let {

                if (g[0] == 0.0 && g[1] == 0.0) {

                    println(" g result ${g[0]}")
                    alert(getString(R.string.error_no_location))

                    // Request location updates
                    if (ActivityCompat.checkSelfPermission(it, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                        var permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)

                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                            permissions = permissions.plus(android.Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                        }
                        ActivityCompat.requestPermissions(context as Activity, permissions, 0)
                    }
                } else {

                    // segue
                    val intent = Intent(it, PostTableViewActivity::class.java)
                    intent.putExtra("long", g[1].toString())
                    intent.putExtra("lat", g[0].toString())
                    startActivity(intent)
                }
            }
        } else {
            alert("TurnOn Geolocation!")
        }
    }
    return v
}

geo.kt:

fun geo(context: Context): DoubleArray? {

    val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    val providers: List<String> = locationManager.getProviders(true)
    var location: Location? = null

    for (i in providers.size - 1 downTo 0) {

        if (ActivityCompat.checkSelfPermission(context.applicationContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context.applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                println(" NO PERMS?? ")
            var permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                permissions = permissions.plus(android.Manifest.permission.ACCESS_BACKGROUND_LOCATION)
            }
            ActivityCompat.requestPermissions(context as Activity, permissions,0)
            return null
        }

        location = locationManager.getLastKnownLocation(providers[i])
        if (location != null)
            break
    }

    val gps = DoubleArray(2)
    if (location != null) {
        println(" GEO FUNC has lat, long - ?? ${location.latitude}, ${location.longitude}")

        gps[0] = location.latitude
        gps[1] = location.longitude
    }
    return gps
}

API 23 控制台结果:

I/System.out: g result 0.0

API 26 控制台结果:

I/System.out: GEO FUNC has lat, long - ?? 37.421998333333335, -122.08400000000002

清单:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />

仅适用于 API == 23

1. build.gradle

implementation 'com.google.android.gms:play-services-location:17.1.0'

2。权限

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

3。上下文 -> gps[纬度,经度]

private fun requestCurrentLocation(context: Context): DoubleArray? {
    val fusedLocationClient: FusedLocationProviderClient by lazy {
        LocationServices.getFusedLocationProviderClient(context)
    }
    var cancellationTokenSource = CancellationTokenSource()
    val gps = DoubleArray(2)

    // Check Fine permission
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        // Main code
        val currentLocationTask: Task<Location> = fusedLocationClient.getCurrentLocation(
            PRIORITY_HIGH_ACCURACY,
            cancellationTokenSource.token
        )

        currentLocationTask.addOnCompleteListener { task: Task<Location> ->
            val result = if (task.isSuccessful) {
                val result: Location = task.result
                gps[0] = result.latitude
                gps[1] = result.longitude
                "Location (success): ${result.latitude}, ${result.longitude}"
            } else {
                val exception = task.exception
                "Location (failure): $exception"
            }

            println("getCurrentLocation() result: $result")
        }
    } else {
        // Request fine location permission (full code below).
    }
    return gps
}