【问题标题】:What am I doing wrong obtaining my current location on my Android App在我的 Android 应用程序上获取当前位置我做错了什么
【发布时间】:2011-10-20 03:43:57
【问题描述】:

我正在尝试通过 GPS 获取我当前的位置,但似乎没有任何效果,我在这里关注了很多问题,但收效甚微...

这是我的代码:

private GeoPoint getActualPosition()
{
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    Location current = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    actualLat = (int)(current.getLatitude()*1E6);
    actualLong = (int)(current.getLongitude()*1E6);

    GeoPoint point = new GeoPoint(actualLat, actualLong);

    return point;
}

现在,方法的“this”部分(在 requestLocationUpdates 上)引用了实现 LocationListener 接口的活动,其 onLocationChanged 方法是:

@Override
public void onLocationChanged(Location location) {
    actualLat = (int)(location.getLatitude()*1E6);
    actualLong = (int)(location.getLongitude()*1E6);

}

我的问题出在当前位置行,其中“当前”始终为空,我找不到原因。

我的清单具有所需的权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

所以我真的不知道我的代码有什么问题。

感谢您的宝贵时间!!

【问题讨论】:

  • 欢迎来到stackoverflow。如果您发现特定答案有帮助,请点赞。如果您发现某个特定答案是正确的,请接受它。

标签: java android gps location


【解决方案1】:

getLastKnownLocation() 返回最后一个缓存 位置。如果没有这样的位置将返回 null(例如,如果手机关闭)如果提供程序当前被禁用,则返回 null

获取 GPS 定位需要时间。 onLocationChanged() 只有在得到适当的修复后才会被调用,这个时间可能从 20 秒到几分钟不等。

只有在至少调用一次onLocationChanged() 之后,getLastKnownLocation() 才会返回最后一个有效位置。

【讨论】:

    【解决方案2】:

    您是在模拟器还是物理设备上运行应用程序/您的代码?如果它是一个模拟器并且您之前从未设置过位置(在 Eclipse 中使用 DDMS 视图),则该位置将为空。

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      根据getLastKnownLocation的文档:

      如果提供者当前被禁用,则返回 null。

      因此,如果您在测试此功能的设备上未启用 GPS,您将获得 null。如果您使用的是安卓模拟器,请查看stackoverflow post 了解如何模拟特定位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多