locationlistener

Hello

We need to cancel the registration of the locationlistener leaving as we do the phonelistener?  Thank you

It is recommended to reset the LocationProvider and LocationListener the value null in the output of application (or when the application no longer need them).  Please see the gpsdemo provided with the BlackBerry JDE for an example.

Tags: BlackBerry Developers

Similar Questions

  • Problem stop LocationListener

    Hello guys '

    My development proposal has associated GPS module. In this module, I am facing this problem.

    IE when stops and starts LocationListener, sometimes it can work and sometimes it does not.

    I use to start and stop LocationListener following code:

    private class GpsInternal implements LocationListener {
    
            LocationProvider lp;
    
            public GpsInternal() {      lp = null;    }
    
      public boolean isConnected() {        return (lp != null);  }
    
      public void start() {     if (lp == null) {         try {         lp = LocationProvider.getInstance(null);          if(lp != null) {          lp.setLocationListener(this, _interval, -1, -1);          }         } catch(LocationException e) {                }         }     }
    
      public void stop() {      if (lp != null) {         lp.reset();           lp.setLocationListener(null, -1, -1, -1);         lp = null;            }     }
    
      public void locationUpdated(LocationProvider provider, Location location) {
    
      if(location.isValid()) {  double longitude = location.getQualifiedCoordinates().getLongitude(); double latitude = location.getQualifiedCoordinates().getLatitude();   float altitude = location.getQualifiedCoordinates().getAltitude();        } }
    
      public void providerStateChanged(LocationProvider provider, int newState) {       //Nothing }}
    

    I think that the start() method has no problem. And the stop() method has something wrong. But I don't know what it is.

    If you have the idea to start and stop LocationListener, please share with me.

    TNX all '

    Try the lp.reset () after the lp.setLocationListener (null,-1, -1, -1).

    It's the way that I do and have not had any problems.

  • Stop a thread LocationListener with interrupt()

    Hi all

    Is there a recommended way to stop a thread LocationListener before the end of the interrogation of a GPS?  Currently, I am calling interrupt() on the thread and catch the InterruptedException.  Although it seems to work in my tests, I feel a little uncomfortable to do that.

    Any thoughts?

    "extends thread and implements LocationListener.

    But this does not mean that the LocationListener is a Thread.  All that means the LocationListener runs a method that is placed in the Thread object.  The Thread may or may not be running.  Whether it is or not, is not relevant to the LocationListener.

    So to stop the LocationListener, you must specify the LocationProvider to stop the driving method.

    Who is?

    Regarding your other questions, I am based in the United Kingdom, we have all GSM phones, and I'm always coded to stand-alone mode.  So I can't help with this.  RexDoug has posted on this kind of thing in the past, I think that, maybe it will be chip here.

  • PopupScreen + LocationListener

    I have tried to create a Popup (PopupScreen) that displays "search satellite...". "while I'm waiting for LocationListener to call. Once it is called, I put the location listener to null, and I try to fill the PopupScreen. No matter what I do I can't close. I get an IllegalStateException.

    I looked in the forums, I've seen 100 threads that tell you how to do this, people link to these articles KB, but nothing works. I don't know if I'm just not thinking clearly, but I just can't understand it.

    Basically... I'm trying to do something like:

    screen = new PopupScreen(); pertend this is a message in it

    UiApplication.getUiApplication () .pushScreen (form);

    Critier criteria = new Criteria();

    LocationProvider provider = new LocationProvider.getInstance (criteria);

    provider.setLocationListener (new MyLocationListenerHere (this));

    Then in my MyLocationListenerHere I want to lie...

    MyLocationListener (form) {}

    This.some_holder = screen;

    }

    {public locationUpdated Sub (LocationProvider provider, a place)

    do things for contact information

    UiApplication.getUiApplication () .popScreen (this.some_holder.screen);

    }

    IllegalStateException

    Note: I just write this code now for this post, it gives you a good example of what I'm trying to do. If anyone can help me it would be GREATLY appreciated.

    locationUpdated() runs as a background Thread.  In my view, that it is running in your Application, just to get your pop on your event feed!  Usually, it's pretty easy.  Assuming this works, then that's all you need:

    {public locationUpdated Sub (LocationProvider provider, a place)

    Final anti-pop = this.some_holder.screen;

    UiApplication.getUiApplication () .invokeLater (new Runnable() {}

    public void run() {}

    UiApplication.getUiApplication () .popScreen (anti-pop);

    }

    };

    do things for contact information

    }

    This code is written from memory, not tested, but I hope that you can find in her compilation errors.

    Let us know how you go.

  • LocationListener Vs getLocation GPS coordinates?

    Hello

    Just a quick question.

    I've read several times that the frequent difficulty, to use a LocationListener instead of lp.getLocation (repeated).

    What can be considered "frequent"?

    All the examples I've seen get GPS coordinates every 5 or 10 seconds.

    On my particular application, I do a lp.getLocation () every 15 minutes... but I want to change that to 5 or 10 minutes.

    I have two solutions work, I just would like to know which should I use for a fix every 5 or 10 minutes?  One who takes fewer resources battery and device?

    Thank you!

    I think that locationprovider would be nice in this case.

  • LocationListener does not receive updates when BrowserField 2 renders in 6.0

    I have an application that calls a mobile web site using BrowserField 2.  The application needs make the current GPS position to the mobile website with each request to the site.

    I used code MultipleFixDemo to get a LocationListener job.  Everything worked very well in the Simulator and all manual updates of location were received by the LocationListener in the application.

    I changed the display to include a component BrowserField 2 and the LocationListener does not update the location of the Simulator.

    Y at - it something I need to do something different when the user interface includes the BrowserField.  Can I have some kind of thread problem?  I only tested on OS 6.0 in the Simulator.  I don't have access to a real device.

    In the code below, I have two defined screens.

    If the pushScreen (new MultipleFixScreen() is uncommented and the pushScreen (new BrowserFieldScreen() is commented out, the LocationListener receives updates.)

    If the pushScreen (newMultpleFixScreen () is commented out and the pushScreen (new BrowserFieldScreen() is uncommented, the LocationListener gets no updates.)

    Here is my code:

    public class MultipleFixDemo extends UiApplication
    {
        private double longitude;
        private double latitude;
        BlackBerryLocationProvider myProvider;
    
        public static void main(String[] args)
        {
            new MultipleFixDemo().enterEventDispatcher();
        }
    
        public MultipleFixDemo()
        {
            startLocationUpdate();
    
            pushScreen(new BrowserFieldScreen());
            //pushScreen(new MultipleFixScreen());
        }
    
       private void startLocationUpdate()
        {
            try
            {
                BlackBerryCriteria myCriteria = new BlackBerryCriteria();
                myCriteria.enableGeolocationWithGPS(BlackBerryCriteria.FASTEST_FIX_PREFERRED);
                try
                {
                    myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria);
    
                    if ( myProvider == null )
                    {
                        Runnable showUnsupportedDialog = new Runnable()
                        {
                            public void run() {
                                Dialog.alert("Location service unsupported, exiting...");
                                System.exit( 1 );
                            }
                        };
                        invokeLater( showUnsupportedDialog );
                    }
                    else
                    {
                        myProvider.setLocationListener(new LocationListenerImpl(), 2, -1, -1);
    
                    }
                }
                catch (LocationException le)
                {
                    System.err.println("Failed to retrieve a location provider");
                    System.err.println(le);
                    System.exit(0);
                }
            }
            catch (UnsupportedOperationException ue)
            {
                System.err.println("Require mode is unavailable");
                System.err.println(ue);
                System.exit(0);
            }
            return;
        }
    
        private class LocationListenerImpl implements LocationListener
        {
            public void locationUpdated(LocationProvider provider, Location location)
            {
                System.out.println("update location called");
                if(location.isValid())
                {
                    longitude = location.getQualifiedCoordinates().getLongitude();
                    latitude = location.getQualifiedCoordinates().getLatitude();
                    float altitude = location.getQualifiedCoordinates().getAltitude();
    
                    StringBuffer sb = new StringBuffer();
                    sb.append("Longitude: ");
                    sb.append(longitude);
                    sb.append("\n");
                    sb.append("Latitude: ");
                    sb.append(latitude);
                    sb.append("\n");
                    sb.append("Altitude: ");
                    sb.append(altitude);
                    sb.append(" m");
                    System.out.println("!!!!!!!Location update: " + sb.toString());
                    //MultipleFixDemo.this.updateLocationScreen(sb.toString());
                }
            }
    
            public void providerStateChanged(LocationProvider provider, int newState)
            {
                System.out.println("providerStateChanged called");
                // Not implemented
            }
        }
    
        class BrowserFieldScreen extends MainScreen
        {
            private BrowserField _browserField;
            private boolean _documentLoaded = false;
            private BrowserFieldRequest _request;
    
            /**
             * Creates a new BrowserFieldScreen object
             * @param request The URI of the content to display in this BrowserFieldScreen
             * @param enableScriptMenu True if a context menu is to be created for this BrowserFieldScreen instance, false otherwise
             */
            public BrowserFieldScreen()
            {
                super(Screen.HORIZONTAL_SCROLL | DEFAULT_CLOSE | DEFAULT_MENU);
                BrowserFieldRequest request = new BrowserFieldRequest("http://www.google.com");
    
                BrowserFieldConfig config = new BrowserFieldConfig();
                _browserField = new BrowserField(config);
                _browserField.addListener(new DemoBrowserListener());
                add(_browserField);
                _request = request;
            }    
    
            /**
             * @see Screen#onUiEngineAttached(boolean)
             */
            protected void onUiEngineAttached(boolean attached)
            {
                if(attached)
                {
                    try
                    {
                        _browserField.requestContent(_request);
                    }
                    catch(Exception e)
                    {
                        deleteAll();
                        add(new LabelField("ERROR:\n\n"));
                        add(new LabelField(e.getMessage()));
                    }
                }
            }
    
            /**
             * Returns this screen's BrowserField object
             * @return This screen's BrowserField object
             */
            public BrowserField getBrowserField()
            {
                return _browserField;
            }
    
            /**
             * A class to listen for BrowserField events
             */
            private class DemoBrowserListener extends BrowserFieldListener
            {
                /**
                 * @see BrowserFieldListener#documentCreated(BrowserField, ScriptEngine, Document)
                 */
                public void documentLoaded(BrowserField browserField, Document document)
                {
                    _documentLoaded = true;
                }
            }
        }
        private final static class MultipleFixScreen extends MainScreen
        {
            MultipleFixScreen()
            {
                super(DEFAULT_CLOSE | DEFAULT_MENU);
    
                RichTextField instructions = new RichTextField("Waiting for location update...",Field.NON_FOCUSABLE);
                this.add(instructions);
            }
        }
    }
    

    Any suggestions would be greatly appreciated.

    Thank you

    Jackie

    This is a limitation of the BrowserField.  The BrowserField also recorded a LocationListener that is use to power the GPS updates via JavaScript to pages it restores.  This LocationListener / that your application has already registered (given that the application can only record 1).

    There are two ways you can work around this problem.  You can save your LocationListener again after posting the BrowserField.  Note that if you take this approach methods JavaScript GPS won't within your BrowserField.

    The second approach is to poll for updates location, instead of using a LocationListener.  It should continue to work after posting a BrowserField.

  • Implementation of locationlistener MIDlet has no effect on jde 4.5.0 or curve 8310

    Hello to the blackberry,

    you try to run the midlet on the jde 4.5.0 or on my 8310 device does nothing (no coordinates and no error).

    I am able to run the method-getLocation(-1) of rental in the most complex midlets,

    but not the locationListener in this very simple (see the following code).

    Why? According to me, it takes a very small thing to make it work.

    I must be blind or...? ;-)

    Thank you very much for your help.

    Christoph rappp

    package fortab;

    Javax.microedition.midlet import. *;
    Javax.microedition.lcdui import. *;
    Javax.microedition.location import. *;

    public class fortab extends MIDlet implements CommandListener, Runnable, LocationListener
    {
    Private TextBox infoBox = new TextBox("Info",null,5000,TextField.ANY);
    CMD_EXIT private final order = new Command("Ende",Command.EXIT,0);
    Private final command CMD_LOCATION = new command ("Position", Command.ITEM, 1);

    protected void pauseApp() {}

    protected void destroyApp (boolean arg0) {}

    ' Public Sub locationUpdated (LocationProvider provider, a place)
    {
    Coordinates of c = location.getQualifiedCoordinates ();
    If (c! = null)
    displayText ("lat" + c.getLatitude () + "lon" + c.getLongitude () + "alt" + c.getAltitude()+"\n\r");
    }

    ' Public Sub providerStateChanged (LocationProvider provider, int newState)
    {
    }

    protected void startApp()
    {
    infoBox.addCommand (CMD_EXIT);
    infoBox.addCommand (CMD_LOCATION);
    infoBox.setCommandListener (this);
    Display.getDisplay (this) .setCurrent (infoBox);
    }

    public void commandAction (command c, displayable d)
    {
    If (c is CMD_EXIT)
    notifyDestroyed();

    If (c is CMD_LOCATION)
    New Thread (this) m:System.NET.HttpListener.start ();
    }

    Private Sub displayText (String str)
    {
    infoBox.insert (str, infoBox.size ());
    Display.getDisplay (this) .setCurrent (infoBox);
    }

    public void run()
    {
    Try
    {
    Cr criteria = new Criteria();
    cr.setHorizontalAccuracy (500);
    LP LocationProvider = LocationProvider.getInstance (cr);
    If (lp! = null)
    {
    infoBox.removeCommand (CMD_LOCATION);
    lp.setLocationListener (this,-1, -1, -1);
    }
    }
    catch (System.Exception e)
    {
    displayText (e.getMessage ());         }
    }
    }

    Thank you for motivating words, david.

    After all try for the last days, I finally changed the - 1 to 1 and GOT a FIX.

    Thank you.

    Good day.

    Christoph rapp

  • Problem with LocationListener availability and network on Storm 9530 Simulator

    Having an interesting problem. I have an application with a locationlistener which works fine on "BOLD" and curve (Simulator and device) and 9500 Simulator. Try to make it work on a Verizon 9530. It * used * to work fine, but now the question I have is this: in the Simulator (9530-Verizon 4.7.0.148 and 9530-JRE that comes with the 4.7 eclipse plugin), if the CDMA network is turned on, I only get invalid places every 15 seconds. As soon as I disable the network (by unchecking it in the simulation/network properties dialog) I can get a good location every second, as it should. If I then select the network locations stop again.

    Pulling my hair out, any ideas?

    OK, solved my problem, I had the incorrect criteria to work with the Verizon Storm discovered. Yet, very strange behavior.

  • Listener GPS problem

    Hi people,

    In collaboration with 4.2.1 on the 8800 Simulator.  My application is currently composed of two separate applications, app UI to obtain/view the information and a 'replication' application that communicates with our backend. I want to be able to include location on request of the user data (in the application user interface) and once it is updated, have replication app send it to the server. I have this work especially to my satisfaction, but the following problem: when I close the application user interface, any incomplete GPS please never finished. It seems that my LocationListener is not registered, or maybe the listener Thread is killed the closure of the part of the user interface. I don't expect that the instance is stored in the runtimestore and the object that is saved as the listener is always valid. Here's how I set it up:

    App of the user interface, the following is performed from a menu, click:

                GPSUpdater gps = GPSUpdaterFactory.getGPSUpdater();            gps.getGPSData(row, GPSUpdater.CHECK_IN);
    

    Replication App: (cut a lot of independent code)

    class ReplicationManagerImpl implements LocationListener{    private GPSUpdater mGPSUpdater;
    
        ReplicationManagerImpl()    {        mGPSUpdater = GPSUpdaterFactory.getGPSUpdater();        mGPSUpdater.setListener(this);    }
    
        public void locationUpdated(LocationProvider provider, Location location)    {        mGPSUpdater.newLocationReceived(location);    }
    
        public void providerStateChanged(LocationProvider provider, int newState)    {        //Not worried about this    }}
    

    GPSUpdater:

    public class GPSUpdater{    private Vector mUpdates;    private LocationProvider mProvider;    private Location mLocation;    private LocationListener mListener;    private Boolean isAcquiring;    private int mCounter;
    
        private static final int MAX_RETRIES = 10;    public static final int CHECK_IN = 0;    public static final int CONFIRM = 1;
    
        private static class UpdateData    {        private DataRow suRow;        private int updateType;        private long timeStamp;    }
    
        GPSUpdater()    {        Criteria criteria = new Criteria();        criteria.setHorizontalAccuracy(50);        criteria.setVerticalAccuracy(50);        criteria.setCostAllowed(false);        try        {            mProvider = LocationProvider.getInstance(criteria);            if (mProvider.getState() == LocationProvider.OUT_OF_SERVICE)            {                SubsystemLog.log("GPS actions not supported", EventLogger.ALWAYS_LOG);            }        }        catch (LocationException lEx)        {            SubsystemLog.log("Error creating LocationProvider in GPSUpdater: " + lEx.getMessage(), EventLogger.ERROR);        }        mUpdates = new Vector();        mLocation = null;        isAcquiring = Boolean.FALSE;        mCounter = 0;    }
    
        public void setListener(LocationListener listener)    {        mListener = listener;    }
    
        public void getGPSData(DataRow row, int updateType)    {        long timestamp = System.currentTimeMillis();        if (((mLocation != null) && (mLocation.isValid()) && (mLocation.getTimestamp() > timestamp - 60000)) || (mProvider == null) || (mProvider.getState() == LocationProvider.OUT_OF_SERVICE))        {            UpdateRow(row, updateType, timestamp);        }        else        {            UpdateData update = new UpdateData();            update.row = row;            update.updateType = updateType;            update.timeStamp = timestamp;
    
                synchronized(mUpdates)            {                mUpdates.addElement(update);            }
    
                synchronized(isAcquiring)            {                if (!isAcquiring.booleanValue())                {                    mProvider.setLocationListener(mListener, 5, 5, -1);                    isAcquiring = Boolean.TRUE;                }            }        }    }
    
        public void newLocationReceived(Location location)    {        if ((location == null) || (!location.isValid()) && (mCounter < MAX_RETRIES))        {            mCounter++;            return;        }
    
            mCounter = 0;        mLocation = location;        SubsystemLog.log("Acquired co-ordinates: " + Double.toString(location.getQualifiedCoordinates().getLatitude()) + "," + Double.toString(location.getQualifiedCoordinates().getLongitude()), EventLogger.DEBUG_INFO);
    
            Database db = DataSystemFactory.getDataSystem().openDatabase(DBSchema.NAME);        Object syncObject = db.getSyncObject();
    
            synchronized(syncObject)        {            while (mUpdates.size() > 0)            {                UpdateData update = (UpdateData)mUpdates.elementAt(0);                UpdateRow(update.row, update.updateType, update.timeStamp);                mUpdates.removeElement(update);            }        }        db.commitAndNotify();
    
            synchronized(isAcquiring)        {            provider.setLocationListener(null, -1, -1, -1);            isAcquiring = Boolean.FALSE;        }    }
    
        private void UpdateRow(DataRow suRow, int updateType, long timeStamp)    {        //wrapper class to allow persisting double values        DBDouble latitude = new DBDouble();        DBDouble longitude = new DBDouble();
    
            if (mLocation != null && mLocation.isValid())        {            latitude.setDouble(mLocation.getQualifiedCoordinates().getLatitude());            longitude.setDouble(mLocation.getQualifiedCoordinates().getLongitude());        }        else        {            latitude.setDouble(0.0);            longitude.setDouble(0.0);        }
    
            //store data here    }
    
    }
    

    GPSUpdaterFactory:

    public abstract class GPSUpdaterFactory {    private static final long ID = ;
    
        public static final GPSUpdater getGPSUpdater()    {        Object o;        GPSUpdater gpsUpdater = null;        RuntimeStore runtimeStore = RuntimeStore.getRuntimeStore();        synchronized (runtimeStore)        {            o = runtimeStore.get(ID);            if (o != null)            {                if (o instanceof GPSUpdater)                {                    gpsUpdater = (GPSUpdater)o;                }            }            if (gpsUpdater == null)            {                gpsUpdater = new GPSUpdater();                runtimeStore.put(ID, gpsUpdater);            }        }        return gpsUpdater;            }}
    

    Any suggestions are greatly appreciated.

    Thank you

    Mike

    Notice that the menu close item also called System.exit.

    In this case the application would stop receiving updates following the call of output.  To work around this problem, you can call Application.requestBackground.  This moves the application in the background, where it can continue to operate.  Once you have your final fix application can call System.exit to close itself.

  • TimerTasks battery drain!

    Hi gurus

    I am developing a project that has 2 main parts: the graphical interface and a background process. I do this with the help of another point of entry for the GUI. The background process starts automatically and the GUI is started using an application icon.

    What is the background process is 3 things:

    1. GPS location of the registry every 10 minutes
    2. Send GPS positions stored each hour to consume a web service (HttpConnection)
    3. Check if the user has saved records and send them to a server with the web services every hour.

    Sorry haven't looked hard to your code, but I see nothing that resets the LocationListener.  So I wonder if in fact the GPS is disabled?

    Memory, to stop a LocationListener, you need to do

    mLocProvider.setLocationListener (null, 1, 1, 1);

    I could be wrong, but I don't think that canceling the TimerTask will do that.

    I understand that there is advantage also made a getLocation() before departure using a LocationListener, to make sure that the GPS actually works.  But it would make your TimerTask blocking, and I'm not sure you want to do.

  • Calculation of the distance of the location GPS provider

    I'm looking to develop an application of GPS based location by saving a LocationListener with the LocationProvider, I need to be able to calculate the distance between two cooridinates.

    The Coordinates () .distance method doesn't seem to work, also responds to 0.

    I saw and distance example where speed and range were used to calculate, but I was wondering is this reliable?

    An alternative is to calculate the distance between two coordinates using the Haversine formula, the java class Math in Blackberry JDE however does not have the required operation atan2. Anyone know of any alternative?

    Thank you

    Dave

    In my experience, the distance calculation works.  What results are you seeing?  Are you sure these two places are valid?

    I would not use speed and interval unless there is no other choice, or that the interval was small.

    The quesiton on atan was invited to this forum, have a search for her.  Here is an answer:

    BB has no ACON, ATAN, ASIN

    http://supportforums.BlackBerry.com/Rim/Board/message?board.ID=java_dev&message.ID=142&query.ID=2195...

  • providerStateChanged... again

    Never get called the providerStateChanged method?

    I've disabled GPS and disabled location caregiver.

    Still my app still does not call the method in the class that implements LocationListener.

    Thanks for the suggestion. That will keep in reserve, don't really like to do workaround when it appears something like cut and dry that the method is never executed. I would like to use the providerStateChanged method as it was designed/intended.

    Are you aware of what is a bug or I use it wrong?

    Thank you.

    BUG - see thread http://supportforums.blackberry.com/t5/Java-Development/locationProvider-getLocation-re-creating/m-p...

    Created the: March 25, 10 15:55 updated: 22 Apr 10 15:33
    Return the search of
    Number 1 of 2 issue (s)
  • GPS returns for speed and longitude 0.0

    I get 0.0 for the speed (except NaN invalid) and longitude.  Latitude and journey to return a valid number. It's on a Torch 9810 OS7 but the app is defined for the OS6.  Look in the console attached through Eclipse,

    public class LocationListener implements javax.microedition.location.LocationListener{
    
        private static long lastFix = 0l;
        private static Object lock = new Object();
    
        public void locationUpdated(LocationProvider provider, Location location) {
            try {
                BlackBerryLocation loc = (BlackBerryLocation) location;
                double longitude = 0d;
                double latitude = 0d;
                if (loc.getQualifiedCoordinates() != null) {
                    longitude = loc.getQualifiedCoordinates().getLongitude();
                    latitude = loc.getQualifiedCoordinates().getLatitude();
                }
                float speed = loc.getSpeed();
                float course = loc.getCourse();
                setLastFix(loc.getTimestamp());
                GPSLocation gps = new GPSLocation(longitude, latitude, speed, course, (loc.getTimestamp() == 0l ? System.currentTimeMillis() : loc.getTimestamp()));
                gps.setValid(loc.isValid());
                gps.setStatus(loc.getStatus());
                gps.setError(loc.getError());
                gps.print();
                App.addToPool(gps);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public void providerStateChanged(LocationProvider provider, int newState) {
            if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE) {
                provider.reset();
                provider.setLocationListener(null, 0, 0, 0);
            }
            App.setupGpsPolling();
        }
    
        public static void setLastFix(long lastFix) {
            synchronized (lock) {
                if (lastFix != 0l)
                    LocationListener.lastFix = lastFix;
            }
        }
    
        public static long getLastFix() {
            synchronized (lock) {
                return lastFix;
            }
        }
    
    }
    
    public class GPSLocation {
        ......
        public void print() {
            StringBuffer sb = new StringBuffer();
            sb.append("longitude: " + getLongitude()).append("\r\n");
            sb.append("latitude: " + getLatitude()).append("\r\n");
            sb.append("speed: " + getSpeed()).append("\r\n");
            sb.append("course: " + getCourse()).append("\r\n");
            sb.append("ts: " + getTimestamp()).append("\r\n");
            sb.append("stat: " + getStatus()).append("\r\n");
            sb.append("err: " + getError()).append("\r\n");
            sb.append("valid: " + isValid()).append("\r\n");
            System.out.println(sb.toString());
        }
        ......
    }
    

    I don't understand.  Do works that way.

               QualifiedCoordinates coor = location.getQualifiedCoordinates();
                if (coor != null) {
                    longitude = coor.getLongitude();
                    latitude = coor.getLatitude();
                    }
    
  • Cannot find the location of the gps on the device

    in my application, I'm trying to find the location of the user.my code owrks in Simulator for the curve8300 and the 9000 "BOLD"

    but he does not get the cordinates on the device even though I update the gps manually using the options--> options--> gps.

    What to do

     package com.MyChamberApp;
    
        import javax.microedition.location.Criteria;
        import javax.microedition.location.Location;
        import javax.microedition.location.LocationListener;
        import javax.microedition.location.LocationProvider;
    
        public class GPS_Location {
         static double longi;
         static double lati;
    
         public GPS_Location() {
    
         }
    
         public void location()
         {
          new LocationTracker();
         }
    
         class LocationTracker
         {
          private LocationProvider provider;
          Criteria cr;
    
          public LocationTracker()
          {
           resetGPS();
          }
    
          public void resetGPS() {
    
          try {
          cr = new Criteria();
          cr.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
          cr.setPreferredResponseTime(120000);
                    cr.setCostAllowed(true);
          provider = LocationProvider.getInstance(cr);
          provider.getLocation(120);
          if (provider != null)
           {
            provider.setLocationListener(new MyLocationListener(), 1,1,1);
           }
          } catch (Exception e) {}
    
          }
    
          public void run(){}
    
         private class MyLocationListener implements LocationListener
             {
           public void providerStateChanged(LocationProvider provider,int newState)
           {
            if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
            {
              provider.reset();
              resetGPS();
            }
           if (newState == LocationProvider.OUT_OF_SERVICE)
           {
            provider.reset();
            resetGPS();
           }
         }
    
         public void locationUpdated(LocationProvider provider,Location location)
          {
           if (location != null && location.isValid()) {
            try {
          lati = location.getQualifiedCoordinates().getLatitude();
          longi = location.getQualifiedCoordinates().getLongitude();
             } catch (Exception e) {}
         }
          }
        }
       }
     }
    

    Although the code seems fine for me, check with this code...

    Criteria criteria = new Criteria();
    
    criteria.setHorizontalAccuracy(50);
                criteria.setVerticalAccuracy(50);
                criteria.setCostAllowed(true);
                criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
                _locationProvider = LocationProvider.getInstance(criteria);
                  Location location =_locationProvider.getLocation(-1);
                _longitude = location.getQualifiedCoordinates().getLongitude();
                _latitude = location.getQualifiedCoordinates().getLatitude();
                 _altitude = location.getQualifiedCoordinates().getAltitude();
                 _speed = location.getSpeed();
                if(_locationProvider!=null)
                 {
                  _locationProvider.setLocationListener(new LocationListenerImpl(), _interval, 1, 1);
    
                }
    
  • GPS of the poll seems to block on setLocationListener

    I try to start the GPS of the poll, but setLocationListener seems to hang.  The application just hangs there.  It's on a device of Torch 9810.  I use 6 SDK.  I don't get any errors, it just seems to stop.  After MUCH research, I came up with this:

    I have static variables of provider and criteria in my main application class.

    To start the voting, the word is setupGpsPolling();

    I put a listener of the situation with my interval.

    I have a thread that checks the latest patch.  If the time is more than 20 minutes, it resets by calling setupGpsPolling();

    In my main application class:

       private static BlackBerryLocationProvider _provider = null;
        private static BlackBerryCriteria _criteria;
    ......
    
        public static void setupGpsPolling() {
            LocationInfo.setLocationOn();
            if (_provider != null) {
                _provider.setLocationListener(null, 0, 0, 0);
                _provider.reset();
                _provider = null;
            }
    
            try {
                _criteria = new BlackBerryCriteria();
                _criteria.setGPSRestartInterval(600, 0);
                _criteria.setSpeedAndCourseRequired(true);
                _provider = (BlackBerryLocationProvider) LocationProvider.getInstance(_criteria);
                _provider.setLocationListener(new LocationListener(), 300, -1, 0);
            } catch (LocationException e) {
                System.out.println(e.getMessage());
            }
        }
    

    LocationListener

    public class LocationListener implements javax.microedition.location.LocationListener{
    
        private static long lastFix = 0l;
        private static Object lock = new Object();
    
        public void locationUpdated(LocationProvider provider, Location location) {
            try {
                BlackBerryLocation loc = (BlackBerryLocation) location;
                double longitude = location.getQualifiedCoordinates().getLongitude();
                double latitude =location.getQualifiedCoordinates().getLatitude();
                float speed = location.getSpeed();
                float course = location.getCourse();
                setLastFix(location.getTimestamp());
                GPSLocation gps = new GPSLocation(longitude, latitude, speed, course, location.getTimestamp());
                gps.setStatus(loc.getStatus());
                gps.setError(loc.getError());
                gps.process();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    
        public void providerStateChanged(LocationProvider provider, int newState) {
    
        }
    
        public static void setLastFix(long lastFix) {
            synchronized (lock) {
                LocationListener.lastFix = lastFix;
            }
        }
    
        public static long getLastFix() {
            synchronized (lock) {
                return lastFix;
            }
        }
    
    }
    

    My thread checker:

    public class GPSThread extends Thread {
    
        public GPSThread() {
        }
    
        public void run() {
            while (true) {
                try {
                    Thread.sleep(300000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if ((System.currentTimeMillis() - LocationListener.getLastFix()) > (20 * 60 * 1000)) {
                    App.setupGpsPolling(); //reset our location listener
                }
            }
    
        }
    }
    
    _provider.setLocationListener(new LocationListener(), 300, -1, 0)
    

    Should have been

    _provider.setLocationListener(new LocationListener(), 300, -1, -1)
    

Maybe you are looking for