<p>In this article, we will talk about what a fused location provider is and how to use it to get the current location using a sample Android application. We need not explicitly choose either <a href="https://www.seeworldgps.com/">GPS provider</a> or Network location provider, as the “<span style="color: #008000;"><strong>Fused Location Provider</strong></span>” automatically chooses the underlying technology and gives the best location as per the need.</p>
<h3><strong><span style="color: #000080;">Fused Location Provider</span></strong></h3>
<ul>
<li>The fused location provider is one of the location APIs in Google Play services that intelligently combines different signals to provide the location information that your app needs.</li>
<li>It manages the underlying location technologies, such as GPS provider and Wi-Fi, and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power.</li>
<li>It also optimizes the device&#8217;s use of battery power.</li>
</ul>
<h3><strong><span style="color: #000080;">FusedLocationProviderClient</span></strong></h3>
<p class="p1">FusedLocationProviderClient is the main entry point for interacting with the fused location provider. With this, your app no longer needs to manually manage connections to Google Play Services through <strong><span style="color: #008000;">GoogleApiClient</span></strong>.</p>
<p class="p1">Advantages with FusedLocationProviderClient :</p>
<ul class="ul1">
<li class="li1">It takes the complete connection logic under the hood. The user no longer needs to initialize GoogleApiClient nor does he need to manage the connection logic.</li>
<li class="li1">It returns the result as a Task object which is easy to manage and share.</li>
<li class="li1">User need not wait until the connection is established to request for a Location. When requesting for the current location the API call automatically waits until the connection is established thereby minimizing the chances of an IllegalStateException.</li>
</ul>
<p class="p1"><span style="color: #0000ff;"><strong>Note</strong></span> : <strong>It’s recommended to use Google Play services version 11.6.0 or higher, which includes bug fixes for this class.</strong></p>
<p class="p1"><span style="color: #0000ff;"><strong><span style="color: #000080;">getLastLocation()</span> </strong></span>: <span style="color: #000000;">getLastlocation()</span> is one of the method provided by <b><span style="color: #008000;">FusedLocationProviderClient</span> c</b>lass which returns the best most recent location currently available.The precision of the location returned by this call is determined by the permission setting you put in your app manifest.</p>
<p>The getLastLocation() method returns a <strong><span style="color: #008000;">Task</span></strong> that you can use to get a Location object with the latitude and longitude coordinates of a geographic location.</p>
<p class="p1"><strong><span style="color: #0000ff;"><span style="color: #000080;">onMapready()</span>: </span></strong><span style="color: #0000ff;"><span style="color: #000000;">This method is c</span></span><span style="color: #000000;">alled when the map is ready to be used.</span></p>
<p class="p1"><strong><span style="color: #0000ff;"><span style="color: #000080;">OnMapReadyCallback</span>: </span></strong>Callback interface for when the map is ready to be used.</p>
<p>Once an instance of this interface is set on a <strong><span style="color: #008000;">MapFragment</span></strong> or <strong><span style="color: #008000;">MapView</span></strong> object, the <strong><span style="color: #008000;">onMapReady(GoogleMap)</span></strong> method is triggered when the map is ready to be used and provides a non-null instance of <strong><span style="color: #008000;">GoogleMap</span></strong>.</p>
<p>Let&#8217;s create an example that shows how to get the current device location using <strong>FusedLocationProviderClient</strong>.</p>
<h3><span style="color: #000080;"><strong>Creating Android Project</strong></span></h3>
<p>1 . Create a new project <span style="color: #008000;"><strong>GetCurrentLocationOnMap</strong></span> in Android Studio from <span style="color: #008000;"><strong>File ⇒ New Project</strong></span> and fill the project details.</p>
<h4><strong><span style="color: #000080;">Getting the Google Maps API key</span></strong></h4>
<p>To integrate google map in your application firstly you have to generate the API key in <span style="color: #008000;"><strong><a style="color: #008000;" href="https://console.developers.google.com/">Google API Console</a></strong></span> .</p>
<p>2 . Go to <span style="color: #0000ff;"><strong>Google API Console</strong></span> and generate a new API key corresponding to your <strong><span style="color: #008000;">SHA1</span></strong> and <strong><span style="color: #008000;">application package name</span></strong>.</p>
<p>3 . Open <strong><span style="color: #008000;">AndroidManifest.xml</span></strong> and add the generated API key to your project above the <;/application >; tag as shown below :</p>
<p><span style="color: #0000ff;"><strong>AndroidManifest.xml</strong> </span></p>
<pre><;application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:roundIcon="@mipmap/ic_launcher_round"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">;
 <;activity android:name=".MainActivity">;
 <;intent-filter>;
 <;action android:name="android.intent.action.MAIN" />;

 <;category android:name="android.intent.category.LAUNCHER" />;
 <;/intent-filter>;
 <;/activity>;

 <strong><span style="color: #0000ff;"> <;meta-data</span></strong>
<strong><span style="color: #0000ff;"> android:name="com.google.android.geo.API_KEY"</span></strong>
<strong><span style="color: #0000ff;"> android:value="YOUR API KEY"/>;</span></strong>

<;/application>;</pre>
<p>4 . Open <strong><span style="color: #008000;">build.gradle</span></strong> and add the following dependencies as shown below :</p>
<p><strong><span style="color: #0000ff;">build.gradle</span></strong></p>
<pre>dependencies {
 implementation fileTree(dir: 'libs', include: ['*.jar'])
 
 <strong><span style="color: #0000ff;"> implementation 'com.google.android.gms:play-services-maps:17.0.0'</span></strong>
 
<strong><span style="color: #0000ff;"> implementation 'com.google.android.gms:play-services-location:17.0.0'</span></strong>
}</pre>
<h4 id="permissions"><strong><span style="color: #000080;">Specify app permissions</span></strong></h4>
<div class="paragraph">
<p>5 . Open <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span> and add the following permissions to your application to use location services.</p>
</div>
<div class="ulist">
<ul>
<li>INTERNET</li>
<li>ACCESS_FINE_LOCATION</li>
<li>ACCESS_COARSE_LOCATION</li>
</ul>
<p><span style="color: #0000ff;"><strong>AndroidManifest.xml</strong></span></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<pre><;?xml version="1.0" encoding="utf-8"?>;
<;manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.getcurrentlocationonmap">;

 <strong><span style="color: #0000ff;"> <;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />;</span></strong>
<strong><span style="color: #0000ff;"> <;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />;</span></strong>
<strong><span style="color: #0000ff;"> <;uses-permission android:name="android.permission.INTERNET" />;</span></strong>

 <;application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:roundIcon="@mipmap/ic_launcher_round"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">;
 <;activity android:name=".MainActivity">;
 <;intent-filter>;
 <;action android:name="android.intent.action.MAIN" />;

 <;category android:name="android.intent.category.LAUNCHER" />;
 <;/intent-filter>;
 <;/activity>;

 <;meta-data
 android:name="com.google.android.geo.API_KEY"
 android:value="YOUR API KEY"/>;

 <;/application>;

<;/manifest>;</pre>
<p> ;</p>
</div>
<p>6 . Open <span style="color: #008000;"><strong>activity_main.xml</strong></span> and add the fragment for the map as shown below:</p>
<p><span style="color: #0000ff;"><strong>activity_main.xml</strong></span></p>
<pre><;fragment
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/map"
 android:name="com.google.android.gms.maps.SupportMapFragment"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context="com.example.getcurrentlocationonmap.MainActivity" />;
</pre>
<p>7 . As of Android <strong><span style="color: #008000;">Marshmallow</span></strong> Location permissions need to be explicitly approved by the user before the app begins to collect device location.</p>
<p>8 . We had already mentioned that <strong><span style="color: #008000;">FusedLocationProviderClient</span></strong> takes care of all the connection logic on its own. Therefore we don’t need to initialize <strong><span style="color: #008000;">GoogleApiClient</span></strong> nor do we need to implement connection callbacks. We only need to initialize the FusedLocationProviderClient as shown below:</p>
<pre>fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);</pre>
<p>9 . Once we have <strong><span style="color: #008000;">FusedLocationProviderClient</span></strong> we can fetch the current location using the <strong><span style="color: #008000;"><em>getLastLocation</em>()</span></strong> . It returns a Task object which represents an asynchronous operation.</p>
<pre>Task task = fusedLocationProviderClient.getLastLocation();</pre>
<p>10 . We will add the success callback listener to the <strong><span style="color: #008000;">Task</span></strong> object which will be invoked once the connection is established and the location is fetched.</p>
<pre>task.addOnSuccessListener(new OnSuccessListener() {
 @Override
 public void onSuccess(Location location) {
 if (location != null)
 currentLocation = location;
 Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + "," +
 currentLocation.getLongitude(), Toast.LENGTH_LONG).show();


 SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
 supportMapFragment.getMapAsync(MainActivity.this);

 }
});</pre>
<p>11 . You must have noticed we add a null check for location in <strong><span style="color: #008000;">OnSuccessListener</span></strong>. This is to avoid crashes in some scenarios in which the location can be null. Below are some of these scenarios</p>
<ul>
<li class="graf graf--li graf-after--p">GPS provider is turned off in the device settings.</li>
<li id="fa85" class="graf graf--li graf-after--li">Location was never recorded on the devices. This could be the case of a new device or a device that has been restored to factory settings.</li>
</ul>
<h3><strong><span style="color: #000080;">Complete Code</span></strong></h3>
<p>12 . Open <span style="color: #008000;"><strong>MainActivity.java</strong></span> and add the below code:</p>
<p><span style="color: #333399;"><strong>MainActivity.java</strong></span></p>
<pre>package com.example.getcurrentlocationonmap;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {


 Location currentLocation;
 FusedLocationProviderClient fusedLocationProviderClient;
 private static final int REQUEST_CODE = 200;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
 fetchLastlocation();
 }


 private void fetchLastlocation() {

 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {


 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
 return;
 }

 Task task = fusedLocationProviderClient.getLastLocation();
 task.addOnSuccessListener(new OnSuccessListener() {
 @Override
 public void onSuccess(Location location) {
 if (location != null)
 currentLocation = location;
 Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + "," +
 currentLocation.getLongitude(), Toast.LENGTH_LONG).show();


 SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
 supportMapFragment.getMapAsync(MainActivity.this);

 }
 });
 }

 @Override
 public void onMapReady(GoogleMap googleMap) {
 LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
 MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("You are here");
 googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
 googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
 googleMap.addMarker(markerOptions);


 }

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

 switch (requestCode) {
 case REQUEST_CODE:

 if (grantResults.length >; 0 &;&; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 fetchLastlocation();
 }
 break;
 }
 }
}</pre>
<p>When you run your app it will look like this :</p>
<p><img class="alignnone wp-image-1268" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1572340388.png" alt="Screenshot_1572340388" width="309" height="550" /> <img class="alignnone wp-image-1267" style="color: var(--color-text);" src="https://c1ctech.com/wp-content/uploads/2019/10/Screenshot_1572340433.png" alt="Screenshot_1572340433" width="310" height="551" /></p>
<p> ;</p>
<p>I hope this article will help you in understanding how to use <span style="color: #008000;"><strong>Fusedlocationprovider</strong></span> to get the current location of your device.

