Creating GPS Tracker Application on J2ME Phones

This article describes how to create the J2ME tracking application to be installed on J2ME capable phones with an internal GPS receiver. The application will utilize the Location API available on GPS enabled phones, read the GPS location data at a specified interval, send the data via HTTP connection to a specified server.

Here is the application looks like.

image

To simulate the GPS events on the device, let’s create an XML file to be loaded to the emulator:

<waypoints>
  <waypoint time="0" latitude="-6.10" longitude="107.36" altitude="100" />
  <waypoint time="10000" latitude="-6.54" longitude="108.38" altitude="0" />
</waypoints>

 

Save it into a file. Then load into the emulator from menu View- External Events Generator. Browse for the script file and press the Start button.

image

Here is the source code for the middlet. The filename is TrackMe.java.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package gpstracking;

import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.location.*;
import java.util.Date;
import java.util.Calendar;

public class TrackMe extends MIDlet implements CommandListener,
        LocationListener {

    private LocationProvider locationProvider = null;
    private Display display;
    private Form form;
    private Command exit = new Command("Exit", Command.EXIT, 1);
    private Command start = new Command("Start", Command.SCREEN, 1);
    private Command stop = new Command("Stop", Command.SCREEN, 1);
    private TextField unitId =
            new TextField("Unit ID/IMEI", "067442957992", 50,
            TextField.ANY);
    private String unitIdstr = "067442957992";
    private TextField interval =
            new TextField("Update Interval(min)", "1", 5,
            TextField.NUMERIC);
    private int sec = 60;
    private StringItem info = new StringItem("Location:", "unknown");

    public TrackMe() {
        display = Display.getDisplay(this);
        form = new Form("GPS Tracking Indonesia");
        form.addCommand(exit);
        form.addCommand(start);
        form.setCommandListener(this);
        form.append(unitId);
        form.append(interval);
        form.append(info);

        try {
            locationProvider = LocationProvider.getInstance(null);
        } catch (Exception e) {
            e.printStackTrace();
            exit();
        }
    }

    public void locationUpdated(LocationProvider provider, Location location) {
        if (location != null && location.isValid()) {
            QualifiedCoordinates qc =
                    location.getQualifiedCoordinates();

            HttpConnection connection = null;
            try {

                String url = "http://server-address/up.php?"
                        + "unit=" + unitIdstr
                        + "&lat=" + qc.getLatitude()
                        + "&lon=" + qc.getLongitude();

                System.out.println(url);
                connection = (HttpConnection) Connector.open(url);

                info.setText(
                        "Lat: " + qc.getLatitude() + "\n"
                        + "Lon: " + qc.getLongitude() + "\n"
                        + "Alt: " + qc.getAltitude() + "\n"
                        + "Server Response: "
                        + connection.getResponseMessage());
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    connection.close();
                } catch (Exception io) {
                    io.printStackTrace();
                }
            }
        }
    }

    static public String urlEncode(String sUrl) {
        StringBuffer urlOK = new StringBuffer();
        for (int i = 0; i < sUrl.length(); i++) {
            char ch = sUrl.charAt(i);
            switch (ch) {
                case ‘<’:
                    urlOK.append("%3C");
                    break;
                case ‘>’:
                    urlOK.append("%3E");
                    break;
                case ‘/’:
                    urlOK.append("%2F");
                    break;
                case ‘ ‘:
                    urlOK.append("%20");
                    break;
                case ‘:’:
                    urlOK.append("%3A");
                    break;
                case ‘-’:
                    urlOK.append("%2D");
                    break;
                default:
                    urlOK.append(ch);
                    break;
            }
        }
        return urlOK.toString();
    }

    public void providerStateChanged(LocationProvider provider,
            int newState) {
    }

    public void commandAction(Command c, Displayable s) {
        if (c == exit) {
            exit();
        }
        if (c == start) {
            form.removeCommand(start);
            unitIdstr = (unitId.getString() != null)
                    ? unitId.getString() : "123";
            sec = (interval.getString() != null)
                    ? Integer.parseInt(interval.getString()) : 5;

            // Start querying GPS data :
            locationProvider.setLocationListener(TrackMe.this, sec, -1, -1);
            form.addCommand(stop);
        }
        if (c == stop) {
            form.removeCommand(stop);

            // Stop querying GPS data :
            locationProvider.setLocationListener(null, -1, -1, -1);
            form.addCommand(start);
        }
    }

    public void startApp() {
        display.setCurrent(form);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean forced) {
    }

    public void exit() {
        destroyApp(false);
        notifyDestroyed();
    }
}

 

Some things that’s important on the above source code:

locationProvider = LocationProvider.getInstance(null)

This is where we instantiate the locationProvider object to be able to query the GPS location from the device.

locationProvider.setLocationListener(TrackMe.this, sec, -1, -1)

This will set the listener that will process the location update information sent by the LocationProvider. The provider will update the listener for the current GPS location at every sec seconds.

public void locationUpdated(LocationProvider provider, Location location)

This is the implemetation of the locationUpdated method of the LocationListener. This will be called on the interval set at the setLocationListener.

QualifiedCoordinates qc = location.getQualifiedCoordinates()

This is called every time the locationUpdated is invoked. This will store the location information into the QualifiedCoordinates qc variable where later we can set the latitude and longitude to be sent to out server.

locationProvider.setLocationListener(null, -1, -1, -1)

This will stop the LocationProvider to send the location information to the listener.

connection = (HttpConnection) Connector.open(url)

This is how we send data to the server using HTTP GET. The data is already encoded on the url, which including the latitude and longitude along with the unit that are sending the data. Later we can see the connection result by setting the info’s text using info.setText() method.

static public String urlEncode(String sUrl)

This is our own function to encode a string to a HTML encoded so that we can send it as a parameter of HTTP GET.

 

Real live example GPS Tracking System complete application can be viewed at www.GpsTrackingIndonesia.com.

If You need any further information or consultation, contact me directly:

Akhmad Daniel Sembiring

vitraining.com – CEO

Share

Tags:

Leave a Reply