How to track your location using GPS and send it over sms in your Android App? – Complete Source Code

This video shows the steps to create a location tracking App and send or share the coordinates of the location (Latitude and Longitude) by sending automatic SMS messages to a predefined phone number.

This video is a combination of following two videos available on this channel:
1. Location Tracking App: https://youtu.be/rN7x3ovWepM
2. How to send SMS automatically through your phone: https://youtu.be/pajvuBZc2WA

You can also refer to below video which shows how to create the APK installer file and install the App in your phone using the below link: https://youtu.be/5c7odVDNHj0

In the code, please ensure that in the gradle.properties file the following lines are added to use androidx libraries:

android.enableJetifier = true
android.useAndroidX = true

How to send current location in the form of link?

Ans:

Convert the string in the below format:

https://maps.google.com/?q=<lat>,<lng>

Below is the example URL for - 

Latitude = 41.24
Longitude = 2.06

https://maps.google.com/?q=41.24,2.06

A bit processing may be required to get the strings in above format.

Source Code:

package com.example.myyoutubelocationapp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

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;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

private LocationManager locationManager;
private LocationListener locationListener;

private final long MIN_TIME = 1000;
private final long MIN_DIST = 5;

private LatLng latLng;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title(“Marker in Sydney”));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
try {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(“My Position”));

mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

String phoneNumber = “99999”;
String myLatidude = String.valueOf(location.getLatitude());
String myLongitude = String.valueOf(location.getLongitude());

String message = “Latitude = ” + myLatidude + ” Longitude = ” + myLongitude;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber,null,message,null,null);
}
catch (Exception e){
e.printStackTrace();
}
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
};

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME,MIN_DIST,locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME,MIN_DIST,locationListener);
}
catch (SecurityException e){
e.printStackTrace();
}

}
}

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
package=”com.example.myyoutubelocationapp”>

<!–
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the ‘MyLocation’ functionality.
–>
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>
<uses-permission android:name=”android.permission.INTERNET”/>
<uses-permission android:name=”android.permission.SEND_SMS”/>

<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”>

<!–
The API key for Google Maps-based APIs is defined as a string resource.
(See the file “res/values/google_maps_api.xml”).
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
–>
<meta-data
android:name=”com.google.android.geo.API_KEY”
android:value=”@string/google_maps_key” />

<activity
android:name=”.MapsActivity”
android:label=”@string/title_activity_maps”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

android.enableJetifier = true
android.useAndroidX = true

<?xml version=”1.0″ encoding=”utf-8″?>

<fragment xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:map=”http://schemas.android.com/apk/res-auto&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:id=”@+id/map”
android:name=”com.google.android.gms.maps.SupportMapFragment”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”.MapsActivity” />

Top posts/ comments from YouTube channel:

Hello, i just finished the project and its work thank you so much but why it does not show me the exact location! and can i add something else in the sms?
The App should show you the exact location. However, if you are running your App on emulator then it will show initial location at Sydney because that is the starting marker position we have set in the code. And later it will move the marker position to California because emulator is not able to give you the location info as it doesn’t have GPS or network data. So, it moves to some Pre-defined location in emulator.
However, if you try running it on your real phone, then it should definitely work. For the first time you may have to go in some open space to get nice view of GPS satellites.
Regarding SMS, yes of course you can send more information. While composing your SMS string “message” feel free to add your additional texts.

Read more

Okay thank you for helping but it doesn’t give me access to choose the phone. automatic execution with emulator and for the sms can i a text with the name of the location ??
Oh … ok. To run your application on your phone, you will have to build the APK (Android Package) file. Then install the App on your phone using this APK file. Then your App will be ready for use on your phone in standalone mode.
For steps to create a APK file please watch my below video: https://youtu.be/5c7odVDNHj0
For steps to install the App please watch my below video: https://youtu.be/StswYn4GSzk
Hope above helps. Good Luck!
Good Day sir, how to convert the longitude and altitude massage in to a City and address thank you for your videos thumbs up
We can use Geocorder API to translate the latitude and longitude to the address. We can get the address using the below command:
geocoder.getFromLocation(latitude, longitude, 1)
Alternately, you can also use below command to show the location on map:
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
I will try to create a tutorial for Geocorder command and let you know once posted.
You should see me next video from the below link. It shows the steps to get the location details from latitude and longitude :

We will be glad to hear from you regarding any query, suggestions or appreciations at: programmerworld1990@gmail.com

[Update:]

The next part of this video can be accessed using below link. It shows the steps to get the location details from latitude and longitude
https://youtu.be/Nsl99WWDFxM

21 comments

  1. Query (Received over email):

    Respected sir

    There’s no error in the entire program but while running it i’m getting errors which i am not able to resolve . Please do help me sir .

    Answer:

    From your error log it seems like there is not issue in your code or Android studio environment. However, the issue is with the emulator. I think the emulator is not properly installed or configured on your machine. I will suggest you to try reinstalling the emulator on your machine. And try starting the emulator without implementing anything first. (Just loading the environment in Android Studio).

    Also, you may try to directly test this App by installing it on your real phone. For steps of installation of APK file, you can refer to my below videos:

    https://www.youtube.com/watch?v=5c7odVDNHj0
    https://www.youtube.com/watch?v=StswYn4GSzk

    Hope above helps.

    Cheers
    Programmer World
    https://programmerworld.co

  2. Sir thank for making great vedio and simple code.sir i am facing problem, when app is install in my mobile phone its working fine.but after some when i open the app it is not showing my current location.And app also not sending message every time.

    • If it worked once then it should work again.

      Message is not being sent may be because if the location is not updated then it will not send the message. So, if your location update is happening it will send the message (of course unless you are out of network coverage or SMS service is not available).

      For the display issue of your current location, ensure your GPS is active. Also, sometimes it may be required to go outside (of the building) to get a clear visibility of the GPS satellite to get the location update.

      Please try above. If still you face the issue then I will suggest you to copy your code here so that we can have a look.

      Good Luck
      Programmer World

  3. sir i want to send my location in link through sms.I follow your program but my latitude and longitude are not updated.In app location is shown correctly but when i want to send sms the latitude and longititide are not updating.Please help me about that

    • That is surprising. Once we have the updated Latitude and Longitude coordinates in the App, then we should be able to send it over SMS as text message.

      I think we are framing our text message in the line below. Please check if the variables used in the below are not hardcoded and are updated with the location information:
      String message = “Latitude = ” + myLatidude + ” Longitude = ” + myLongitude;

      Also, check you have used “message” variable in the below sendText SMS API:
      smsManager.sendTextMessage(phoneNumber,null,message,null,null);

      I think the issue is very simple and tricky. Somewhere the update of variable is missing. Please refer to the complete source code shared in this page once again..

      Good Luck
      Programmer World

      • Thank you for reply sir.sir i want to send the location in Link through sms.when the user click on the the link he will found my location.I have followed your tetorial but i the latitude and longitude are not update and the message is also not sended to the user.Following is my code.Please help me.

        public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

        private GoogleMap mMap;
        private LocationManager locationManager;
        private LocationListener locationListener;

        private final long MIN_TIME = 1000;
        private final long MIN_DIST = 5;

        private LatLng latLng;
        private Object LocationListener;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS}, PackageManager.PERMISSION_GRANTED);
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title(“Marker in Sydney”));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        LocationListener= new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
        try {
        latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title(“My Position”));

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        String phoneNumber = “03325728216”;
        String myLatidude = String.valueOf(location.getAltitude());
        String myLongitude = String.valueOf(location.getLongitude());

        String message = “I am in trouble.Please pick me from this location”
        + “https://www.google.co.id/maps/@” +”Latitude = ” + myLatidude + ” Longitude = ” + myLongitude;
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNumber,null,message,null,null);
        }
        catch (Exception e){
        e.printStackTrace();
        }
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
        };

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME,MIN_DIST,locationListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME,MIN_DIST,locationListener);
        }
        catch (SecurityException e){
        e.printStackTrace();
        }

        }
        }

  4. hello sir the application is working but whenever it changes the location new pinpoint appear then the previous pinpoints will remain. how can i remove those previous pinpoints and only have the newest one. The other problem is, we tried this on 4 different phones, for the 2 phones it run smoothly it can locate the exact location no problem at all (just the pinpoint) but for the other 2 it cant locate its location. and for the last one, is it possible to draw an object in the map? for example a circle with the pin location in the center of the circle. Thank you!!!!!

    • Qs: how can i remove those previous pinpoints and only have the newest one.

      Just add mMap.clear() to remove all the markers before adding the new marker.

      Qs The other problem is, we tried this on 4 different phones, for the 2 phones it run smoothly it can locate the exact location no problem at all (just the pinpoint) but for the other 2 it cant locate its location. and for the last one

      Just ensure that GPS and Data network is ON and location access permissions (Coarse and Fine) both are granted to the App in the phone. Also, sometimes in some phones there may be restriction on using certain permissions for the user Apps. Just check that by going to Settings->Apps->Permission. A quick fix for this will be to just reinstall the App after removing the App (including the App data).

      Qs: is it possible to draw an object in the map? for example a circle with the pin location in the center of the circle.

      There are lots of properties of markers which allows to customize the shape, color, size, etc. of the marker. As of now I do not have a video to show this but below page will help you with this:
      https://developers.google.com/maps/documentation/android-sdk/marker

      Hope above details helps.

      Cheers
      Programmer World

      • Thank you for response!!

        I’m planning to remove access coarse location, because we wont be using network data for our application. Would that be okay? Would this application work offline? Btw the map doesnt load with no internet, does it really need a data or internet in order to load the map?

      • Qs: I’m planning to remove access coarse location, because we wont be using network data for our application. Would that be okay? Would this application work offline?

        Yes, that would be okay. But even if you remove coarse location and go for just fine location permission then also most of the phones tries to use both GPS and network data to get the location info. In simple words, fine location supersedes coarse location. However, when network is unavailable then the App will just use GPS data to update the location (fine location). So, yes this App will work offline also.

        Qs. Btw the map doesnt load with no internet, does it really need a data or internet in order to load the map?

        Yes, in the first run the App will need internet to download the map. Usually it will store the map information in the App data for the previously viewed region of the maps. But for exploring any new region the App will need internet to download the relevant part of the maps info. So, better to use this App with data/ internet once in a while.

        Cheers
        Programmer World

  5. Is there another way to have an offline map in our application that doesnt need internet? I’ve read other way like open street map offline or osmdroid? Would that work? I’m sorry i am just a beginner. Right now we are planning to develop an offline tracking system in an off-grid places so we prefer having an offline map. Anyway thank you for expanding my knowledge!! You are a big help for us who are starting to learn in this specific field. Thank you so much!

    • To make the App work in offline mode, the map has to be locally available in the phone as the App data. Now, we have 2 options here. Either bundle the map data in the installation package of the App. Or download the map whenever the network is available and work with the downloaded map in offline mode when the network is not available.

      The App developed in this tutorial follows 2nd concept. That is it will download the map when the network is available but will work in the offline mode also if the map is downloaded. The location will get updated using the GPS.

      For the 1st option, that is to bundle map with the App installer (APK), unfortunately, I do not have a page to demonstrate that.

      Cheers
      Programmer World

  6. bro very usefull video bro,,, such a great video, but broo while im exequting , sms va not properly working bro, guid me bro

Leave a Reply