Android:GoogleApiClient尚未连接?

时间:2017-01-13 09:21:02

标签: android location google-api-client

更新用户的当前位置 我对我的项目实现了以下方法:

GoogleApiClient.ConnectionCallbacks,         GoogleApiClient.OnConnectionFailedListener

执行项目时,将发生以下错误:

java.lang.IllegalStateException: GoogleApiClient is not connected yet.

代码中有错误:

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

已提出了许多解决方案,例如ThisThis 但是没有解决任何问题。

请帮助解决它。

我的代码在onCreate方法:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        FirebaseCrash.report(new Exception("Exceptin"));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mGoogleClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
                .setInterval(60*1000) 
                .setFastestInterval(1*1000);}

在onMapReady中:

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        buildGoogleApiClient();
        mMap.setTrafficEnabled(true);
        mMap.setMyLocationEnabled(true);}

而且这个:

   protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

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

 if (servicesAvailable()) {
            // Get best last location measurement meeting criteria
            mLastLocation = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);

            if (null == mLastLocation
                    || mLastLocation.getAccuracy() > MIN_LAST_READ_ACCURACY
                    || mLastLocation.getTime() < System.currentTimeMillis() - TWO_MIN) {

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

                // Schedule a runnable to unregister location listeners
                Executors.newScheduledThreadPool(1).schedule(new Runnable() {

                    @Override
                    public void run() {
                        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);//This Line Return Error
                    }

                }, ONE_MIN, TimeUnit.MILLISECONDS);
            }
        }else{
            handleNewLocation(mLastLocation);
        }

    }

感谢您的帮助:)

3 个答案:

答案 0 :(得分:2)

解决了我的问题,因为我在项目中使用启动画面将此代码放在启动画面活动中:

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

答案 1 :(得分:0)

这是适合我的完整实现..

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


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

        buildGoogleApiClient();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.d(TAG, "Connection established. Fetching location ..");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

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

    @Override
    public void onLocationChanged(Location location) {

        Log.d("Lat: " + location.getLatitude() + "Lng : " + location.getLongitude());    
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    }

    public synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
        mGoogleApiClient.connect();
    }

            @Override
        public void onStart(){
            super.onStart();
            if(this.googleApiClient != null){
                    this.googleApiClient.connect();
            }
        }

    @Override
    public void onPause() {
        super.onPause();
        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }
}

答案 2 :(得分:0)

在onCreate中,您在没有客户的情况下呼叫getMapAsync()

您需要在mGoogleClient.connect()中致电onCreate,然后将mapFragment.getMapAsync(this)移至onConnected