2011-11-08 107 views
0

我正在用J2ME写我的第一个BB应用程序。我找到了一段描述如何获取GPS坐标的代码片段。我得到一个空指针异常(在手机上),但没有在模拟器上,我不知道为什么。黑莓j2me位置服务

我将不胜感激任何帮助。下面

代码:

try 
{ 
    // Set criteria for selecting a location provider: 
    Criteria cr= new Criteria(); 
    cr.setCostAllowed(true); 
    cr.setSpeedAndCourseRequired(true); 
    // Get an instance of the provider 
    LocationProvider lp= LocationProvider.getInstance(cr); 

    // Request the location, setting a 60 second timeout 
    Location l = lp.getLocation(300); //always times out 
    Coordinates c = l.getQualifiedCoordinates(); 
    double longitude = 0; 
    double latitude = 0; 
    float course = l.getCourse(); 
    float speed = l.getSpeed(); 
    long timestamp = l.getTimestamp();  
    if(c != null) 
    { 
     // Use coordinate information 
     latitude = c.getLatitude(); 
     longitude = c.getLongitude(); 
    } 
    System.out.println("Lon" + longitude + " Lat "+ latitude + " course "+course+" speed "+speed+" timestamp "+timestamp); 
} 
catch(LocationException le) 
{ 
    System.out.println("Location exception "+le); 
} 
catch(InterruptedException ie) 
{ 
    System.out.println("Interrupted exception "+ie); 
} 
+0

这里有丢失了一些细节:什么电话时间;它有清楚的天空视野;何时获得了最后一次GPS定位。如果GPS已经冷一段时间并且/或者您的天空视野很差,则60秒很短。 IIRC模拟器将始终立即返回一个位置,即使该位置为0,0,除非您明确禁用了LBS。 – Richard

+0

嗯,谢谢理查德。最终,我通过进入选项 - >设备 - >位置设置并打开位置服务来解决问题。如果定位服务关闭,则Midlet引发java.lang.NullPointerException。这款手机是一款9780 btw。 Regards Luben – Luben

回答

0

使用此代码

public class handleGPS{ 
     static GPSThread gpsThread; 
     public static double latitude ; 
     public static double longitude; 

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

     private static class GPSThread extends Thread{ 
      public void run() { 
       Criteria myCriteria = new Criteria(); 
       myCriteria.setCostAllowed(false); 

       try { 
        LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria); 

        try { 
         Location myLocation = myLocationProvider.getLocation(300); 
         latitude = myLocation.getQualifiedCoordinates().getLatitude(); 
         longitude = myLocation.getQualifiedCoordinates().getLongitude(); 
         System.out.print("latitude= "+latitude+" longitude="+longitude); 


        } 
        catch (InterruptedException iex) { 
         return; 
        } 
        catch (LocationException lex) { 
         return; 
        } 
       }catch (LocationException lex) { 
        return; 
       } 
       return; 
      } 
     } 
    } 

然后在你的主类,请拨打上面的类

handleGPS handleGPS=new handleGPS(); 
    int m_bbHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs"); 
     if(m_bbHandle>0){ 

     Dialog.alert("GPS not found"); 
     } 
     else{ 
      Dialog.alert("GPS found"); 
      //your code 
      } 
+0

谢谢Rez,今天晚些时候我会试试这个代码... – Luben