getLastKnownLocation返回Null值

时间:2014-04-25 07:45:42

标签: android geolocation

我正在开发一个Android应用程序,我尝试使用代码。 我还在我的xml文件中添加了所有的persmission。

public class LbsGeocodingActivity extends Activity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

protected LocationManager locationManager;

protected Button retrieveLocationButton;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MINIMUM_TIME_BETWEEN_UPDATES, 
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );

    retrieveLocationButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
    });        

}    

protected void showCurrentLocation() {

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(LbsGeocodingActivity.this, message,
                Toast.LENGTH_LONG).show();
    }

}   

private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(LbsGeocodingActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(LbsGeocodingActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}

}

但是我在getLastKnownLocation获得null值。 我正在三星Galaxy Grand上运行我的项目。 请告诉我我在哪里做错了。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您的代码看起来很完美,我认为您正在使用Null,因为您的设备中没有以前的GPS值。这样做,在您的设备中加载应用程序,移动到天空,运行应用程序,等待2分钟。回到办公室里面,然后执行上面的代码