Get Location from withIn the Android app

How to get location from android app using the simple codes ?

  1. Create a new java class in project names LocationHelper.java
package andro.getlocationnew;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
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.api.Status;

public class MainActivity extends AppCompatActivity  implements LocationHelper.OnLocationCompleteListener, View.OnClickListener {

    String[] perm  = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    LocationHelper locationHelper;

    TextView lattxt, longtxt;

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

        lattxt = findViewById(R.id.lat);
        longtxt = findViewById(R.id.longt);

        askPermission();

    }
    public void GetLoc(View view){
        if(askPermission()){
            // permission already granted

            locationHelper = new LocationHelper(MainActivity.this, this);

        }else{
            askPermission();
        }
    }

    @Override
    public void getLocationUpdate(Location location) {

        lattxt.setText(String.valueOf(location.getLatitude()));
        longtxt.setText(String.valueOf(location.getLongitude()));
    }

    @Override
    public void onError(ConnectionResult connectionResult, Status status, String error) {

        if (connectionResult != null) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(this,
                            LocationHelper.CONNECTION_FAILURE_RESOLUTION_REQUEST);
                } catch (IntentSender.SendIntentException e) {
                    e.printStackTrace();
                }
            }
        } else if (status != null) {
            // Location is not available, but we can ask permission from users
            try {
                status.startResolutionForResult(this, LocationHelper.REQUEST_CHECK_SETTINGS);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View v) {
        locationHelper = new LocationHelper(MainActivity.this, this);
    }

    public boolean askPermission(){
        int hasPerm = ActivityCompat.checkSelfPermission(
                MainActivity.this,
                Manifest.permission.ACCESS_COARSE_LOCATION
        );
        // 0 for permissionGranted || 1 for permissionDenied
        if(hasPerm != 0){
            ActivityCompat.requestPermissions(
                    this,
                    perm,
                    100
            );

        }else{
            return true;
        }
        return false;
    }
}

2. Add the dependency in gradles file

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

3. Now in the MainActivity

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:onClick="GetLoc"
    android:text="get Loc"/>
public void GetLoc(View view){
    if(askPermission()){
        // permission already granted

    locationHelper = new LocationHelper(MainActivity.this, this);

    }else{
// if permission not granted
        askPermission();
    }
}
On buttonclick  call the below method to ask for the permission if not granted. 
String[] perm  = {
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION
};

public boolean askPermission(){
    int hasPerm = ActivityCompat.checkSelfPermission(
            MainActivity.this,
            Manifest.permission.ACCESS_COARSE_LOCATION
    );
    // 0 for permissionGranted || 1 for permissionDenied
    if(hasPerm != 0){
        ActivityCompat.requestPermissions(
                this,
                perm,
                100
        );
    }else{
        return true;
    }
    return false;
}

4. Now in Main Activity add

Create Object LocationHelper locationHelper;

implement in MainActivity

LocationHelper.OnLocationCompleteListener, View.OnClickListener

5. Implement three method named. getLocationUpdate, onError, onClick

6. Create two textView in XML

<TextView
    android:id="@+id/lat"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:textSize="20sp"
    android:gravity="center"/>

<TextView
    android:id="@+id/longt"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:layout_below="@+id/lat"
    android:textSize="20sp"
    android:gravity="center"
    />

TextView lattxt, longtxt;

lattxt = findViewById(R.id.lat);
longtxt = findViewById(R.id.longt);

7. Implementation Of Method

@Override
public void getLocationUpdate(Location location) {

    lattxt.setText(String.valueOf(location.getLatitude()));
    longtxt.setText(String.valueOf(location.getLongitude()));
}

@Override
public void onError(ConnectionResult connectionResult, Status status, String error) {

    if (connectionResult != null) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(this,
                        LocationHelper.CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        }
    } else if (status != null) {
        // Location is not available, but we can ask permission from users
        try {
            status.startResolutionForResult(this, LocationHelper.REQUEST_CHECK_SETTINGS);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onClick(View v) {
    locationHelper = new LocationHelper(MainActivity.this, this);
}

Add the Permission in Manifest file also

AccessCoarseLocation

AccessFineLocation

8. If the GPS is not ON

9 . After Location is ON And Active

The Location will retrieved in Longitude and Latitude

10. Location will retrieved in an interval of 5000 milliseconds

1 second. = 1000 millisecond

to change the interval go to LocationHelper and change the

UPDATE_INTERVAL_IN_MILLISECONDS = 5000;

Leave a Comment