位置返回NULL

时间:2011-12-15 21:21:22

标签: java android location smartphone locationmanager

我正在编写一个返回经度和纬度的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();
}
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

相关问题