Get user's current latitude-longitude and convert them in full address using FusedLocation API

The Fused Location Provider intelligently manages the underlying location technology and gives us the best location according to our needs.
WHY USE
We could choose one of the location providers (network or GPS) and request location updates or set up proximity alert. But there were two main issues with this approach:
1. In case we need to define precise location, we had to switch between network and GPS location providers (as GPS doesn’t work indoors).
2. Proximity alerts were used to notify a user about proximity to a location, and this took its toll on the battery life.
ADVANTAGE OF USING THIS API
1. Simple APIs: Lets us specify high-level needs like “high accuracy” or “low power”, instead of having to worry about location providers.
2. Immediately available: Gives our apps immediate access to the best, most recent location.
3. Power-efficiency: Minimizes out app’s use of power. Based on all incoming location requests and available sensors, fused location provider chooses the most efficient way to meet those needs.
4. Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
Note : Make sure Google Play services is properly installed and working in our device. Please don’t test this location api in emulator because this api is not working in the emulator.
STEP -1 :  create main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:lib="http://schemas.android.com/apk/res-auto"
    android:background="#10000000">

    

    <TextView
        android:id="@+id/lblLocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="15dp"
        android:textColor="#fff"
        android:textSize="@dimen/abc_action_bar_content_inset_material"
        android:background="@android:color/transparent"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:shadowColor="@color/text_shadow"
        android:shadowDx="1"
        android:shadowDy="1"
        android:shadowRadius="2"
        />
</RelativeLayout>

STEP -2 :  Add dependency in build.gradle file
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.google.android.gms:play-services:8.3.0'
}


STEP -3 :  Create MainActivity.java

package com.sample.foo.simplewidget;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.os.Handler;
import java.util.logging.LogRecord;


/**
 * Created by C.limbachiya on 1/1/2016.
 */
public class MainActivity extends Activity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

    // UI elements
    private TextView lblLocation;
  
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private static Location mLastLocation;

    // Google client to interact with Google API
    private static GoogleApiClient mGoogleApiClient;
    FusedLocationProviderApi fusedLocationProviderApi;

    LocationRequest mLocationRequest;
    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 10000; // 60 sec
    private static int FATEST_INTERVAL = 5000; // 10 sec
    private static int SPLASH_TIME_OUT = 3000;
    protected PowerManager.WakeLock mWakeLock;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.sharing_view);

        /* This code together with the one in onDestroy()
         * will make the screen be always on until this Activity gets destroyed. */
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        this.mWakeLock.acquire();

        lblLocation = (TextView) findViewById(R.id.lblLocation);

        lblLocation.setVisibility(View.GONE);

             
        new Handler().postDelayed(new Runnable() {


            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity

                createLocationRequest();

                fusedLocationProviderApi = LocationServices.FusedLocationApi;
                mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                        .addApi(LocationServices.API)
                        .addConnectionCallbacks(MainActivity.this)
                        .addOnConnectionFailedListener(MainActivity.this)
                        .build();
                if (mGoogleApiClient != null) {
                  
                    mGoogleApiClient.connect();
                }
            }
        }, SPLASH_TIME_OUT);

    }

    public void createLocationRequest() {
  
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(null != mWakeLock)
            this.mWakeLock.release();

    }

    @Override
    protected void onStop() {
        super.onStop();

        if (null != mGoogleApiClient) {

           
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);

            if(mGoogleApiClient.isConnected())
                mGoogleApiClient.disconnect();

          
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        
        fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(getApplicationContext(), "onConnectionSuspended", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(getApplicationContext(), "onConnectionFailed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {
            Location mLastLocation = LocationServices.FusedLocationApi
                    .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {

            double latitude = location.getLatitude();
            double longitude = location.getLongitude();

            //Toast.makeText(getApplicationContext(), "latitude : "+latitude+" longitude : "+longitude, Toast.LENGTH_SHORT).show();

            Geocoder geocoder;
            List<Address> addresses = null;
            geocoder = new Geocoder(this, Locale.getDefault());

            try {
                addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
            } catch (IOException e) {
                e.printStackTrace();
            }

            String address = null;
            String city = null;
            String state = null;
            String country = null;
            //String postalCode = null;
            //String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

            if (null != addresses) {

                if (null == addresses.get(0).getAddressLine(0)) {
                    address = "unknown";
                } else {
                    address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                }

                if (null == addresses.get(0).getLocality()) {
                    city = "unknown";
                } else {
                    city = addresses.get(0).getLocality();
                }

                if (null == addresses.get(0).getAdminArea()) {
                    state = "unknown";
                } else {
                    state = addresses.get(0).getAdminArea();
                }

                if (null == addresses.get(0).getCountryName()) {
                    country = "unknown";
                } else {
                    country = addresses.get(0).getCountryName();
                }

               
                lblLocation.setVisibility(View.VISIBLE);

                lblLocation.setText(
                        "Address : " + address + "\n" +
                                "City : " + city + "\n" +
                                "State : " + state + "\n" +
                                "Country : " + country);

            } else {
                
                lblLocation.setVisibility(View.VISIBLE);
                lblLocation.setText("Your internet connection is too slow! Please Retry");
            }

        } else {
           
            lblLocation.setVisibility(View.VISIBLE);
            lblLocation.setText("Couldn't get the location");
            Toast.makeText(getApplicationContext(), "Couldn't get the location", Toast.LENGTH_SHORT).show();
        }
    }

}


STEP -4 :  Add below permissions in AndroidMenifiest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Also write meta in Application tag in menifiest file
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version">
</meta-data>

Comments