无法获得android的经纬度

时间:2011-07-12 17:02:42

标签: android android-emulator gps

getLastKnownLocation始终返回null值。我在模拟器上启用了geo fix和gps。但是,在模拟器上运行时,通知栏上没有gps信号。我可以知道我的代码中有任何错误吗?谢谢。

public void onCreate(Bundle savedInstanceState) {
    LocationManager location = null;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.near_layout);

    location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.NO_REQUIREMENT);
    criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    String bestProvider = location.getBestProvider(criteria, true);

    LocationListener ll = new mylocationlistener();


    Location loc = location.getLastKnownLocation(bestProvider);
    if(loc != null)
    {
        double latitude = loc.getLatitude();
        double longitude = loc.getLongitude();
        Toast.makeText(nearPlace.this,  " nice" + latitude, Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(nearPlace.this,  "Location not available. GPS is not enabled.", Toast.LENGTH_LONG).show();
    }
    location.requestLocationUpdates(bestProvider, 0, 0, ll);
 }

 private class mylocationlistener implements LocationListener {

     @Override
     public void onLocationChanged(Location location) {
            Toast.makeText(nearPlace.this,  " nice" + location.getLatitude(), Toast.LENGTH_LONG).show();
            nearPlaceDownloaderTask getNearPlace = new nearPlaceDownloaderTask();
            getNearPlace.execute(ANDROID_WEB_LINK + "gt.php?la=" + location.getLatitude() + "&lo=" + location.getLongitude());

     }
     public void onProviderDisabled(String provider) {}
     public void onProviderEnabled(String provider) {}
     public void onStatusChanged(String provider, int status, Bundle extras) {}

 }

2 个答案:

答案 0 :(得分:0)

您可能还想查看geofix not working

还要确保在模拟器中设置了允许的模拟位置。看看Pauls的回答,这就是为什么我在评论中询问提供者被退回的原因

答案 1 :(得分:0)

您的代码无效的原因是因为您指定了以下条件:

criteria.setAccuracy(Criteria.NO_REQUIREMENT);

Android会优先使用GPS上的网络位置,因为您不关心准确性。通过指定20米左右的精度,它可能会自动调用GPS。

要手动调用GPS位置更新,请覆盖bestProvider

bestProvider = LocationManager.GPS_PROVIDER;

您可以将其简化为两行代码:

LocationManager locationManager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval,
            precision, listener);

不要忘记取消注册您的听众:

locationManager.removeUpdates(listener);