2011-12-15 99 views
1

我正在编写一个返回经度和纬度的Android应用程序,但是位置保留一个空值。位置返回NULL

请看看你是否能看到为什么,它一直在窃听我。代码如下:

public class example extends Activity { 

    public static double latitude; 
    public static double longitude; 
    LocationManager lm; 
    LocationListener ll; 
    Location location; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.questions); 


     lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

     ll = new MyLocationListener(); 

     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); 
     //location = lm.getLastKnownLocation(lm.getBestProvider(criteria, true)); 

     Button b = (Button) findViewById(R.id.button2); 
     b.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
      int index1 = provider.indexOf("gps"); 
      if(index1 < 0) 
       // gps not enabled, call msgbox  
       showMsgBox("GPS is off", "GPS is off. Turn it on?", "Turn on"); 
      else 
      areWeThereYet(); }}); 
} 

    private void areWeThereYet() 
    { 
     if(weAreThere()) 
     { 
      toastMsg("in correct place");  
     } 
     else if(location!=null) 
      toastMsg("not there yet"); 
    } 

private boolean weAreThere() { 

    location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    if (location!=null) 
    { 
     longitude = location.getLongitude(); 
     latitude = location.getLatitude(); 
     toastMsg(latitude + " " + longitude); 
     return inCorrectPlace(question); 
    } 
    else 
    { 
     toastMsg("Location not ready yet"); 
     return false; 
    } 
} 

private void toastMsg(String msg) { 
     Toast toast = Toast.makeText(this, msg, 2000); 
     toast.setGravity(Gravity.BOTTOM, 0, 0); 
      toast.show(); 
} 
} 

回答

3

如果自设备启动以来GPS没有得到位置,则位置对象将为空。您可以做的一件事就是尝试获取GPS位置和网络位置,并检查两个以查看它们中的任何一个是否良好(或哪个更好)并使用该位置。

2

如果您正在使用模拟器,请参阅here以获取有关设置模拟器以提供位置的建议。如果您在设备上进行测试,可能是因为您从未拥有过gps位置。在测试您的应用之前,请尝试使用Google地图应用。