Search code examples
androidandroid-geofence

onConnected does not respond on Android Geofence


When I run 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 says. Then I got SHA1 key of my application and add it into console.developers.google.com page for creating an API key. At the end I enabled both Google Maps Android API v2 and Google Play Android Developer APIs. When I run the code below, even though Google Api Client is build , mGoogleApiClient.isConnecting() function returns true but mGoogleApiClient.isConnected() function returns false.

Can someone tell me where I might be doing wrong ?

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>


Solution

  • Connect as most of network processes is asynchronous and yours mGoogleApiClient.connect() not happens immediately. You need to use listener to know when GoogleApiClient connected. As I see you added ConnectionCallbacks and OnConnectionFailedListener interfaces, but not uses they as needed. Your code that should performed after connection happens must be implemented in ConnectionCallbacks.onConnected(Bundle) method that overriden in yours Activity, like below:

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

    Also to activate Geofencing you need call of LocationServices.GeofencingApi.addGeofences(GoogleApiClient, GeofencingRequest, PendingIntent) after GoogleApiclient connected, i.e. in onConnected(Bundle) also. And not forget to set ResultCallback for Geofencing result (LocationServices.GeofencingApi.addGeofences(...).setResultCallback(resultCallback) - listener interface too).