lat и lon ничего не возвращают из метода getlocation () - PullRequest
0 голосов
/ 25 апреля 2020

я получил разрешения и хочу получить широту и долготу количества из метода getLocation(), моя проблема в том, что LAT и LON имеют десятичное число внутри getLocation(), но когда я использую это значение из getLocation(), они возвращают нуль, как и я хочу использовать в API в WeatherTask нужны лат и долг, но ничего не происходит

class MainActivity : AppCompatActivity() {
    private val locationPermissions = arrayOf(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION)
    private val REQUEST_LOCATION_PERMISSION = 1
    private val TAG = "PermissionDemo"

    lateinit var locationManager: LocationManager
    private var hasGps = false
    private var hasNetwork = false

    private var locationGps: Location? = null
    private var locationNetork: Location? = null

    var LAT = 0.0
    var LON = 0.0
    val API="837f502858a52a78b98b5d7be51d0741"


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

        setupPermissions()
        weatherTask().execute()

    }

    fun getLocation() {

        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        hasNetwork = locationManager.isProviderEnabled(
                LocationManager.NETWORK_PROVIDER
        )
        if (hasGps || hasNetwork) {
            if (hasGps) {
                if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    makeRequest()
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0f, object : @SuppressLint("MissingPermission") LocationListener {
                    override fun onLocationChanged(p0: Location?) {
                        if (p0 != null) {
                            locationGps = p0

                            LAT = locationGps!!.latitude
                            LON = locationGps!!.longitude
                            Log.d("AndroidLocation has gps", "Latitude : " + locationGps!!.latitude)
                            Log.d("AndroidLocation has gps", "longitude : " + locationGps!!.longitude)
                        }
                    }

                    override fun onProviderEnabled(p0: String?) {

                    }

                    override fun onProviderDisabled(p0: String?) {

                    }

                    override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {

                    }

                })

                val localGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                if (localGpsLocation != null) {
                    locationGps = localGpsLocation
                }
            }
            if (hasNetwork) {

                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0f, object : LocationListener {
                    override fun onLocationChanged(p0: Location?) {
                        if (p0 != null) {
                            locationNetork = p0

                            Log.d("AndroidLocation has net", "Latitude : " + locationNetork!!.latitude)
                            Log.d("AndroidLocation has net", "longitude : " + locationNetork!!.longitude)
                        }
                    }

                    override fun onProviderEnabled(p0: String?) {

                    }

                    override fun onProviderDisabled(p0: String?) {

                    }

                    override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {

                    }

                })

                val localNetworkLOcation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                if (localNetworkLOcation != null) {
                    locationNetork = localNetworkLOcation
                }

            }


            if (locationGps != null && locationNetork != null) {
                if (locationGps!!.accuracy > locationNetork!!.accuracy) {

                   LAT =locationNetork!!.latitude
                   LON =locationNetork!!.longitude
                    Log.d("AndroidLocation", "Latitude : " + locationNetork!!.latitude)
                    Log.d("AndroidLocation", "longitude : " + locationNetork!!.longitude)

                } else {

                     LAT =locationGps!!.latitude
                     LON =locationGps!!.longitude
                    Log.d("AndroidLocation", "Latitude : " + locationGps!!.latitude)
                    Log.d("AndroidLocation", "longitude : " + locationGps!!.longitude)
                }
            }


        } else {
            Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show()
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivity(intent)
        }

    }

    private fun setupPermissions() {
        val finePermission = ContextCompat.checkSelfPermission(this,
                ACCESS_FINE_LOCATION)
        val coarsePermission = ContextCompat.checkSelfPermission(this,
                ACCESS_FINE_LOCATION)

        if (finePermission != PackageManager.PERMISSION_GRANTED && coarsePermission != PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "Permission to record denied")
            makeRequest()
        }
    }

    private fun makeRequest() {
        ActivityCompat.requestPermissions(this,
                arrayOf(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION),
                REQUEST_LOCATION_PERMISSION)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {

        when (requestCode) {
            REQUEST_LOCATION_PERMISSION -> {

                if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) {

                    Log.i(TAG, "Permission has been denied by user")
                } else {
                    Log.i(TAG, "Permission has been granted by user")
                }
            }
        }
    }

    inner class weatherTask() : AsyncTask<String, Void, String>() {
        override fun onPreExecute() {
            super.onPreExecute()
            /* Showing the ProgressBar, Making the main design GONE */
            findViewById<ProgressBar>(R.id.loader).visibility = View.VISIBLE
            findViewById<RelativeLayout>(R.id.mainContainer).visibility = View.GONE
            findViewById<TextView>(R.id.errorText).visibility = View.GONE
        }

        override fun doInBackground(vararg params: String?): String? {
            var response: String?
            try {
                Log.i("doIN" ,"LAt is : " +LAT)
                response = URL("https://api.openweathermap.org/data/2.5/weather?lat=$LAT&lon=$LON&units=metric&appid=$API").readText(
                        Charsets.UTF_8
                )
            } catch (e: Exception) {
                response = null
            }
            return response
        }
...