Showing posts with label Location Based Services. Show all posts
Showing posts with label Location Based Services. Show all posts

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>


Tuesday, April 19, 2016

Location Based Services Part-III (Get Updated Address also with Latitude & Longitude)

" Jai Saraswati Maa"

Please refer Part - II  of LBS


In this example you will also get Address of your new updated location.
In previous example i have added only one Button & one Text View in Layout.
One method which is on onClick of Button.
Changed from previous example are in Bold Italic. 
A. Changed Layout file is activity_main.xml file is as
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.exam.ravi.locationbsex1.MainActivity">

    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Ltitude and  Longitude... "

        android:id="@+id/textLocation"

        android:textSize="20dp"/>
    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"        android:text="GetAddress"

        android:onClick="findAddress"

        android:id="@+id/butAdd"

        android:layout_below="@+id/textLocation"

        android:layout_marginTop="10dp"/>

    <TextView        android:layout_width="wrap_content"

        android:layout_height="match_parent"

        android:id="@+id/textAdd"

        android:textSize="15sp"

        android:layout_below="@+id/butAdd"

        android:layout_marginTop="10dp"/>
</RelativeLayout>

B. Java code is as   MainActivity.java  

package com.exam.ravi.locationbsex1;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
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;

public class MainActivity extends AppCompatActivity
         implements GoogleApiClient.OnConnectionFailedListener ,
                GoogleApiClient.ConnectionCallbacks ,LocationListener
{
    TextView dis,add;
    GoogleApiClient googleApiClient;
    int SERVICE_CODE = 99;
    Double lat,lng;
    LocationRequest locationRequest;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        add= (TextView) findViewById(R.id.textAdd);
        dis = (TextView) findViewById(R.id.textLocation);
        if(checkServices())
        {
            clientInitialization();
        }
    }
    private void clientInitialization() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();
    }
    @Override    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }
@Overrideprotected void onStop() {
    super.onStop();
    if(googleApiClient.isConnected())
        googleApiClient.disconnect();
}

private boolean checkServices()
{
    int result= GooglePlayServicesUtil.isGooglePlayServicesAvailable
                                                      (getApplicationContext());
    if(result!= ConnectionResult.SUCCESS)
    {
        if(GooglePlayServicesUtil.isUserRecoverableError(result))
        {
            GooglePlayServicesUtil.getErrorDialog(result,this,SERVICE_CODE).show();
        }
        return false;
    }
    return true;
}

@Overridepublic void onConnected(Bundle bundle) {
locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(36000000);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
                               locationRequest,this);

    }

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

    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();

    }

    @Override    public void onLocationChanged(Location location) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        if(location!=null)
            dis.setText("Latitude = " + lat + "\n Longitude = " + lng);
        else            dis.setText("Location Not Found");

    }
   public void findAddress(View view) {
       Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
       try {
           List<Address> addressList = geocoder.getFromLocation(lat,lng, 1);
           if (addressList != null && addressList.size() > 0) {
             String message ="";
               for(int i = 0 ; i<addressList.get(0).getMaxAddressLineIndex();i++)
               {
                   message = message + addressList.get(0).getAddressLine(i)+"\n";
               }
            
               add.setText("Address is \n"+ message);
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}
  

Sunday, April 17, 2016

Location Based Services Part-II (Get Updates in every 30 seconds)

Please refer Part - I

Location Based Services Part-I (Find Latitude & Longitude)


And make few changes in MainActivity.java file.
Please see.....

A. One more method added and LocationListener added   in 
       MainActivity.java   is as 

package com.exam.ravi.locationbsex1;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity
         implements GoogleApiClient.OnConnectionFailedListener ,
                GoogleApiClient.ConnectionCallbacks ,LocationListener
{
    TextView dis;
    GoogleApiClient googleApiClient;
    int SERVICE_CODE = 99;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dis = (TextView) findViewById(R.id.textLocation);
        if(checkServices())
        {
            clientInitialization();
        }
    }
    private void clientInitialization() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();
    }
    @Override    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }

    @Override    protected void onStop() {
        super.onStop();
        if(googleApiClient.isConnected())
            googleApiClient.disconnect();
    }

    private boolean checkServices()
    {
        int result= GooglePlayServicesUtil.isGooglePlayServicesAvailable
                                             (getApplicationContext());
        if(result!= ConnectionResult.SUCCESS)
        {
            if(GooglePlayServicesUtil.isUserRecoverableError(result))
            {
             GooglePlayServicesUtil.getErrorDialog(result,this,SERVICE_CODE).show();
            }
            return false;
        }
        return true;
    }

    @Override    public void onConnected(Bundle bundle) {
         LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30000);
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
                                                        locationRequest,this);
    }

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

    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();

    }

    @Override    public void onLocationChanged(Location location) {
        
        if(location!=null)
            dis.setText("Latitude = " + location.getLatitude()+ 
                              "Longitude" + location.getLongitude());
        else            dis.setText("Location Not Found");


    }
}

Location Based Services Part-I (Find Latitude & Longitude)

" Jai Saraswati Maa" 
Hi ... Dear All ..Today I am uploading a superb example of finding Latitude & Longitude of your position.

Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.
***Please check on physical device or on emulator but make sure to set your position.
*** Make sure Google Play Services is installed or not. (if not please install first)
*** Add dependency in gradle file like
compile 'com.google.android.gms:play-services:8.3.0'

*** Add meta tag with application tag in manifest file like 
<meta-data    android:name="com.google.android.gms.version"

    android:value="@integer/google_play_services_version"/>
**** Also add permission in manifest file like 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
               </uses-permission>

A. Nothing in Layout file only one text view is there to show values
xml code of activity_main.xml is 

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.exam.ravi.locationbsex1.MainActivity">

    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Ltitude and  Longitude... "

        android:id="@+id/textLocation"

        android:textSize="25sp"/>
</RelativeLayout>

B. Java Code of MainActivity.java 

package com.exam.ravi.locationbsex1;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends AppCompatActivity
         implements GoogleApiClient.OnConnectionFailedListener ,
                                        GoogleApiClient.ConnectionCallbacks
{
    TextView dis;
    GoogleApiClient googleApiClient;
    int SERVICE_CODE = 99;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dis = (TextView) findViewById(R.id.textLocation);
        if(checkServices())
        {
            clientInitialization();
        }
    }
    private void clientInitialization() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .build();
    }
    @Override    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }

    @Override    protected void onStop() {
        super.onStop();
        if(googleApiClient.isConnected())
            googleApiClient.disconnect();
    }

    private boolean checkServices()
    {
        int result= GooglePlayServicesUtil.isGooglePlayServicesAvailable
                                           (getApplicationContext());
        if(result!= ConnectionResult.SUCCESS)
        {
            if(GooglePlayServicesUtil.isUserRecoverableError(result))
            {
                GooglePlayServicesUtil.getErrorDialog(result,this,SERVICE_CODE).show();
            }
            return false;
        }
        return true;
    }

    @Override    public void onConnected(Bundle bundle) {
        Location location  = LocationServices.FusedLocationApi.getLastLocation
                                            (googleApiClient);
        if(location!=null)
            dis.setText("Latitude = " + location.getLatitude()+ "Longitude" +
                                  location.getLongitude());
        else            dis.setText("Location Not Found");

    }

    @Override

    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "Connection Susspended", Toast.LENGTH_SHORT).show();
    }

    @Override

    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();

    }
}