2017-02-28 81 views
0
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; 
} 

} 

它发现以下错误。发现GoogleApiClient尚未连接的错误

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)  
+0

呼叫mGoogleApiClient.connect()。 –

+0

格式化完成 – Manishika

回答

1

您请求在的onCreate() method.This位置更新应该在onConnected()回调被调用一次的GoogleAPIClient已成功地连接。

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

我在活动中也OnStart方法有同样的问题,我想下面的代码,希望它可以帮助你也..

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