【问题标题】:Location returns NULL位置返回 NULL
【发布时间】:2011-12-15 21:21:22
【问题描述】:

我正在编写一个返回经度和纬度的 Android 应用程序,但是 location 包含 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();
}
}

【问题讨论】:

    标签: java android location smartphone locationmanager


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您使用的是模拟器,请参阅here,获取有关设置模拟器以提供位置的建议。如果你在你的设备上测试它,可能是因为你从来没有在它上面有 GPS 位置。在测试您的应用之前尝试使用 Google 地图应用。

      【讨论】:

        猜你喜欢
        • 2017-10-05
        • 2020-03-24
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-23
        • 2011-11-03
        相关资源
        最近更新 更多