Android

How to fetch current location using Fused Location Provider Client Api in Android

How to fetch current location using Fused Location Provider Client Api in Android
Photo by Christine Roy on Unsplash Photo by Christine Roy on Unsplash

Fetching user current location is now the most basic trend in Android apps because this helps the app to display the custom preference based on their local preference.So now we will see “How to fetch current location using Fused Location Provider Client Api in Android.”

For fetching the user’s current location Google came up with https://developer.android.com/training/location/receive-location-updates

But the demo and approaches are not working perfectly and seems to buggy. That is why I tried to make some changes in the approach and created one demo which utilizes latest Fused Location Provider Client Api to determine latitude and longitude.

If you are interested in how earlier Api which was deprecated Fused Location Provider Api works then check my previous post http://askfortricks.com/2016/03/get-location-android-using-fused-location-provider-api/

So lets start we will see short code snippets which will make it easy for us to understand the code.

Contents

What we will do:

  1. First Check Location enabled or not
  2. Check permission for location is granted or not.
  3. If user allow permission for location then display the location as a marker in Map.

So lets start now:

Step 1: Check if GPS/Network Provider Enabled

We have written the logic in SplashActivity.java :

FIrst when app launch we check if the location is enabled or not on the device. If enabled then we go to MainActivity.java otherwise we show a dialog to the user to enable the location

LocationManager mListener = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if(mListener != null){
            isGPSLocation = mListener.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkLocation = mListener.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            Log.e("gps, network", String.valueOf(isGPSLocation + "," + isNetworkLocation));
        }
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                if(isGPSLocation){
                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    intent.putExtra("provider", LocationManager.GPS_PROVIDER);
                    startActivity(intent);
                    finish();
                }else if(isNetworkLocation){
                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    intent.putExtra("provider", LocationManager.NETWORK_PROVIDER);
                    startActivity(intent);
                    finish();
                }else{
                    //Device location is not set
                    PermissionUtils.LocationSettingDialog.newInstance().show(getSupportFragmentManager(), "Setting");
                
            }
        }, 1500);

 

 

Step 2: Check Runtime permission

If permission for location is not granted (on first launch) then we have to allow the app to access the device location:

 private void checkMyPermissionLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //Permission Check
            PermissionUtils.requestPermission(this);
        } else {
            //If you're authorized, start setting your location
            initGoogleMapLocation();
        }
    }

Step 3: Adding SupportMapFragment (optional)

In this demo we have included SupportMapFragment . We have initialized Google Map and once the current location is determined then we display the current location as a marker on our location.

For enabling Map first ,you have to create a new app on https://console.cloud.google.com and have to go to Enabled APIs and services to enable Geolocation API

Then create a key and upload your development machine SHA1 key.

Note : To know how to create SHA-1 from Android Studio (debug mode) 

use Step 10 from :

http://askfortricks.com/2016/07/implement-firebase-clould-messaging-android/

We will initialize as below:

SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                /*if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    return;
                }*/
                mMap = googleMap;
                mMap.getUiSettings().setZoomControlsEnabled(true);
                //mMap.setMyLocationEnabled(true);
            }
        });

Step 4 : Register a Location callback

How to fetch current location using Fused Location Provider Client Api in Android
How to fetch current location using Fused Location Provider Client Api in Android

In location callback we will receive the latitude and longitude which we will need to determine the location. On callback we will animate the marker and display our current location.

In log we can also print the latitude and longitude.

mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult result) {
                super.onLocationResult(result);
                //mCurrentLocation = locationResult.getLastLocation();
                mCurrentLocation = result.getLocations().get(0);


                if(mCurrentLocation!=null)
                {
                    Log.e("Location(Lat)==",""+mCurrentLocation.getLatitude());
                    Log.e("Location(Long)==",""+mCurrentLocation.getLongitude());
                }

We have just taken Map for demo purpose. You can comment out the Google Map related code and still you can find latitude and longitude.

Final Output will look something like this:

 

Complete Source code available on https://github.com/askfortricks/FusedLocationProviderClient

Thus ,Fused Location Provider Client is latest Android api which utilizes Google play services to determine current user location and if you want to dive deep about benefits of Fused Location Provider then read my previous post  http://askfortricks.com/2016/03/get-location-android-using-fused-location-provider-api/

So friends, I hope we will move to Fused Location Provider Client  to determine location as Location Manager Services are deprecated and please comment about any issues,suggestions or help.

Feeling glad to receive your comment