我移动时onLocationChange方法未执行

时间:2018-08-27 16:19:43

标签: java android location android-fusedlocation

我试图每次在10米之内执行一段代码,当我第一次运行我的应用程序时,它会执行onLocationChange内部的所有代码,但是当我移动10米以上时,似乎监听器无法正常工作还是该位置未更新,是否可能导致此问题的任何线索?

@Override
    public void onLocationChanged(Location location) {
        Toast.makeText(Principal.this, "it moved: " + location.getLatitude() + "" + location.getLongitude(), Toast.LENGTH_SHORT).show();
        Log.i(TAG, "onLocationChanged: "+location.getLatitude()+""+location.getLongitude());
        getPlaceByTimer();

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        Toast.makeText(this, "connected", Toast.LENGTH_SHORT).show();
        startLocationUpdate();


    }

    private void initLocationRequest() {
        mLastLocationRequest = new LocationRequest();
        mLastLocationRequest.setSmallestDisplacement(10);
      mLastLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    }


    private void startLocationUpdate() {

        initLocationRequest();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLastLocationRequest, this);
    }

FusedLocationApi似乎已被弃用,但是我读到的是它也适用于Google Play服务的版本,因此我认为那里没有问题

1 个答案:

答案 0 :(得分:0)

似乎将mLastLocationRequest.setFastestInterval(10000);参数添加到mLastLocationRequest中解决了更新问题