Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Posts: 108
Registered: ‎01-29-2009
My Device: BlackBerry 8700g
My Carrier: Tigo

GPS Tracker on Background Treadh

Hi Team,

 

I need your valious help.

 

I need create a GPS tracker application with special funcionallity:

- The application gps tracker will be run when the device is turn on,

- The application gps tracker wiil be not cancelled by user,

- the gps tracker will run all the time, in background thread.

 

For this prototipe, i have create two applications:

 

The one application is suggested by RIM BlackBerry "How To - Create a Background Application".

 

 

/**
* GUILessApplication
*
* A sample application that appears on the ribbon
* but does not have any user interface.
*/

package com.samples.guiLessApplication;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;

public final class GUILessApp extends Application
{ 
     private BackGroundApp backGroundApp;
     public static void main(String[] args)
     {
          GUILessApp theApp = new GUILessApp();
          theApp.enterEventDispatcher();
     }

     public GUILessApp()
     {
          //Creates and starts a new BackGroundApp thread.

          backGroundApp = new BackGroundApp();
          backGroundApp.start();
     }

     //The thread that will run in the background.
     private class BackGroundApp extends Thread
     {
          boolean stopThread = false;
          public synchronized void stop()
          {
               stopThread = true;
          }

          public void run()
          {
               while (!stopThread)
               {
                    //You would perform your processing here.
                    //This sample just prints out a line
                    //to the BlackBerry JDE Output Window
                    System.out.println("Application is running");

                    //Sleep for 5 seconds to prevent the
                    //application from running out of control
                    try
                    {
                         sleep(5000);
                    }
                    catch (Exception e)
                    {
                         //Exception handling would go here.
                    }
               }
          }
     }
     //Stop the thread on exit.
     protected void onExit()
     {
          backGroundApp.stop();
     }
}

 

 

This code run perfectly,

 

Now, i have implemented the GPS Tracker application, the code is:

 

 

package com.rim.samples.device.tracker;


import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import javax.microedition.location.*;
import javax.microedition.location.Location.*;
import javax.microedition.location.Criteria.*;
import javax.microedition.io.*;
import java.util.*;


public class tracker extends UiApplication
{
    public static void main(String[] args)
    {
        tracker trackerApp = new tracker();
        trackerApp.enterEventDispatcher();
    }

    public tracker()
    {
       pushScreen(new startScreen());
    }
} 


final class startScreen extends MainScreen
{
    Timer updateTimer = new Timer(); 
    TimerTask updateTask = new TimerTask()
    {
        public void run()
        {
            LocationProvider lp; // LocationProvider does the actual work of reading coordinates from the GPS
            Location currentLoc; // Stores component information of our position
            Criteria cr = new Criteria(); // Settings for the GPS - we can read it at different accuracy levels
            HttpConnection httpConn;  // An HTTP socket connection class to send our results to a webserver
            String getStr; 

            cr.setCostAllowed(true);
            cr.setHorizontalAccuracy(javax.microedition.location.Criteria.NO_REQUIREMENT);
            cr.setVerticalAccuracy(javax.microedition.location.Criteria.NO_REQUIREMENT);
            cr.setPreferredPowerConsumption(javax.microedition.location.Criteria.NO_REQUIREMENT);

            try
            {
                lp = LocationProvider.getInstance(cr);
                currentLoc = lp.getLocation(5);
            }

            catch(LocationException e)
            {
                Dialog.alert("Error getting coordinates");
                return;
            }

            catch(InterruptedException e)
            {
                Dialog.alert("GPS Interrupted!");
                return;
            }

            try
            {
                getStr = "LATITUDE=" + currentLoc.getQualifiedCoordinates().getLatitude();
                getStr = getStr + "&LONGITUDE=" + currentLoc.getQualifiedCoordinates().getLongitude();
                getStr = getStr + "&ALTITUDE=" + currentLoc.getQualifiedCoordinates().getAltitude();
                getStr = getStr + "&SPEED=" + currentLoc.getSpeed();

                httpConn = (javax.microedition.io.HttpConnection) javax.microedition.io.Connector.open("http://mysite.com/getgps.asp?" + getStr);
                httpConn.setRequestMethod(HttpConnection.GET);
                httpConn.setRequestProperty("Connection","close");
                httpConn.setRequestProperty("Content-Length","0");
                httpConn.getResponseCode();
                httpConn.close();
            }

            catch (java.io.IOException e)
            {
                Dialog.alert("Error contacting web server");
                return;
            }
        }
    };

    public startScreen()
    {
        super();

        LabelField title = new LabelField("GPS Tracker", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
        setTitle(title);

        add(new RichTextField("Starting transmission..."));
        updateTimer.scheduleAtFixedRate(updateTask, 10, 10000);
    }

    public boolean onClose()
    {
      Dialog.alert("Transmission Ended!");
      System.exit(0);
      return true;
    }
}

 

 

Now, my problem, i need integrate the gps tracker on background treadh, i have attemp varios ways, but i do not have good results. This is my better attemp.

 

 

package com.rim.samples.device.trackerbg;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;

import javax.microedition.location.*;
import javax.microedition.location.Location.*;
import javax.microedition.location.Criteria.*;
import javax.microedition.io.*;
import java.util.*;
import net.rim.device.api.ui.container.MainScreen;


   
public final class GUILessApp extends UiApplication
{ 
     private BackGroundApp backGroundApp;
     public static void main(String[] args)
     {
          GUILessApp theApp = new GUILessApp();
          theApp.enterEventDispatcher();
     }

     public GUILessApp()
     {
          //Creates and starts a new BackGroundApp thread.

          backGroundApp = new BackGroundApp();
          backGroundApp.start();
         
     }
    
    
     //The thread that will run in the background.
     private class BackGroundApp extends Thread
     {
          boolean stopThread = false;
          public synchronized void stop()
          {
               stopThread = true;
          }

          public void run()
          {
               while (!stopThread)
               {
                    //You would perform your processing here.
                    //This sample just prints out a line
                    //to the BlackBerry JDE Output Window
                    System.out.println("Application is running");

                    //Sleep for 5 seconds to prevent the
                    //application from running out of control
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                         public void run() {
                               pushScreen(new MyMainScreen());
                        }
                    });
                    UiApplication.getUiApplication().requestForeground();

                    try
                    {
                         sleep(5000);
                    }
                    catch (Exception e)
                    {
                         //Exception handling would go here.
                    }
                    
                    
               }
          }
          
          final class MyMainScreen extends MainScreen 
            {
                Timer updateTimer = new Timer(); 
                TimerTask updateTask = new TimerTask()
                {
                    public void run()
                    {
                        LocationProvider lp; // LocationProvider does the actual work of reading coordinates from the GPS
                        Location currentLoc; // Stores component information of our position
                        Criteria cr = new Criteria(); // Settings for the GPS - we can read it at different accuracy levels
                        HttpConnection httpConn;  // An HTTP socket connection class to send our results to a webserver
                        String getStr; 
            
                        cr.setCostAllowed(true);
                        cr.setHorizontalAccuracy(javax.microedition.location.Criteria.NO_REQUIREMENT);
                        cr.setVerticalAccuracy(javax.microedition.location.Criteria.NO_REQUIREMENT);
                        cr.setPreferredPowerConsumption(javax.microedition.location.Criteria.NO_REQUIREMENT);
            
                        try
                        {                        
                            lp = LocationProvider.getInstance(cr);
                            currentLoc = lp.getLocation(60);
                        }
                        catch(LocationException e)
                        {
                            Dialog.alert("Error getting coordinates");
                            return;
                        }
                        catch(InterruptedException e)
                        {
                            Dialog.alert("GPS Interrupted!");
                            return;
                        }
                        try
                        {
                            getStr = "LATITUDE=" + currentLoc.getQualifiedCoordinates().getLatitude();
                            getStr = getStr + "&LONGITUDE=" + currentLoc.getQualifiedCoordinates().getLongitude();
                            getStr = getStr + "&ALTITUDE=" + currentLoc.getQualifiedCoordinates().getAltitude();
                            getStr = getStr + "&SPEED=" + currentLoc.getSpeed();
            
                            httpConn = (javax.microedition.io.HttpConnection) javax.microedition.io.Connector.open("http://mysite.com/getgps.asp?" + getStr);
                            httpConn.setRequestMethod(HttpConnection.GET);
            
                            httpConn.setRequestProperty("Connection","close");
                            httpConn.setRequestProperty("Content-Length","0");
            
                            httpConn.getResponseCode();
                            httpConn.close();
                        }
                        catch (java.io.IOException e)
                        {
                            Dialog.alert("Error contacting web server");
                            return;
                        }
                    }
                };
            
                public MyMainScreen()
                {
                    super();
            
                    LabelField title = new LabelField("GPS Tracker", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
                    setTitle(title);
            
                    add(new RichTextField("Starting transmission..."));
                    updateTimer.scheduleAtFixedRate(updateTask, 10, 10000);
                }
            
                public boolean onClose()
                {
                Dialog.alert("Transmission Ended!");
                System.exit(0);
                return true;
                }
            }
     }
     //Stop the thread on exit.
     protected void onExit()
     {
          backGroundApp.stop();
     }
}

 

Guys, Do you have any suggestion for my requirement, samples code, tutorials or other information? I have searched on Google and RIM Forum, but, i do not have good results.

 

Thanks for your help.

 

Best Regards

Jorge Luis

 

 

Jorge Luis Frias B

Leader on Development
BlackBerry/iPhone Technologies
Developer
Posts: 713
Registered: ‎05-31-2010
My Device: 8520

Re: GPS Tracker on Background Treadh

Developer
Posts: 108
Registered: ‎01-29-2009
My Device: BlackBerry 8700g
My Carrier: Tigo

Re: GPS Tracker on Background Treadh

Hi Yamil

 

I have attemped to run this code, but, the result is very frustrated, the sample application not run, i wrote the author but i do not have any news.

 

The error is the following:

 

synchronized (MyApplicationName().enterEventDispatcher())

 

What is the value of MyApplicationName i have attemped with diferents values

 

 

Are you any suggestgions, thanks

 

Jorge

Jorge Luis Frias B

Leader on Development
BlackBerry/iPhone Technologies
Developer
Posts: 4,764
Registered: ‎07-21-2008
My Device: Not Specified

Re: GPS Tracker on Background Treadh

"MyApplicationName" refers to the class name of you UiApplication (or Application) class, i.e. your main application object.

 

public class MyApplication extends UiApplication {

 

...more stuff here

 

}

 

In your main() method, you will beed to instantiate the MyApplication class...

 

MyApplication app = new MyApplication();

 

..then enter the event dispatcher:

 

app.enterEventDispatcher();

 

 

 

 

Developer
Posts: 713
Registered: ‎05-31-2010
My Device: 8520

Re: GPS Tracker on Background Treadh

Jorge, MyApplicationName() must return a object of Application type, so I guess this method return the current application.

I think you could change to getApplication(). this method is from Screen and returns the Application object which owns the current screen.

Developer
Posts: 108
Registered: ‎01-29-2009
My Device: BlackBerry 8700g
My Carrier: Tigo

Re: GPS Tracker on Background Treadh

Hi Yamil, thanks for the explanation, but, this not run, Would you help me?

 

 

The code suggested i have eimplemented in the following lines:

 

 

/*
* GPSScreen.java
*
* © <your company here>, 2003-2008
* Confidential and proprietary.
*/

package com.rim.samples.device.GPSScreen;

import java.util.Timer;
import java.util.TimerTask;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

public class GPSScreen extends MainScreen
{
GPS gps;
Timer timer;
RichTextField txtGPS;

public GPSScreen()
{
gps = new GPS();
timer = new Timer();
timer.schedule(new CheckGPS(), 100, 1000); //check for GPS every 1 second;

String textGPS = "";
txtGPS = new RichTextField(textGPS, RichTextField.NON_FOCUSABLE);

add(txtGPS);
}
public boolean onClose()
{
timer.cancel(); //cleanup
this.close();
return true;
}

public class CheckGPS extends TimerTask
{
public CheckGPS()
{
}

public void run()
{
double lat;
double lng;
lat = 0;
lng = 0;

lat = gps.getLatitude();
lng = gps.getLongitude();

if (lat != 0.0 & lng != 0.0)
{
synchronized (MyApplicationName().enterEventDispatcher())
{
double acc = gps.getAccuracy();
txtGPS.setText(lat + ", " + lng + " (" + gps.getSatCount() + ") (" + (int) acc + ")");
}

}
else
{
String thetxt = txtGPS.getText();
synchronized (MyApplicationName().enterEventDispatcher())
{
if(thetxt.length() > 10)
if(thetxt.length() > 25)
txtGPS.setText("Waiting for GPS.");
else
txtGPS.setText(thetxt + ".");
else
txtGPS.setText("Waiting for GPS.");
}
}
}
}
}


/*
* GPS.java
*
* © <your company here>, 2003-2008
* Confidential and proprietary.
*/

package com.rim.samples.device.GPSScreen;

import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;

public class GPS extends Thread {

private double latitude;
private double longitude;
private String satCountStr;
private float accuracy;
private double heading;
private double altitude;
private double speed;

private int interval = 1; // time in seconds to get new gps data

/**
* This will start the GPS
*/
public GPS()
{
// Start getting GPS data
if (currentLocation())
{
// This is going to start to try and get me some data!
}
}

private boolean currentLocation()
{
boolean retval = true;
try
{
LocationProvider lp = LocationProvider.getInstance(null);
if (lp != null)
{
lp.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
}
else
{
// GPS is not supported, that sucks!
// Here you may want to use UiApplication.getUiApplication() and post a Dialog box saying that it does not work
retval = false;
}
}
catch (LocationException e)
{
System.out.println("Error: " + e.toString());
}

return retval;
}

private class LocationListenerImpl implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if (location.isValid())
{
heading = location.getCourse();
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
speed = location.getSpeed();

// This is to get the Number of Satellites
String NMEA_MIME = "application/X-jsr179-location-nmea";
satCountStr = location.getExtraInfo("satellites");
if (satCountStr == null)
{
satCountStr = location.getExtraInfo(NMEA_MIME);
}

// this is to get the accuracy of the GPS Cords
QualifiedCoordinates qc = location.getQualifiedCoordinates();
accuracy = qc.getHorizontalAccuracy();
}
}

public void providerStateChanged(LocationProvider provider, int newState)
{
// no-op
}
}

/**
* Returns the terminal's course made good in degrees relative to true north.
* The value is always in the range (0.0,360.0) degrees.
*
* @return double
*/
public double getHeading()
{
return heading;
}

/**
* Returns the altitude component of this coordinate.
* Altitude is defined to mean height above the WGS84 reference ellipsoid.
* 0.0 means a location at the ellipsoid surface, negative values mean the
* location is below the ellipsoid surface, Float.NaN that no altitude is
* available.
*
* @return double
*/

public double getAltitude()
{
return altitude;
}

/**
* Get the number of satellites that you are currently connected to
*
* @return String
*/
public String getSatCount()
{
return satCountStr;
}

/**
* Get the Accuracy of your current GPS location
*
* @return float
*/
public float getAccuracy()
{
return accuracy;
}

/**
* Returns the latitude component of this coordinate.
*
* Positive values indicate northern latitude and negative values southern latitude.
*
* @return double
*/

public double getLatitude()
{
return latitude;
}

/**
* Returns the longitude component of this coordinate.
*
* Positive values indicate eastern longitude and negative values western longitude.
*
* @return double
*/

public double getLongitude()
{
return longitude;
}

/**
* Get your current ground speed in meters per second (m/s) at the time of measurement
*
* @return double
*/

public double getSpeed()
{
return speed;
}
}


 

 

The part of code that mentioned in this sample not run, synchronized (MyApplicationName().enterEventDispatcher())

 

I have attemped all suggested including the last, but, it is not running.

 

Thanks for great help

 

Jorge

Jorge Luis Frias B

Leader on Development
BlackBerry/iPhone Technologies
Developer
Posts: 4,764
Registered: ‎07-21-2008
My Device: Not Specified

Re: GPS Tracker on Background Treadh

Your code does not contain any class called MyApplicationName, nor is this class ever instantiated in your code, so how can you call it's methods?

 

Please see my previous post. You need to stop blindly copying code, and spend a little time to understand it.

 

Have you looked at the GPSDemo that ships with the JDE? I think thiswould be a good starting point.

 

 

 

 

Developer
Posts: 108
Registered: ‎01-29-2009
My Device: BlackBerry 8700g
My Carrier: Tigo

Re: GPS Tracker on Background Treadh

Hi Rex,

 

Thanks for your help.

I need any Suggestion, not bad comments.

I have a problem and your post do not have any solution  to my issues. Do you understand my requiremnt or problem in the previous line?

 

Jorge

 

Jorge Luis Frias B

Leader on Development
BlackBerry/iPhone Technologies
Developer
Posts: 713
Registered: ‎05-31-2010
My Device: 8520

Re: GPS Tracker on Background Treadh

Change MyApplicationName().enterEventDispatcher() to Application.getEventLock()