Android: Check if Location Services Enabled using Fused Location Provider

前端 未结 5 674
囚心锁ツ
囚心锁ツ 2021-01-31 10:59

According to the Android documentation:

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework t

5条回答
  •  庸人自扰
    2021-01-31 11:18

    If use FusedLocationProviderClient, first we need check Location is enabled in device.

    private fun isLocationEnabled(): Boolean {
        val activity: Activity? = this.activity
        val lm = activity?.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
        if (lm != null) {
            val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                lm.isLocationEnabled
            } else {
                lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
                        || lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
            }
            Log.d(TAG, "isLocationServiceEnabled", enabled)
            return enabled
        }
        return false
    }
    

    And then, check LocationSettings.

    val request = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    
    val settingRequest = LocationSettingsRequest.Builder()
            .addLocationRequest(request)
            .build()
    // check Location settings for the request
    LocationServices.getSettingsClient(context)
            .checkLocationSettings(settingRequest)
            .addOnSuccessListener {
                // OK!!
                // fusedLocationProviderClient.requestLocationUpdates
            }
            .addOnFailureListener {  exception ->
                if (exception  is ResolvableApiException) {
                    try {
                        exception.startResolutionForResult(activity, RC_LOCATION_SETTINGS)
                    } catch (ex: IntentSender.SendIntentException) {
                        // ignore
                    }
                } else {
                    // handle other errors
                    showFusedDisabledDialog()
                }
            }
    

    also, please check below link.

    https://developer.android.com/training/location/change-location-settings

提交回复
热议问题