【问题标题】:Unable to get latitude and longitude from android无法从android获取纬度和经度
【发布时间】:2011-07-12 17:02:41
【问题描述】:

getLastKnownLocation 总是返回空值。我在模拟器上启用了地理修复和 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) {}

 }

【问题讨论】:

  • 我建议在onResume() 中执行requestLocationUpdates,并确保在onPause() 中取消注册位置更新。

标签: android android-emulator gps


【解决方案1】:

您的代码不工作的原因是因为您指定了以下条件:

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);

【讨论】:

    【解决方案2】:

    您可能还想查看geofix not working

    还要确保您在模拟器中设置了允许的模拟位置。看看 Pauls 的回答,这就是为什么我在 cmets 中询问返回了什么提供程序

    【讨论】:

    • @davidlee 好的,它是在喂位置吗?如果没有建立修复,lastknown 调用将返回 null。另外,您的标准设置返回的提供者是什么? Paul 的 cmets 也是正确的,但不应阻止您进行初始修复。还看到许多人在使用 telnet 时抱怨 geoFix,您是否尝试过直接 DDMS 方法只是为了看看这是否可能是一个问题?
    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多