首页 > 解决方案 > 通过官方 API 在不使用 GPS 和 Google 服务的情况下获取位置

问题描述

我想知道是否有可能在没有谷歌服务的情况下获得一个位置,而无需NETWORK_PROVIDER在 Android 设备上使用 GPS(因此使用)。我当前的代码如下所示:

public void onButtonTap(View view) {

LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        // we're done here
        printLocation(location);
    }
    public void onStatusChanged(String provider, int status, Bundle extras) { }
    public void onProviderEnabled(String provider) { }
    public void onProviderDisabled(String provider) { }
};

String provider = LocationManager.NETWORK_PROVIDER;
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Location location = null;
try {
    location = locationManager.getLastKnownLocation(provider);
} catch (SecurityException se) { 
}
if(location != null) {
    // we're done here
    printLocation(location);
}
if(location == null) {
    try {
        locationManager.requestSingleUpdate(provider, locationListener, null);
    } catch (SecurityException se) {
    }
} // end of onButtonTab (formatting issues)

private void printLocation(Location location) {
    String latitude = String.format(Locale.US, "%.4f", location.getLatitude());
    String longitude = String.format(Locale.US, "%.4f", location.getLongitude());
    String slocation = "lat: " + latitude + ", lon: " + longitude;
    Toast.makeText(getApplicationContext(), slocation, Toast.LENGTH_LONG).show();
}

所以我基本上查询最后一个位置,如果没有,我请求更新。这适用于PASSIVE_PROVIDER(如果有 GPS 活动),当然也适用于,GPS_PROVIDER但我没有使用NETWORK_PROVIDER. listeners 方法onLocationChanged永远不会被调用。该应用程序具有正确的权限并且locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)是真实的。

这个功能是不是因为没有数据库(由谷歌拥有并由谷歌服务提供)来比较?或者 AOSP 是否会随着时间的推移建立自己的数据库(从 GPS 数据中学习)?我怀疑后者。

额外的小问题:我无法使用Fused Location Provider API,因为我没有安装 Google 服务,可以吗?

标签: android

解决方案


推荐阅读