融合位置问题 - 地理位置不起作用

时间:2017-12-15 11:29:07

标签: android geolocation position

我必须使用所有可用传感器之一(例如wifi,gps,data ecc)实现一个返回用户当前地理位置的函数。

我查找了有关它的信息,我找到了几个解决方案,目前我感兴趣的是使用"融合位置",但我没有找到指南或完整的使用示例

这是我目前使用的代码:

public class LocationService extends Service {

private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private Boolean mRequestingLocationUpdates;
private WriteInLogFile wil = new WriteInLogFile();

@Override
public void onCreate() {
    try {
        DbGest db = DbGest.getInstance(getApplicationContext());
        String deviceType = db.getSetting("deviceType");

        long updateInterval;
        if (deviceType.compareToIgnoreCase("smartphone") == 0) {
            updateInterval = Long.parseLong(db.getSetting("pollGPSPhone"));
        } else {
            updateInterval = Long.parseLong(db.getSetting("pollGPSTablet"));
        }

        long updateInMillisecond = updateInterval / 2;

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(updateInterval);
        mLocationRequest.setFastestInterval(updateInMillisecond);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


        mRequestingLocationUpdates = false;
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);

        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                mCurrentLocation = locationResult.getLastLocation();
                updateLocation();
            }
        };


        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setNeedBle(true);
        mLocationSettingsRequest = builder.build();
        startLocationUpdates();
    } catch (Exception e) {
        wil.WriteFile("1)LocationService - Exception: " + e.toString());
    }
}


public void startLocationUpdates() {
    if (!mRequestingLocationUpdates) {
        mRequestingLocationUpdates = true;
        mSettingsClient.checkLocationSettings(mLocationSettingsRequest).addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                wil.WriteFile("2)LocationService - Exception: " + e.toString());
            }
        });
    }
}


private void stopLocationUpdates() {
    if (!mRequestingLocationUpdates) {
        return;
    }
    mFusedLocationClient.removeLocationUpdates(mLocationCallback).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            mRequestingLocationUpdates = false;
        }
    });
}


private void updateLocation() {
    if (mCurrentLocation != null) {   
    DbGest.getInstance(getApplicationContext()).insertIntoLastPositionKnown(mCurrentLocation, getApplicationContext());
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopLocationUpdates();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
} }

如果我在这种情况下通过Wi-Fi连接到网络,代码工作完全正常,但当我切换3g时会出现错误:

  

com.google.android.gms.common.api.ResolvableApiException:6:   RESOLUTION_REQUIRED

在gradle中:

compile 'com.google.android.gms:play-services-gcm:11.6.2'
compile 'com.google.android.gms:play-services-vision:11.6.2'
compile 'com.google.android.gms:play-services-location:11.6.2'
compile 'com.google.android.gms:play-services-maps:11.6.2'

我不知道要解决这个问题......

2 个答案:

答案 0 :(得分:1)

获取位置可能需要一些时间,我建议在后台处理它会使体验更顺畅。检查您是否获得了该权限,并且您的应用已启用该权限。如果您需要进一步的帮助,请发布日志。我已经尝试过此代码并且运行正常!

    private void getUserLocation() {
    FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        mFusedLocationClient.getLastLocation()
                .addOnSuccessListener(new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                });
    }
}

答案 1 :(得分:0)

遇到相同错误的任何人: 当您致电

时出现
 new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);

 LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);

对我来说是解决方案-不要调用.addLocationRequest(...) 当我在添加请求的同时调用builder.addLocationRequesttask = client.checkLocationSettings(builder.build())时,发生了此错误。 参见https://developer.android.com/training/location/change-location-settings#get-settings