1

我正在尝试创建一个使用 GPS 的 BB 应用程序。

_screen 出现但 _status 没有改变(它总是说“等待位置更新”)。

我用新的 GPS(lugar)创建了对象,但它不起作用。其他 GPS 应用程序正常工作。

这是我的 BB 代码:

package mypackage;


import java.util.*;
import javax.microedition.location.*;

import data.Lugar;

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

public class GPS
{
    // Represents the number of updates over which altitude is calculated, in seconds
    private static final int GRADE_INTERVAL = 5;

    // com.rim.samples.device.gpsdemo.GPSDemo.ID
    private static final long ID = 0x5d459971bb15ae7aL;    

    // Represents period of the position query, in seconds
    private static int _interval = 1;

    private static Vector _previousPoints;
    private static float[] _altitudes;
    private static float[] _horizontalDistances;
    private static PersistentObject _store;

    // Initialize or reload the persisted WayPoints 
    static
    {
        _store = PersistentStore.getPersistentObject(ID);

        if(_store.getContents() == null)
        {
            _previousPoints = new Vector();
            _store.setContents(_previousPoints);
        }

        _previousPoints = (Vector) _store.getContents();
    }

    private long _startTime;
    private float _wayHorizontalDistance;
    private float _horizontalDistance;
    private float _verticalDistance;
    private double latitud;
    private double longitud;
    private double latitud_anterior = 0;
    private double longitud_anterior = 0;
    private RichTextField status;
    private EditField _status;
    private LocationProvider _locationProvider;
    private GPSDemoScreen _screen;
    Lugar destino;

    /**
     * Create a new GPS object
     */
    public GPS(Lugar l)
    {
        destino = l;
        // Used by WayPoints, represents the time since the last waypoint
        _startTime = System.currentTimeMillis();

        _altitudes = new float[GRADE_INTERVAL];
        _horizontalDistances = new float[GRADE_INTERVAL];

        _screen = new GPSDemoScreen();
        _screen.setTitle("GPS Demo");

        _status = new EditField(Field.NON_FOCUSABLE);
        status = new RichTextField("Obteniendo señal GPS...");
        _screen.add(_status);
        _screen.add(status);

        // Attempt to start the location listening thread
        if(startLocationUpdate())
        {
            _screen.setState(_locationProvider.getState());
        }
        // Render the screen
        UiApplication.getUiApplication().pushScreen(_screen);
    }


    /**
     * Update the GUI with the data just received
     * 
     * @param msg The message to display
     */
    private void updateLocationScreen(final String msg)
    {

        _status.setText(msg);

    }


    /**
     * Invokes the Location API with Standalone criteria
     * 
     * @return True if the <code>LocationProvider</code> was successfully started, false otherwise
     */
    private boolean startLocationUpdate()
    {
        boolean returnValue = false;

        if(GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS))
        {
            try
            {
                Criteria criteria = new Criteria();
                criteria.setCostAllowed(false);

                _locationProvider = LocationProvider.getInstance(criteria);

                if(_locationProvider != null)
                {
                    /*
                     * Only a single listener can be associated with a provider,
                     * and unsetting it involves the same call but with null.
                     * Therefore, there is no need to cache the listener
                     * instance request an update every second.
                     */
                    _locationProvider.setLocationListener(new LocationListenerImpl(), _interval, -1, -1);
                    returnValue = true;
                }
                else
                {
                            Dialog.alert("Failed to obtain a location provider, exiting...");
                            System.exit(0);
                }

            }
            catch(final LocationException le)
            {
                        Dialog.alert("Failed to instantiate LocationProvider object, exiting..." + le.toString());
                        System.exit(0);
            }
        }
        else
        {
                    Dialog.alert("GPS autonomous/standalone mode is not supported on this device, exiting...");
                    System.exit(0);
        }

        return returnValue;
    }

    /**
     * Implementation of the LocationListener interface. Listens for updates to
     * the device location and displays the results.
     */
    private class LocationListenerImpl implements LocationListener
    {

        /**
         * @see javax.microedition.location.LocationListener#locationUpdated(LocationProvider,Location)
         */
        public void locationUpdated(LocationProvider provider, Location location)
        {
            if(location.isValid())
            {
                float heading = location.getCourse();
                longitud = location.getQualifiedCoordinates().getLongitude();
                latitud = location.getQualifiedCoordinates().getLatitude();
                float altitude = location.getQualifiedCoordinates().getAltitude();
                float speed = location.getSpeed();

                // Horizontal distance for current Location
                float horizontalDistance = speed * _interval;
                _horizontalDistance += horizontalDistance;

                // Horizontal distance for WayPoint
                _wayHorizontalDistance += horizontalDistance;

                // Distance over the current interval
                float totalDist = 0;

                // Moving average grade
                for(int i = 0; i < GRADE_INTERVAL - 1; ++i)
                {
                    _altitudes[i] = _altitudes[i + 1];
                    _horizontalDistances[i] = _horizontalDistances[i + 1];
                    totalDist = totalDist + _horizontalDistances[i];
                }

                _altitudes[GRADE_INTERVAL - 1] = altitude;
                _horizontalDistances[GRADE_INTERVAL - 1] = speed * _interval;
                totalDist = totalDist + _horizontalDistances[GRADE_INTERVAL - 1];
                float grade = (totalDist == 0.0F) ? Float.NaN : ((_altitudes[4] - _altitudes[0]) * 100 / totalDist);

                // Running total of the vertical distance gain
                float altGain = _altitudes[GRADE_INTERVAL - 1] - _altitudes[GRADE_INTERVAL - 2];

                if(altGain > 0)
                {
                    _verticalDistance = _verticalDistance + altGain;
                }

                // Information to be displayed on the device
                StringBuffer sb = new StringBuffer();
                sb.append("Longitude: ");
                sb.append(longitud);
                sb.append("\n");
                sb.append("Latitude: ");
                sb.append(latitud);
                sb.append("\n");
                sb.append("Grade : ");
                if(Float.isNaN(grade))
                {
                    sb.append(" Not available");
                }
                else
                {
                    sb.append(grade + " %");
                }

                GPS.this.updateLocationScreen(sb.toString());
                //... other things non related to GPS    
            }
        }

        public void providerStateChanged(LocationProvider provider, int newState)
        {
            if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
            {
                provider.reset();
            }
            _screen.setState(newState);
        }
    }

    /**
     * The main screen to display the current GPS information
     */
    private final class GPSDemoScreen extends MainScreen
    {
        TextField _statusTextField;

        /**
         * Create a new GPScreen object
         */
        GPScreen()
        {   
            // Initialize UI
            _statusTextField = new TextField(Field.NON_FOCUSABLE);
            _statusTextField.setLabel("GPS Status: ");
            add(_statusTextField);
            RichTextField instructions = new RichTextField("Waiting for location update...", Field.NON_FOCUSABLE);
            add(instructions);
        }

        public void setState(final int newState)
        {
            UiApplication.getUiApplication().invokeLater(new Runnable()
            {
                public void run()
                {
                    switch(newState)
                    {
                        case LocationProvider.AVAILABLE:
                            _statusTextField.setText("Available");
                            break;
                        case LocationProvider.OUT_OF_SERVICE:
                            _statusTextField.setText("Out of Service");
                            break;
                        case LocationProvider.TEMPORARILY_UNAVAILABLE:
                            _statusTextField.setText("Temporarily Unavailable");
                            break;
                    }
                }
            });
        }


        /**
         * @see net.rim.device.api.ui.Screen#close()
         */
        public void close()
        {
            if(_locationProvider != null)
            {
                _locationProvider.reset();
                _locationProvider.setLocationListener(null, -1, -1, -1);
            }

            super.close();
        }
    }
}
4

0 回答 0