4

我正在尝试通过单击按钮来刷新当前位置。该位置可以通过 GPS 或手机信号塔获取,无论哪个可用。我的问题是我从来没有看到“加载屏幕”。我知道当坐标保持为零时,它会立即出现/关闭。有人可以帮助我 - 我在下面做错了什么?

位置不会更新,加载屏幕也不会出现。在没有加载屏幕的情况下,通过多次单击“刷新按钮”,我确实得到了位置。下面是我处理点击“刷新按钮”的代码:

FieldChangeListener refreshImgListener = new FieldChangeListener() {   
    public void fieldChanged(Field field, int context) 
    {
        Thread backgroundWorker = new Thread(new Runnable() {
            public void run() {
                refreshCoordinates();
            }
        });
        busyDialog.setEscapeEnabled(false);  
        busyDialog.show();
        backgroundWorker.start();
    }
};

我的refreshCoordinates()方法如下:

public void refreshCoordinates() {
    do
    {
        getLatitude(handleeGPS.latitude);
        getLongitude(handleeGPS.longitude);
    } while ((longi == "0.0" || lati == "0.0") || (longi.length() == 0 || lati.length()==0));

    UiApplication.getUiApplication().invokeLater( new Runnable()
    {
        public void run ()
        {
            lblLatitude.setText(lati);
            lblLongitude.setText(longi);
            busyDialog.cancel();
        }
    } );
}

public static String getLatitude(double value) 
{
    lati= Double.toString(value);
    return lati;
}
public static String getLongitude(double value) 
{
    longi= Double.toString(value);
    return longi;
}

返回纬度和经度值的类:

public class handleeGPS{

    static GPSThread gpsThread;
    public static double latitude;
    public static double longitude;

    public handleeGPS(){
        gpsThread = new GPSThread();
        gpsThread.start();
    }

    private static class GPSThread extends Thread{
        public void run() {
            Criteria myCriteria = new Criteria();
            myCriteria.setCostAllowed(false);
            int m_bbHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs");
            if(m_bbHandle>0){
                try {
                    int cellID = GPRSInfo.getCellInfo().getCellId();
                    int lac = GPRSInfo.getCellInfo().getLAC();
                    String urlString2 = "http://www.google.com/glm/mmap";
                    // Open a connection to Google Maps API
                    ConnectionFactory connFact = new ConnectionFactory();
                    ConnectionDescriptor connDesc;
                    connDesc = connFact.getConnection(urlString2);
                    HttpConnection httpConn2;
                    httpConn2 = (HttpConnection)connDesc.getConnection();
                    httpConn2.setRequestMethod("POST");
                    // Write some custom data to Google Maps API
                    OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
                    WriteDataGoogleMaps(outputStream2, cellID, lac);
                    // Get the response
                    InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
                    DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
                    // Interpret the response obtained
                    dataInputStream2.readShort();
                    dataInputStream2.readByte();
                    int code = dataInputStream2.readInt();
                    //Dialog.alert(code+"");
                    if (code == 0) {
                        latitude= dataInputStream2.readInt() / 1000000D;
                        longitude=dataInputStream2.readInt() / 1000000D;
                        //Dialog.alert(latitude+"-----"+longitude);
                        dataInputStream2.readInt();
                        dataInputStream2.readInt();
                        dataInputStream2.readUTF();
                    } else {
                        System.out.println("Error obtaining Cell Id ");
                    }
                    outputStream2.close();
                    inputStream2.close();
                } catch (Exception e) {
                    System.out.println("Error: " + e.getMessage());
                }
            } else {
                try {
                    LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
                    try {
                        Location myLocation = myLocationProvider.getLocation(300);
                        latitude  = myLocation.getQualifiedCoordinates().getLatitude();
                        longitude = myLocation.getQualifiedCoordinates().getLongitude();
                        if(latitude==0.0 && longitude==0.0){
                            try {
                                int cellID = GPRSInfo.getCellInfo().getCellId();
                                int lac = GPRSInfo.getCellInfo().getLAC();
                                String urlString2 = "http://www.google.com/glm/mmap";
                                // Open a connection to Google Maps API
                                ConnectionFactory connFact = new ConnectionFactory();
                                ConnectionDescriptor connDesc;
                                connDesc = connFact.getConnection(urlString2);
                                HttpConnection httpConn2;
                                httpConn2 = (HttpConnection)connDesc.getConnection();
                                httpConn2.setRequestMethod("POST");
                                // Write some custom data to Google Maps API
                                OutputStream outputStream2 = httpConn2.openOutputStream();
                                //getOutputStream();
                                WriteDataGoogleMaps(outputStream2, cellID, lac);
                                // Get the response
                                InputStream inputStream2 = httpConn2.openInputStream();
                                //getInputStream();
                                DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
                                // Interpret the response obtained
                                dataInputStream2.readShort();
                                dataInputStream2.readByte();
                                int code = dataInputStream2.readInt();
                                //Dialog.alert(code+"");
                                if (code == 0) {
                                    latitude= dataInputStream2.readInt() / 1000000D;
                                    longitude=dataInputStream2.readInt() / 1000000D;
                                    //Dialog.alert(latitude+"-----"+longitude);
                                    dataInputStream2.readInt();
                                    dataInputStream2.readInt();
                                    dataInputStream2.readUTF();
                                } else {
                                    System.out.println("Error obtaining Cell Id ");
                                }
                                outputStream2.close();
                                inputStream2.close();
                            } catch (Exception e) {
                                System.out.println("Error: " + e.getMessage());
                            }
                        }
                    }
                    catch ( InterruptedException iex ) {
                        return;
                    }
                    catch ( LocationException lex ) {
                        return;
                    }
                } catch ( LocationException lex ) {
                    return;
                }
            }
            return;
        }
    }

    private static void WriteDataGoogleMaps(OutputStream out, int cellID, int lac)
    throws IOException {
        DataOutputStream dataOutputStream = new DataOutputStream(out);
        dataOutputStream.writeShort(21);
        dataOutputStream.writeLong(0);
        dataOutputStream.writeUTF("en");
        dataOutputStream.writeUTF("Android");
        dataOutputStream.writeUTF("1.0");
        dataOutputStream.writeUTF("Web");
        dataOutputStream.writeByte(27);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(3);
        dataOutputStream.writeUTF("");
        dataOutputStream.writeInt(cellID);
        dataOutputStream.writeInt(lac);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.flush();
    }
}
4

3 回答 3

5

好的,虽然我的原始答案是有效的,但您发布的代码存在一些不同的问题,所以我发布了第二个答案。有很多看起来不正确的东西,我只是重写了你的handleeGPS课程。我将一一解释我所做的主要更改:

  1. 尝试使用Java 命名约定。这使我们更容易为您提供帮助。在您将代码发布到您的handleeGPS类之前,我认为它是一个变量,因为小写名称通常用于变量,而不是类。

  2. 避免重复代码。该handleeGPS课程有很多代码要通读,但大部分是从 Google 的网络服务获取位置的代码,您在两个地方重复了这些代码。只需创建一个只包含该代码的方法,然后调用它两次。

  3. 我将您的handleeGPS课程重命名为GPSHandler. 我不确定这是否handlee是一个错误,或者这是否是您使用的另一种语言中的一个词。无论如何,名称至少应该以大写字母开头。

  4. 避免大量的static变量和方法。有时,真的应该只有其中之一。GPS 处理类可能是一个很好的例子,因为该设备只有一个 GPS 系统。但是,要强制执行此代码结构,请不要将所有内容标记为static. 只需将类设为 Singleton 即可,这仅涉及创建一个static成员变量 ( _instance) 和一个静态方法 ( getInstance())。在我的代码中,您将像这样访问该类:GPSHandler gps = GPSHandler.getInstance();.

  5. 我相信您对是否安装了 BB 地图的检查实际上是倒退的。您查看了该net_rim_bb_lbs模块,如果它大于零(这意味着安装了 BB 地图),那么您就直接访问了 Google 网络服务。我认为您希望反过来(如果安装了 BB 地图,请尝试设备 GPS)。此外,从 6.0 开始,您还需要检查net_rim_bb_maps.

  6. 在您发布更新之前,我认为您的getLatitude()getLongitude()方法实际上是在获取设备位置。这对我来说是一个糟糕的假设。他们只是将数字转换为字符串。因此,没有理由在后台(使用Thread)完成此操作。您已经编写handleeGPS了使用后台线程的类,这很好。一个后台线程就足够了。使用位置信息的 UI 也不需要背景Thread。我更改了代码以添加GPSListener接口。该接口应该由您的 UI 代码实现,以接收位置更新。没有理由继续循环,询问位置是否不等于 {0.0, 0.0}。那是低效的。使用我的代码,您只会在位置发生变化时收到通知。

  7. 原始代码不是线程安全的。handleeGPS latitudelongitude变量在后台线程上设置,并在 UI 线程上访问。那不安全。两个线程不应该同时读取和写入同一条数据。通过更改将位置数据推送到 的代码GPSListener,可以避免此问题。

  8. 我取消了Dialog.alert()您在handleeGPS课堂上的代码的注释,这对您不起作用,因为您不允许从后台进行 UI 调用。我包围了这些电话,UiApplication.getUiApplication().invokeLater()以确保它们安全。

要使用此类,请在您的 UI 代码中的某处执行此操作,而不是使用 aThread来运行您的refreshCoordinates()方法:

public void fieldChanged(Field field, int context) 
    // this is called when your location refresh button is clicked
    GPSHandler.getInstance().setListener(this); 
    GPSHandler.getInstance().requestLocationUpdates();
    busyDialog.setEscapeEnabled(false);  
    busyDialog.show();
}

...

public void onLocationReceived(Coordinates location) {
    lblLatitude.setText(Double.toString(location.getLatitude()));               
    lblLongitude.setText(Double.toString(location.getLongitude()));               
    busyDialog.cancel();               
}     

确保您放置该代码(上面)的类也是implements GPSListener一个接口,在此处定义:

public interface GPSListener {
    public void onLocationReceived(Coordinates location);
}

最后是GPSHandler

public class GPSHandler { 

   private GPSThread _gpsThread;
   private Coordinates _location;
   private boolean _gotLocation;
   private GPSListener _listener;

   /** this class will be a Singleton, as the device only has one GPS system */
   private static GPSHandler _instance;

   /** @return the Singleton instance of the GPSHandler */
   public static GPSHandler getInstance() {
      if (_instance == null) {
         _instance = new GPSHandler();
      }
      return _instance;
   }

   /** not publicly accessible ... use getInstance() */
   private GPSHandler() { 
   }

   /** call this to trigger a new location fix */
   public void requestLocationUpdates() {
       if (_gpsThread == null || !_gpsThread.isAlive()) {
          _gpsThread = new GPSThread();
          _gpsThread.start(); 
       }
   }

   public void setListener(GPSListener listener) {
      // only supports one listener this way
      _listener = listener;   
   }

   private void setLocation(final Coordinates value) {
      _location = value;
      if (value.getLatitude() != 0.0 || value.getLongitude() != 0.0) {
         _gotLocation = true;
         if (_listener != null) {
            // this assumes listeners are UI listeners, and want callbacks on the UI thread:
            UiApplication.getUiApplication().invokeLater(new Runnable() {
               public void run() {
                  _listener.onLocationReceived(value);
               }
            });
         }
      }
   }

   private class GPSThread extends Thread {

      private void getLocationFromGoogle() {
         try { 
            int cellID = GPRSInfo.getCellInfo().getCellId(); 
            int lac = GPRSInfo.getCellInfo().getLAC(); 

            String urlString2 = "http://www.google.com/glm/mmap"; 

            // Open a connection to Google Maps API  
            ConnectionFactory connFact = new ConnectionFactory(); 
            ConnectionDescriptor connDesc; 
            connDesc = connFact.getConnection(urlString2); 

            HttpConnection httpConn2; 
            httpConn2 = (HttpConnection)connDesc.getConnection(); 
            httpConn2.setRequestMethod("POST"); 

            // Write some custom data to Google Maps API  
            OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream(); 
            writeDataGoogleMaps(outputStream2, cellID, lac); 

            // Get the response   
            InputStream inputStream2 = httpConn2.openInputStream();//getInputStream(); 
            DataInputStream dataInputStream2 = new DataInputStream(inputStream2); 

            // Interpret the response obtained  
            dataInputStream2.readShort(); 
            dataInputStream2.readByte(); 

            final int code = dataInputStream2.readInt(); 
            UiApplication.getUiApplication().invokeLater(new Runnable() {
               public void run() {
                  Dialog.alert(code + "");   
               }
            });                        

            if (code == 0) { 
               final double latitude = dataInputStream2.readInt() / 1000000D; 
               final double longitude = dataInputStream2.readInt() / 1000000D; 
               setLocation(new Coordinates(latitude, longitude, 0.0f));

               UiApplication.getUiApplication().invokeLater(new Runnable() {
                  public void run() {
                     Dialog.alert(latitude+"-----"+longitude);   
                  }
               });

               dataInputStream2.readInt(); 
               dataInputStream2.readInt(); 
               dataInputStream2.readUTF(); 
            } else { 
               System.out.println("Error obtaining Cell Id "); 
            } 
            outputStream2.close(); 
            inputStream2.close(); 
         } catch (Exception e) { 
            System.out.println("Error: " + e.getMessage()); 
         } 
      }

      private void tryGetLocationFromDevice() {
         _gotLocation = false;
         try {
            Criteria myCriteria = new Criteria(); 
            myCriteria.setCostAllowed(false); 
            LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria); 

            try { 
               Location myLocation = myLocationProvider.getLocation(300); 
               setLocation(myLocation.getQualifiedCoordinates()); 
            } catch ( InterruptedException iex ) { 
               System.out.println(iex.getMessage());
            } catch ( LocationException lex ) { 
               System.out.println(lex.getMessage());
            } 
         } catch ( LocationException lex ) { 
            System.out.println(lex.getMessage());
         }

         if (!_gotLocation) { 
            getLocationFromGoogle();
         } 
      }

      public void run() { 
         int bbMapsHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs");    // OS < 6.0
         int bbMapsHandle60 = CodeModuleManager.getModuleHandle("net_rim_bb_maps"); // OS 6.0+
         if (bbMapsHandle > 0 || bbMapsHandle60 > 0) { 
            tryGetLocationFromDevice();
         } else {
            getLocationFromGoogle();
         }
      } 
   } 

   private void writeDataGoogleMaps(OutputStream out, int cellID, int lac) throws IOException { 
      DataOutputStream dataOutputStream = new DataOutputStream(out); 
      dataOutputStream.writeShort(21); 
      dataOutputStream.writeLong(0); 
      dataOutputStream.writeUTF("en"); 
      dataOutputStream.writeUTF("Android"); 
      dataOutputStream.writeUTF("1.0"); 
      dataOutputStream.writeUTF("Web"); 
      dataOutputStream.writeByte(27); 
      dataOutputStream.writeInt(0); 
      dataOutputStream.writeInt(0); 
      dataOutputStream.writeInt(3); 
      dataOutputStream.writeUTF(""); 

      dataOutputStream.writeInt(cellID); 
      dataOutputStream.writeInt(lac); 

      dataOutputStream.writeInt(0); 
      dataOutputStream.writeInt(0); 
      dataOutputStream.writeInt(0); 
      dataOutputStream.writeInt(0); 
      dataOutputStream.flush(); 
   } 

} 
于 2012-08-15T03:02:20.903 回答
2

有很多我们看不到的代码(例如getLatitude(), getLongitude(), refreshDetails())。所以,那里可能会出现问题。另外,我在您发布的代码中没有看到任何加载屏幕,所以我不能说为什么没有显示。

但是,这里有一些看起来不正确的东西:

        synchronized (Application.getEventLock())
        {
            busyDialog.show();
        }

如果您阅读此 BlackBerry 论坛问题,您会发现尝试从主 (UI) 线程同步应用程序事件锁定可能会导致您的应用程序冻结。该public void fieldChanged(Field field, int context)方法总是在 UI 线程上调用,因为它是 UI 线程监视按钮的点击,并回调您的点击处理程序,例如fieldChanged().

您还可以阅读Application 的 BlackBerry API 文档,该文档说明这getEventLock()是针对工作线程(也称为background)线程,而不是主(又名UI)线程。

因此,无需在已在 UI 线程上运行的代码中使用特殊技术来获取事件锁。而不是上面的代码,只需这样做:

            busyDialog.show();

这两种技术:

        synchronized (Application.getEventLock())
        {
            busyDialog.show();
        }

或者

        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
               busyDialog.show();  
            }
        });

是从后台线程安全调用 UI 方法的方法。但是,您不应该在您知道已经在 UI 线程上运行的代码中使用这些代码。

尝试修复它,看看您的问题是否消失。

编辑:此外,您的代码正在刷新位置之前检查用户名和密码。这真的是你想要的吗?我认为这与您的问题没有任何关系,但通常情况下,我不希望需要用户名或密码才能访问位置服务。当然,我不知道你的申请,所以这只是我的评论。

于 2012-08-14T07:38:40.727 回答
2

我认为你很简单的答案是这里的错误:

((longi == "0.0" || lati == "0.0") || (longi.length() == 0 || lati.length()==0));

您必须使用String.equals()而不是==运算符。

在第一次调用longilati具有"0.0"价值之后。但是==会返回false,因为它默认比较引用并且它们是不同的,因为它是不同的对象。

于 2012-08-14T12:12:55.313 回答