onConnected 在 Android 地理围栏上没有响应

onConnected does not respond on Android Geofence

当我运行sample codes for android geofence, It works well. However in order to implement geofence on my own project, I tried to set up it by myself. Firstly I add some codes on build.gradle file and manifest file as documentation说。然后我得到了我的应用程序的 SHA1 密钥并将其添加到 console.developers.google.com 页面以创建 API 密钥。最后我启用了 Google Maps Android API v2 和 Google Play Android Developer APIs。当我 运行 下面的代码时,即使 Google Api 客户端正在构建,mGoogleApiClient.isConnecting() 函数 returns true 但 mGoogleApiClient.isConnected() 函数returns 错误。

谁能告诉我哪里做错了?

public class MainActivity extends ActionBarActivity implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {
protected ArrayList<Geofence> mGeofenceList;
protected GoogleApiClient mGoogleApiClient;
private PendingIntent mGeofencePendingIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buildGoogleApiClient();
    mGeofenceList = new ArrayList<Geofence>();

    mGeofenceList.add(new Geofence.Builder().setRequestId("ITU_Tekno_kent").setCircularRegion(41.107993, 29.032625, 1609).setExpirationDuration(100000).setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
            Geofence.GEOFENCE_TRANSITION_EXIT).build());
    mGoogleApiClient.connect();
    if (mGoogleApiClient.isConnecting()) {
        Toast.makeText(this, "connecting", Toast.LENGTH_SHORT).show();

    }
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, "not connected", Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                // The GeofenceRequest object.
                getGeofencingRequest(),
                // A pending intent that that is reused when calling removeGeofences(). This
                // pending intent is used to generate an intent when a matched geofence
                // transition is observed.
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        Log.i("catch","d");
       // logSecurityException(securityException);
    }
}

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);
}
private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();

    // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
    // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
    // is already inside that geofence.
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);

    // Add the geofences to be monitored by geofencing service.
    builder.addGeofences(mGeofenceList);

    // Return a GeofencingRequest.
    return builder.build();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build()    ;
}
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

@Override
public void onResult(Status status) {

}

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hangaar.geofencingtest2" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".GeofenceTransitionsIntentService"/>
    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
</application>

连接,因为大多数网络进程是异步的,您的 mGoogleApiClient.connect() 不会立即发生。您需要使用侦听器来了解 GoogleApiClient 何时连接。如我所见,您添加了 ConnectionCallbacks 和 OnConnectionFailedListener 接口,但未根据需要使用它们。连接发生后应执行的代码必须在 ConnectionCallbacks.onConnected(Bundle) 方法中实现,该方法在您的 Activity 中覆盖,如下所示:

@Override
public void onConnected(Bundle bundle) {
    Toast.makeText(this, "Connected!", Toast.LENGTH_SHORT).show();
}

此外,要激活 Geofencing,您还需要在 GoogleApiclient 连接后调用 LocationServices.GeofencingApi.addGeofences(GoogleApiClient, GeofencingRequest, PendingIntent),即在 onConnected(Bundle) 中。并且不要忘记为地理围栏结果设置 ResultCallback(LocationServices.GeofencingApi.addGeofences(...).setResultCallback(resultCallback) - 监听器接口)。