首页 > 解决方案 > 如何获取当前位置?

问题描述

我尝试了一些方法来获取当前用户位置(纬度、经度、..),但没有任何结果。你能帮助我吗?我最后一次尝试使用空位置:

    private void getLocation() throws IOException {
        if (ActivityCompat.checkSelfPermission(MainWindow.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(MainWindow.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        } else {
            Location locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Location locationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Location locationPassive = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

            if (locationGPS != null)
                setCoordinate(locationGPS.getLatitude(), locationGPS.getLongitude());
            else if (locationNetwork != null)
                setCoordinate(locationNetwork.getLatitude(), locationNetwork.getLongitude());
            else if (locationPassive != null)
                setCoordinate(locationPassive.getLatitude(), locationPassive.getLongitude());
            else
                Toast.makeText(this, "Ошибка", Toast.LENGTH_SHORT).show();
        }
    }

    private void setCoordinate(double Latitude, double Longitude) throws IOException {
        latitude = String.valueOf(Latitude);
        longitude = String.valueOf(Longitude);
        coordinate = "Широта: " + latitude + ", долгота: " + longitude;

        geocoder = new Geocoder(this, Locale.getDefault());
        addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
        String state = addresses.get(0).getAdminArea();
    }

标签: androidlocation

解决方案


Try to use fused location provider - https://developers.google.com/location-context/fused-location-provider.

It works really better.


推荐阅读