Search code examples
androidgoogle-mapsandroid-fusedlocation

android: improving Find Current Location


I want find current user location on android.

I use these code:

mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000); // Update location every second
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            mMap.setMyLocationEnabled( true );
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation != null) {
                lat = String.valueOf(mLastLocation.getLatitude());
                lon = String.valueOf(mLastLocation.getLongitude());

            }
            firstLoction();
        }
        else
        {
            Toast.makeText(this, "Not promisseion", Toast.LENGTH_SHORT).show();
        }

It works with some network (Data mobile). but not works for all location. (Also It works with GPS)

Can I do more thing to handle networks better?


Solution

  • Make your activity implementing LocationListener interface and then exploit FusedLocationApi, that take care of all available providers (e.g. GPS, Network).

    In your onConnected method you need to proceed as follows:

    @Override
    public void onConnected(Bundle connectionHint) {
        LocationRequest request = new LocationRequest();
        request.setInterval(10000);
        request.setFastestInterval(5000);
        request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // using fused location api, taking care of all
        // available providers (e.g. GPS, NETWORK)
        // here do not forget to check for available LOCATION
        // permission before asking for updates
        LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, request, this);
    }
    

    Since your Activity implements LocationListener interface, you will receive updates in onLocationChanged method.

    @Override
    public void onLocationChanged(Location location) {
        // this method is defined by LocationListener interface
        // here you will receive location updates based
        // on fused location api        
    }
    

    Refer here for additional details on how to improve code for reducing battery drain.

    I see you are using GoogleMap in your activity. It is possible also to get current location directly from GoogleMap object by using its method setOnMyLocationChangeListener. Unfortunately this method is now deprecated, so the recommendation is to use FusedLocationProviderApi.