发现GoogleApiClient尚未连接的错误

时间:2017-02-28 06:58:39

标签: android location-services google-location-services

private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private double currentLatitude;
private double currentLongitude;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

Button btn_start;
TextView txt_refersh;


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


    btn_start = (Button) findViewById(R.id.btn_start);
    txt_refersh = (TextView) findViewById(R.id.txt_refersh);


    btn_start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getLocationdetails(Demo.this);

        }
    });


    mGoogleApiClient = new GoogleApiClient.Builder(this)
            // The next two lines tell the new client that “this” current class will handle connection stuff
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            //fourth line adds the LocationServices API endpoint from GooglePlayServices
            .addApi(LocationServices.API)
            .build();

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds


    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    locationRequest.setInterval(60000);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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, mLocationRequest, this);


}

@Override
protected void onResume() {
    System.runFinalization();
    Runtime.getRuntime().gc();
    System.gc();
    Log.e("System GC", "Called");


    super.onResume();


    //Now lets connect to the API
    mGoogleApiClient.connect();

}

@Override
protected void onStart() {

    super.onStart();
}

@Override
protected void onPause() {

    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }


    super.onPause();
    Log.v(this.getClass().getSimpleName(), "onPause()");


}

@Override
public void onConnected(Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    } else {
        //If everything went fine lets get latitude and longitude
        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();

    }
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
        Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

/**
 * If locationChanges change lat and long
 *
 * @param location
 */
@Override
public void onLocationChanged(Location location) {
    currentLatitude = location.getLatitude();
    currentLongitude = location.getLongitude();
}

private Location getLocationdetails(Context context) {

    Location location = null;

    if (mGoogleApiClient != null) {


        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return null;


        } else {


            location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }


    }


    return location;
}

}

发现以下错误。

FATAL EXCEPTION: main
Process: nividaweb.com.gpsdemo, PID: 32012
java.lang.RuntimeException: Unable to start activity ComponentInfo{nividaweb.com.gpsdemo/nividaweb.com.gpsdemo.Demo}: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2335)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397)
   at android.app.ActivityThread.access$800(ActivityThread.java:151)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:135)
   at android.app.ActivityThread.main(ActivityThread.java:5268)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet.
   at com.google.android.gms.internal.zzaal.zzb(Unknown Source)
   at com.google.android.gms.internal.zzarl.requestLocationUpdates(Unknown Source)
   at nividaweb.com.gpsdemo.Demo.onCreate(Demo.java:84)
   at android.app.Activity.performCreate(Activity.java:6033)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397) 
   at android.app.ActivityThread.access$800(ActivityThread.java:151) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:135) 
   at android.app.ActivityThread.main(ActivityThread.java:5268) 
   at java.lang.reflect.Method.invoke(Native Method) 
   at java.lang.reflect.Method.invoke(Method.java:372) 
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902) 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697) 

2 个答案:

答案 0 :(得分:1)

您正在 onCreate()方法中请求位置更新。一旦GoogleAPIClient成功连接,就应在 onConnected()回调中调用此方法。

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

答案 1 :(得分:0)

我有同样的问题,我尝试了下面的代码,希望它对你也有帮助..

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