0

这是我目前拥有的代码:

public class Map extends FragmentActivity implements LocationListener
{

  private Location l;
  private Location x;

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    LocationManager provider = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    provider.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    l = provider.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    showm();

    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date date = new Date(l.getTime());

    Toast.makeText(this, "Fix received on: " + format.format(date), Toast.LENGTH_SHORT).show();
  }

  void showm()
  {
    Toast.makeText(this, "Latitude: " + l.getLatitude() + ", Longitude: " + l.getLongitude(), Toast.LENGTH_SHORT).show();

  }

  @Override
  public void onLocationChanged(Location location)
  {
    if(location != null)
      x = location;
  }

现在,如果我运行应用程序,则此代码provider.getLastKnownLocation有效经度/纬度。

4

1 回答 1

1

showm() 应该在 onLocationChanged(Location location) 内。

您正在尝试在查询仍在进行时显示位置。在 GPS 修复时,通过回调 onLocationChanged(...) 方法报告新位置。否则为 NULL(这是 null 异常的原因)。

于 2013-11-04T08:01:40.730 回答