为什么永不调用onLocationchanged

时间:2018-10-20 08:38:19

标签: android google-maps google-maps-api-3 on-location-changed

我已经实现了一种从Google Maps检索当前位置的方法,并且效果很好。

但是它不会突然起作用。

所以我检查了过去的代码,但仍然无法正常工作。

我发现哪些功能不起作用,我注意到没有调用onLocationChanged()。

我不知道问题出在哪里,因为日志中没有显示错误消息。

这是相关的代码。

Google地图片段中的代码

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    previous_marker = new ArrayList<>();
    getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_main, container, false);
    ButterKnife.bind(this, rootView);

    mActivity = getActivity();
    mcontext = getContext();
    Initialize();

    mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
            .enableAutoManage(mActivity, 1, this)
            .addConnectionCallbacks(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .addApi(LocationServices.API)
            .build();

    mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.googleMap);
    mapFragment.getMapAsync(this);

    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(UPDATE_INTERVAL_MS);
    locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);

其他代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case GPS_ENABLE_REQUEST_CODE:
            if (checkLocationServicesStatus()) {
                if (checkLocationServicesStatus()) {
                    if ( mGoogleApiClient.isConnected() == false ) {
                        Log.d( TAG, "onActivityResult : mGoogleApiClient connect ");
                        mGoogleApiClient.connect();
                    }
                    return;
                }
            }
            break;


 @Override
public void onLocationChanged(Location location) {
    setCurrentLocation(location);
    currentPosition = new LatLng(location.getLatitude(), location.getLongitude());
    saveLat = location.getLatitude();
    saveLng = location.getLongitude();

    chooseLat  = location.getLatitude();
    chooseLng = location.getLongitude();
    district = getDistrict(mcontext, location.getLatitude(), location.getLongitude());
    getToken();
    setDefaultPlace(location.getLatitude(), location.getLongitude());
}

@Override
public void onResume() {
    super.onResume();
    if (mGoogleApiClient.isConnected()) {
        if (!mRequestingLocationUpdates) startLocationUpdates();
    }
    if (askPermissionOnceAgain) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            askPermissionOnceAgain = false;
            checkPermissions();
        }
    }
}

private void startLocationUpdates() {
    if (!checkLocationServicesStatus()) {
        Log.d(TAG, "startLocationUpdates : call showDialogForLocationServiceSetting");
        showDialogForLocationServiceSetting();
    }else {
        if (ActivityCompat.checkSelfPermission(mcontext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mcontext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
        mRequestingLocationUpdates = true;
        mGoogleMap.setMyLocationEnabled(false);
    }
}

public boolean checkLocationServicesStatus() {
    locationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);

    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}


@Override
public void onStart() {
    if(mGoogleApiClient != null && mGoogleApiClient.isConnected() == false){
        Log.d(TAG, "onStart: mGoogleApiClient connect");
        mGoogleApiClient.connect();
    }
    if(!firstLoad){
        mRequestingLocationUpdates = true;
    }
    super.onStart();
}

@Override
public void onStop() {
    firstLoad = false;
    if (mRequestingLocationUpdates) {
        Log.d(TAG, "onStop : call stopLocationUpdates");
        stopLocationUpdates();
    }
    if ( mGoogleApiClient.isConnected()) {
        Log.d(TAG, "onStop : mGoogleApiClient disconnect");
        mGoogleApiClient.disconnect();
    }
    super.onStop();
}

@Override
public void onConnected(Bundle connectionHint) {
    if ( mRequestingLocationUpdates == false ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasFineLocationPermission = ContextCompat.checkSelfPermission(mcontext,
                    android.Manifest.permission.ACCESS_FINE_LOCATION);
            if (hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
                ActivityCompat.requestPermissions(mActivity,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
            } else {
                Log.d(TAG, "onConnected : call startLocationUpdates");
                startLocationUpdates();
                mGoogleMap.setMyLocationEnabled(true);
            }

        } else {
            Log.d(TAG, "onConnected : call startLocationUpdates");
            startLocationUpdates();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    setDefaultLocation();
}

@Override
public void onConnectionSuspended(int cause) {
    if (cause == CAUSE_NETWORK_LOST)
        Log.e(TAG, "onConnectionSuspended(): Google Play services " +
                "connection lost.  Cause: network lost.");
    else if (cause == CAUSE_SERVICE_DISCONNECTED)
        Log.e(TAG, "onConnectionSuspended():  Google Play services " +
                "connection lost.  Cause: service disconnected");
}

这是我的允许

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

如果您知道代码的原因或错误部分,请告诉我。

感谢您阅读本文。祝你有美好的一天

1 个答案:

答案 0 :(得分:0)

在mapready方法中检查这些行

public void onMapReady(GoogleMap googleMap) {


            mMap = googleMap;

            mMap.setMyLocationEnabled(true);

    // Setting event handler for location change
            mMap.setOnMyLocationChangeListener(this);
}