这是我目前的代码:
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;
}
现在这个代码可以运行,如果我运行应用程序调用LocationListener方法并立即收到GPS修复,我就会调用provider.getLastKnownLocation
并根据第二个Toast的日期我得到了当前位置和showm( )方法将显示具有正确长/纬度的祝酒词。
答案 0 :(得分:1)
showm()应该位于onLocationChanged(位置位置)内。
您正在尝试在查询仍在进行时显示位置。在GPS修复时,通过回调onLocationChanged(...)方法报告新位置。否则为NULL(这是null异常的原因)。