Java 地理围栏:GoogleAppClient尚未连接

Java 地理围栏:GoogleAppClient尚未连接,java,android,google-maps,android-studio,Java,Android,Google Maps,Android Studio,我正在尝试在我的应用程序中实现地理围栏,因此每当用户输入一个地理围栏对象时,就会发生一些事情。当我添加此代码段时,请遵循《android开发者指南》(让您的应用程序能够感知位置): LocationServices.GeofencingApi.addGeofences( mGoogleApiClient, getGeofencingRequest(), getGeofencePendingIntent() ).set

我正在尝试在我的应用程序中实现地理围栏,因此每当用户输入一个地理围栏对象时,就会发生一些事情。当我添加此代码段时,请遵循《android开发者指南》(让您的应用程序能够感知位置):

LocationServices.GeofencingApi.addGeofences(
            mGoogleApiClient,
            getGeofencingRequest(),
            getGeofencePendingIntent()
    ).setResultCallback(this);
加载geofences后,我将其放入onMapReady()中,以便它们将立即添加到我的应用程序中。但是,我得到了这个错误:

java.lang.IllegalStateException: GoogleApiClient is not connected yet.
我确信我已经在onCreate()中构建了GoogleAPI客户端,但仍然会遇到这个错误。如果我删除了上面的代码段(第一个代码段),那么错误就不再存在了。我做错了什么

代码:

公共类MapsActivity扩展了AppCompativeActivity在MapReadyCallback、ConnectionCallbacks、OnConnectionFailedListener、LocationListener、ResultCallback上的实现{

//Google Maps
public GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest = new LocationRequest();
public Location mCurrentLocation;
private static final int FINE_LOCATION_PERMISSION_REQUEST = 1;
private static final int CONNECTION_RESOLUTION_REQUEST = 2;
List<Marker> markerList = new ArrayList<Marker>();

//Temporary Vars
double lat = 0;
double lon = 0;
Marker current_marker;

//Request Info vars
static final int GET_DETAILS = 1;
static final int EDIT_DETAILS = 2;


//Debug
private static final String TAG = "GeekysMessage";

SharedPreferences sharedPreferences;
int markerCount;

private Toolbar toolbar;


//Geofence
private boolean mGeofencesAdded;
ArrayList mGeofenceList = new ArrayList<Geofence>();
private PendingIntent mGeofencePendingIntent;
public int geofenceCount;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(toolbar);


    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    buildGoogleAPIClient();
    //Geofence
    // Empty list for storing geofences.
    mGeofenceList = new ArrayList<Geofence>();

    // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null.
    mGeofencePendingIntent = null;
}

@Override
protected void onResume() {
    super.onResume();

    buildGoogleAPIClient();

    if (mGoogleApiClient.isConnected()) {
        startLocationUpdates();
    }
}

//LOCATION
private void buildGoogleAPIClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}



protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            updateUI();
        }
        startLocationUpdates();

    }

}

@TargetApi(Build.VERSION_CODES.N)
@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;
    updateUI();
    Toast.makeText(this, "Updated",
            Toast.LENGTH_SHORT).show();
}

private void updateUI() {

}

@Override
public void onConnectionSuspended(int i) {
    Toast.makeText(this, "Connection suspended", Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
        try {
            connectionResult.startResolutionForResult(this, CONNECTION_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {
            // There was an error with the resolution intent. Try again.
            mGoogleApiClient.connect();
        }
    } else {
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 1);
        dialog.show();
    }
}

protected void stopLocationUpdates() {
    // It is a good practice to remove location requests when the activity is in a paused or
    // stopped state. Doing so helps battery performance and is especially
    // recommended in applications that request frequent location updates.

    // The final argument to {@code requestLocationUpdates()} is a LocationListener
    // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}

@Override
protected void onPause() {
    super.onPause();
    // Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
    if (mGoogleApiClient.isConnected()) {
        stopLocationUpdates();
    }
}


int requestCode = 0;

//MAP
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    //load all saved markers
    loadMarkers();

    LocationServices.GeofencingApi.addGeofences(
            mGoogleApiClient,
            getGeofencingRequest(),
            getGeofencePendingIntent()
    ).setResultCallback(this);

    //Permissions
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                FINE_LOCATION_PERMISSION_REQUEST);
    } else {
        mMap.setMyLocationEnabled(true);

    }


}
private void loadMarkers() {

    // Opening the sharedPreferences object
    sharedPreferences = getSharedPreferences("location", 0);

    // Getting number of locations already stored
    markerCount = sharedPreferences.getInt("markerCount", 0);

    //if marker are already saved
    if (markerCount != 0) {

        String lat = "";
        String lng = "";
        String marker_title = null;
        String marker_snippet = null;
        int marker_radius = 0;

        for (int i=0; i < markerCount; i++) {
            lat = sharedPreferences.getString("lat"+i, "0");
            lng = sharedPreferences.getString("lng"+i, "0");
            marker_title = sharedPreferences.getString("title"+i, "");
            marker_snippet = sharedPreferences.getString("snippet"+i, "");
            marker_radius = sharedPreferences.getInt("radius"+i, 20);

            double lati = Double.valueOf(lat);
            double lngi = Double.valueOf(lng);

            addMarker(lati, lngi, marker_title, marker_snippet);
            addGeofence(marker_title, lati, lngi, marker_radius);

        }

    }
}
private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
    // calling addGeofences() and removeGeofences().
    return PendingIntent.getService(this, 0, intent, PendingIntent.
            FLAG_UPDATE_CURRENT);
}

public void addMarker(double lati, double longi, String title, String snippet){
    if (snippet==""){snippet = null;}
     Marker m = mMap.addMarker(new MarkerOptions()
            .position(new LatLng(lati, longi))
            .title(title)
             .snippet(snippet)
            .draggable(true));
    markerList.add(m);
}

public void saveMarkers(){
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    markerCount = 0;
    for (Marker i : markerList) {
        //Save to sharedprefences
        markerCount++;

        editor.putString("lat" + Integer.toString((markerCount - 1)), String.valueOf(i.getPosition().latitude));
        editor.putString("lng" + Integer.toString((markerCount - 1)), String.valueOf(i.getPosition().longitude));
        editor.putString("title" + Integer.toString((markerCount - 1)),i.getTitle());
        editor.putString("snippet" + Integer.toString((markerCount - 1)),i.getSnippet());
        editor.putInt("markerCount", markerCount);

        editor.commit();
    }
}

private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

public void addGeofence(String key, double lat, double lng, int radius ){
    mGeofenceList.add(new Geofence.Builder()
            // Set the request ID of the geofence. This is a string to identify this
            // geofence.
            .setRequestId(key)

            .setCircularRegion(
                    lat,
                    lng,
                    radius
            )
            .setExpirationDuration(12*60*60*1000)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                    Geofence.GEOFENCE_TRANSITION_EXIT)
            .build());

    Circle circle = mMap.addCircle(new CircleOptions()
            .center(new LatLng(lat, lng))
            .radius(radius)
            .fillColor(Color.parseColor("#02bbff")));



}

@Override
public void onResult(@NonNull Status status) {
    if (status.isSuccess()) {
        // Update state and save in shared preferences.
        mGeofencesAdded = !mGeofencesAdded;
        Toast.makeText(
                this,
                getString(mGeofencesAdded ? R.string.geofences_added :
                        R.string.geofences_removed),
                Toast.LENGTH_SHORT
        ).show();
    } else {
        // Get the status code for the error and log it using a user-friendly message.
        String errorMessage = GeofenceErrorMessages.getErrorString(this,
                status.getStatusCode());
        Log.e(TAG, errorMessage);
    }
}
}
//谷歌地图
公共谷歌地图;
私人GoogleapClient MGoogleapClient;
LocationRequest MLLocationRequest=新的LocationRequest();
公共场所;
私有静态final int FINE\u LOCATION\u PERMISSION\u REQUEST=1;
专用静态最终int连接\u解析\u请求=2;
列表标记列表=新的ArrayList();
//临时变量
双lat=0;
双lon=0;
标记当前标记;
//请求信息变量
静态最终int GET_DETAILS=1;
静态最终整数编辑_详细信息=2;
//调试
私有静态最终字符串TAG=“GeekysMessage”;
SharedReferences SharedReferences;
国际马克计数;
专用工具栏;
//土工栅栏
私有布尔值mgeofenced;
ArrayList mGeofenceList=新的ArrayList();
私人吊挂帐篷管理围栏吊挂帐篷;
公众参与人数;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
toolbar=(toolbar)findviewbyd(R.id.my_toolbar);
设置支持操作栏(工具栏);
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
buildGoogleAppClient();
//土工栅栏
//用于存储地理围栏的空列表。
mGeofenceList=newarraylist();
//最初将addGeofences()和removeGeofences()中使用的PendingEvent设置为null。
mgeofencependingent=null;
}
@凌驾
受保护的void onResume(){
super.onResume();
buildGoogleAppClient();
if(mgoogleapClient.isConnected()){
startLocationUpdates();
}
}
//位置
私有void BuildGoogleAppClient(){
if(mGoogleApiClient==null){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
}
受保护的void createLocationRequest(){
mlLocationRequest=新位置请求();
mlLocationRequest.setInterval(10000);
mlLocationRequest.SetFastTestInterval(5000);
mLocationRequest.setPriority(位置请求.优先级高精度);
}
受保护的void onStart(){
mGoogleApiClient.connect();
super.onStart();
}
受保护的void onStop(){
mGoogleApiClient.disconnect();
super.onStop();
}
受保护的void startLocationUpdates(){
LocationServices.FusedLocationApi.RequestLocationUpdate(
mgoogleapclient,mLocationRequest,this);
}
@凌驾
未连接的公共无效(@Nullable Bundle){
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
if(mCurrentLocation==null){
mCurrentLocation=LocationServices.FusedLocationApi.getLastLocation(mgoogleapClient);
updateUI();
}
startLocationUpdates();
}
}
@TargetApi(Build.VERSION\u code.N)
@凌驾
已更改位置上的公共无效(位置){
mCurrentLocation=位置;
updateUI();
Toast.makeText(此“已更新”,
吐司。长度(短)。show();
}
私有void updateUI(){
}
@凌驾
公共空间连接暂停(int i){
Toast.makeText(此“连接挂起”,Toast.LENGTH_SHORT).show();
}
@凌驾
public void onconnection失败(@NonNull ConnectionResult ConnectionResult){
if(connectionResult.hasResolution()){
试一试{
connectionResult.startResolutionForResult(这是连接解析请求);
}catch(IntentSender.sendtintentexe){
//解析意图出错。请重试。
mGoogleApiClient.connect();
}
}否则{
Dialog Dialog=GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(),this,1);
dialog.show();
}
}
受保护的void stopLocationUpdates(){
//当活动处于暂停或暂停状态时,删除位置请求是一种很好的做法
//停止状态。这样做有助于电池性能,尤其是
//建议在要求频繁位置更新的应用程序中使用。
//{@code requestLocationUpdates()}的最后一个参数是LocationListener
// (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
LocationServices.FusedLocationApi.RemovelocationUpdate(mgoogleapClient,this);
}
@凌驾
受保护的void onPause(){
super.onPause();
//停止位置更新以节省电池,但不要断开GoogleAppClient对象的连接。
if(mgoogleapClient.isConnected()){
stopLocationUpdates();
}
}
int requestCode=0;
//地图
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
//加载所有保存的标记
loadMarkers();
LocationServices.GeofencingApi.AddGeofines(
MGoogleapClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(此);
//权限
如果(上下文)
Boolean fromOnMapReady = false;
@Override
public void onMapReady(GoogleMap googleMap) {
     fromOnMapReady = true;
protected void onStop() {
  if(!fromOnMapReady){
    mGoogleApiClient.disconnect();
  }
  super.onStop();
}