How to get initial location with LocationManager?

后端 未结 1 425
孤城傲影
孤城傲影 2020-12-21 09:32

I\'ve been getting current location with GoogleApiClient up until now but I\'ve just noticed that it\'s much simpler to do it with LocationManager

相关标签:
1条回答
  • 2020-12-21 10:06

    Use the following method to get the Location object:

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    
            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    
            Log.v(TAG, "isGPSEnabled =" + isGPSEnabled);
    
            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            Log.v(TAG, "isNetworkEnabled =" + isNetworkEnabled);
    
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d(TAG, "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled && location == null) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d(TAG, "GPS Enabled");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Location Not Found");
        }
        return location;
    }
    

    For more information on the method getLastKnownLocation, please refer to the docs.

    0 讨论(0)
提交回复
热议问题