android位置获取null需要解决方案

时间:2013-08-23 06:43:51

标签: android gps location

String logloc ="";
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null) {
    double longitude = location.getLongitude();
    double latitude = location.getLatitude();
    logloc = String.valueOf(latitude)+","+String.valueOf(longitude);
    notfi(logloc); 
}

在上面的代码中我的位置总是变为null,即使我的gps设备已打开,并且在建筑物外和建筑物内部,我只获得空值,请帮我运行此代码

2 个答案:

答案 0 :(得分:1)

只是因为你的设备没有最后的已知位置,这就是原因。首先为onLocationChanged()制作代码。它将获取当前位置并将其另存为lastKnownLocation。然后该方法将起作用。

您可以在此处获取当前位置的帮助

How do I get the current GPS location programmatically in Android?

答案 1 :(得分:0)

尝试这样你的活动必须像这样

Activity extends MapActivity implements LocationListener

 LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 Criteria criteria = new Criteria();
 String provider = locationManager.getBestProvider(criteria, false);
 Location location = locationManager.getLastKnownLocation(provider);

    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        lat = (double) (location.getLatitude());
        lng = (double) (location.getLongitude());

        Log.i(TAG, "Lattitude:" + lat);
        Log.i(TAG, "Longitude:" + lng);

    }