需要更好的方式来获取当前位置

时间:2013-11-18 06:58:37

标签: android networking gps location locationmanager

通过此处和网络上的几乎所有问题/答案,当前位置的最佳方式如下:

if ( mLocationManager==null )
    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

Location l;
for ( String provider : mLocationManager.getAllProviders() ){
    mLocationManager.requestLocationUpdates(provider, 1000, 1, locationListener);
    l = mLocationManager.getLastKnownLocation(provider);
    if ( isBetterLocation(l, currentBestLocation) )
    currentBestLocation = l;
}

通常它在模拟器和设备上运行正常,但正如一些人所说,Android 4.0+此代码提供了exception

09-06 22:46:16.163: ERROR/AndroidRuntime(351): Caused by: java.lang.IllegalArgumentException: provider=network
09-06 22:46:16.163: ERROR/AndroidRuntime(351):     at android.os.Parcel.readException(Parcel.java:1325)
09-06 22:46:16.163: ERROR/AndroidRuntime(351):     at android.os.Parcel.readException(Parcel.java:1275)
09-06 22:46:16.163: ERROR/AndroidRuntime(351):     at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:646)
09-06 22:46:16.163: ERROR/AndroidRuntime(351):     at android.location.LocationManager._requestLocationUpdates(LocationManager.java:582)
09-06 22:46:16.163: ERROR/AndroidRuntime(351):     at android.location.LocationManager.requestLocationUpdates(LocationManager.java:446)

但是当只有WIFI / 3G覆盖(GPS无法在室内工作)时,同一设备上的其他应用可以正常工作。

所以我的问题是: 如何检索建筑物内的当前位置?

PS:等待Android映像更新是不可接受的,因为其他应用程序在同一设备上正常运行。必须有一种方法可以使用LocationManager中的错误获取Android图像上的当前位置。

最诚挚的问候。

修改

这次我尽可能简单地调整了我的代码(在onResume中):

    if ( mLocationManager==null )
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    for ( String provider : mLocationManager.getAllProviders() )
        mLocationManager.requestLocationUpdates(provider, 0, 0, locationListener);

并在locationListener.onLocationChanged:

public void onLocationChanged(Location location) {
    if (isBetterLocation(location, currentBestLocation)) {
        currentBestLocation = location;
        ...make use of this location
    }
}

只有被动 gps 提供商可用,无网络提供商可以在我的XT928上获得,而在另一部手机上则显示

编辑2 : 最后,我通过转向名为百度位置库的第三方库来实现这一目标,该库也需要访问密钥应用程序。它很棒。

2 个答案:

答案 0 :(得分:0)

试试这个: GoogleMap googleMap;

googleMap.setMyLocationEnabled(true); //在create()上面

这可以帮助你!!!

答案 1 :(得分:0)

为什么在mLocationManager.requestLocationUpdates(provider, 1000, 1, locationListener);之前致电mLocationManager.getLastKnownLocation(provider);?据我所知,requestLocationUpdates会注册一个听众,会不断通知您手机的位置。 getLastKnownLocation()将为您提供提供商的最后一个已知位置。所以两者要完成不同的事情。

如果您只想要当前位置的一个实例,请删除requestLocationUpdates()。然后,您需要根据上面的代码检查当前最佳位置是否足够好。如果不是,您可以稍后请求单个更新(在for循环之外):locationManager.requestSingleUpdate(criteria, singleUpdatePI);

另请注意,如果用户已在设置中获得授权,则您只能从提供商处获取位置。在Android 4+中,“位置访问”设置明确要求授权:

  

让应用使用Google的位置服务来估算您的位置   更快。