融合位置提供程序始终返回相同位置

时间:2016-10-03 05:30:12

标签: android location fusedlocationproviderapi

我一直在努力获取当前的位置信息,并按照Google的建议使用了Fused位置提供商,但我无法获得任何更新。我在网上彻底搜索过但无法找到任何解决方案。融合提供商返回的位置甚至不在我所在的位置,它显示了其他一些国家。任何人都可以帮助我吗?

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener ,
        LocationListener, GoogleApiClient.ConnectionCallbacks{

    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private TextView mLocationTextView;

    private static final int LOC_PERMISSION_CODE = 100;
    private Location mCurrentLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createLocationRequest();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();


        mLocationTextView = (TextView) findViewById(R.id.location);
    }

    private boolean isLocationProviderAvailable(){
        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) || lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private void requestLocation() {
        if (!hasLocationPermission()) {
            ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, LOC_PERMISSION_CODE);
        }else {

            if(!isLocationProviderAvailable()){
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle("No location service")
                        .setMessage("Location adapters are turned off. Please turn on and try again.")
                        .setIcon(R.drawable.location_icon)
                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        })
                        .create();
                dialog.show();
            }else {
                //noinspection MissingPermission
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        }
    }
    private boolean hasLocationPermission(){
        return ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    private void createLocationRequest(){
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(1000 * 10);
        mLocationRequest.setFastestInterval(1000 * 5);
        mLocationRequest.setNumUpdates(2);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if(requestCode == LOC_PERMISSION_CODE){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                requestLocation();
            }else {
                Toast.makeText(this, "Permission Required.", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        log("onConnectionFailed -> %s", connectionResult.getErrorMessage());
    }

    private void log(String format, Object... args){
        Log.d("MainActivity", String.format(format, args));
    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        log("onLocationChanged()");
        updateUI();
    }

    private void updateUI(){
        log("updateUI()");
        if(null != mCurrentLocation) {
            mLocationTextView.setText(String.format("Lat: %s, Lon: %s", mCurrentLocation.getLatitude(), mCurrentLocation.getLatitude()));
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        requestLocation();
        log("onConnected()");
    }

    @Override
    public void onConnectionSuspended(int i) {
        log("onConnectionSuspended()");
    }
}

1 个答案:

答案 0 :(得分:1)

"Lat: %s, Lon: %s", mCurrentLocation.getLatitude(), mCurrentLocation.getLatitude())

第二个参数应该是getLongitude,而不是getLatitude

相关问题