Wednesday, September 29, 2021

Where am I ? Location Based Services @FusedLocationProviderClient

 "Jai Sarawati Maa"

Location Based Services 

The location APIs available in Google Play services facilitate adding location awareness to your app with automated location tracking, wrong-side-of-the-street detection, geofencing, and activity recognition. 

The API updates your app periodically with the best available location, based on the currently-available location providers such as WiFi and GPS (Global Positioning System). 

I am uploading how to find out your current location and address by using FusedLocationProviderClient. Which is the best way to deal with location based activities.  

Step-I: Open Android SDK Manager and check either Google Play Services Installed or not. if not please install google play services. See the below pic. 


  

Step-II: After installation kindly add below dependencies in module level gradle file. 

implementation 'com.google.android.gms:play-services-location:18.0.0'

Step-III: Add meta data in between application tag and required permission in Manifest file.

<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>

<uses-permission android:name="android.permission.
                              ACCESS_FINE_LOCATION"/>
Step-IV: Your output will be like. 





See the code of MainActivity
package com.example.locationbasedservices2021;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity
{
final int REQUEST_CODE_LOCATION=123;
int locationRequestCode;
TextView lat_text,long_text,add_text;
FusedLocationProviderClient fusedLocationClient;
double lat, longi;
String addres;
Button button;
Boolean flag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat_text = findViewById(R.id.textLat);
long_text = findViewById(R.id.textLong);
add_text = findViewById(R.id.textCity);
button = findViewById(R.id.btn_location);
fusedLocationClient = LocationServices.
getFusedLocationProviderClient(this);

locationRequestCode =
ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
 button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag)
{
finLoc();

}
}
});
}

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

if(locationRequestCode == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission Already Given ",
                        Toast.LENGTH_LONG).show();
flag = true;
}
else
{
askforPermission();
}
}
private void askforPermission() {

if(locationRequestCode != PackageManager.PERMISSION_GRANTED)
{
if(!ActivityCompat.shouldShowRequestPermissionRationale
      (MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
return;
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
        String[] permissions,int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
            grantResults);
if(requestCode == REQUEST_CODE_LOCATION)
{
if(grantResults.length>0 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this,"Permission Granted",
                                Toast.LENGTH_LONG).show();
flag = true;
finLoc();
}
}
}
private void finLoc() {

fusedLocationClient.getLastLocation().addOnCompleteListener
                (new OnCompleteListener<Location>() {
        @Override
public void onComplete(Task<Location> task) {

Location location = task.getResult();
if(location!=null)
{
Geocoder geocoder = new Geocoder(MainActivity.this,
                                 Locale.getDefault());
try {
List<Address> address = geocoder.getFromLocation
                                        (location.getLatitude(),
             location.getLongitude(),1);
lat = location.getLatitude();
longi = location.getLongitude();
lat_text.setText("Latitide: " + lat);
long_text.setText("Longitude: " + longi);

StringBuilder sb = new StringBuilder();
if (address.size() > 0) {
Address addr = address.get(0);
for (int i = 0; i < addr.getMaxAddressLineIndex(); i++)
sb.append(addr.getAddressLine(i)).append("\n");
sb.append(addr.getLocality()).append("\n");
sb.append(addr.getPostalCode()).append("\n");
sb.append(addr.getCountryName());
}
addres = sb.toString();

} catch (IOException e) {
e.printStackTrace();
}
}
add_text.setText("Address:"+addres);
}
});
}
}

// Layout File 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<Button
android:id="@+id/btn_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_marginTop="100dp"
android:text="Find Location" />

<TextView
android:id="@+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lattitude"
android:textSize="30dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"/>
<TextView
android:id="@+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude "
android:textSize="30dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"/>

<TextView
android:id="@+id/textCity"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginTop="20dp"
android:text="City"
android:textSize="30dp" />

</LinearLayout>