Location returns NULL

2019-03-03 02:31发布

问题:

I am writing an Android app that returns longitude and latitude, however location holds a Null value.

Please see if you can see why, Its been bugging me all day. Code below:

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();
}
}

回答1:

If the GPS has not ever gotten a location since the device was booted, the location object will be null. One thing you can do is attempt to get a GPS location and a network location, and check to two to see if either of them are good (or which one is better) and use that location.



回答2:

If you're using the emulator, then see here for advice on setting up the emulator to provide a location. If you're testing it on your device, it may be because you've never had a gps location on it. Try using the Google maps application before testing your app.