How to get the current location latitude and longitude in android

In this tutorials, I will show you how to get the latitude and longitude of your location on a Android mobile phone or tablet. Please note, if you’re using an android tablet it needs to have inbuilt GPS. Often its referred as ‘Android Cellular Tablet’. This approach also works in offline mode which means you won’t need any internet connection. Please note, you will need to allow permission in your Manifest for internet connection and gps permission. Download the source code if you don’t know how to do it.

What does this app do?
– You will start on the MainActivity which is the activity that app will launch initially.
– Touch/Click on to ‘Start’ button which will take you to the GPS activity.
– It will prompt you with permission request to access you location
– It will prompt you and warn you if your GPS is not enabled
– After 7-8 seconds you will see Latitude and Longitude on the EditText fields. You can start moving around and you will see the coordinates will update every few seconds.

Hope you enjoy!

Language: Java
Software: Android Studio 3.1
CODE:

 

MainActivity

package com.subzdesigns.gpsoffline;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        Button gpsactivity = (Button) findViewById(R.id.gpsactivity);

        gpsactivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, OfflineGPS.class);
                intent.putExtra("Id", 7);
                startActivity(intent);
            }
        });
    }

}

OfflineGPS

package com.subzdesigns.gpsoffline;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class OfflineGPS extends AppCompatActivity implements LocationListener {

    LocationManager locationManager;

    String locationText = "";
    String locationLatitude = "";
    String locationLongitude = "";

    private int mInterval = 3000; // 3 seconds by default, can be changed later
    private Handler mHandler;


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

        setContentView(R.layout.activity_gps_offline);

        //Alert Dialog
        AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
                OfflineGPS.this);

        // Setting Dialog Title
        alertDialog2.setTitle("Notification");

        // Setting Dialog Message
        String string1 = "Give it 10-15 seconds for your coordinates to update. Keep moving around and you will see coordinates update.";

        alertDialog2.setMessage(string1);

        // Setting Icon to Dialog
        alertDialog2.setIcon(R.drawable.ic_launcher_background);

        // Setting Positive "Yes" Btn
        alertDialog2.setPositiveButton("Continue",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

        // Showing Alert Dialog
        alertDialog2.show();


        Handler handler2 = new Handler();
        handler2.postDelayed(new Runnable() {
            public void run() {
                mHandler = new Handler();
                startRepeatingTask();
            }
        }, 5000);   //5 seconds



        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

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

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopRepeatingTask();
    }

    Runnable mStatusChecker = new Runnable() {
        @Override
        public void run() {

            final EditText yourlat = (EditText) findViewById(R.id.yourLat);
            final EditText yourlong = (EditText) findViewById(R.id.yourLong);

            try {
                getLocation(); //this function can change value of mInterval.

                if (locationText.toString() == "") {
                    Toast.makeText(getApplicationContext(), "Trying to retrieve coordinates.", Toast.LENGTH_LONG).show();
                }
                else {

                    yourlat.setText(locationLatitude.toString());
                    yourlong.setText(locationLongitude.toString());
                }
            } finally {

                mHandler.postDelayed(mStatusChecker, mInterval);
            }
        }
    };

    void startRepeatingTask() {
        mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }

    void getLocation() {
        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, (LocationListener) this);
        }
        catch(SecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLocationChanged(Location location) {

        locationText = location.getLatitude() + "," + location.getLongitude();
        locationLatitude = location.getLatitude() + "";
        locationLongitude = location.getLongitude() + "";
    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(OfflineGPS.this, "Please Enable GPS", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }
}

Screenshots:

 

 

 

 

 

 

Source code:

Click to download