我对示例代码也有一些麻烦。这对我有用。
latitude = sharedPreferences.getFloat("storeAddress_lat", -1);
longitude = sharedPreferences.getFloat("storeAddress_lng", -1);
final ArrayList<Geofence> list = new ArrayList<Geofence>();
Builder builder = new Geofence.Builder();
builder.setRequestId("near_store_geofence");
builder.setCircularRegion(latitude, longitude, 50);
builder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER);
builder.setExpirationDuration(Geofence.NEVER_EXPIRE);
list.add(builder.build());
builder = new Geofence.Builder();
builder.setRequestId("leave_store_geofence");
builder.setCircularRegion(latitude, longitude, 50);
builder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_EXIT);
builder.setExpirationDuration(Geofence.NEVER_EXPIRE);
list.add(builder.build());
final GooglePlayServicesClient.ConnectionCallbacks connectionCallbacks = new GooglePlayServicesClient.ConnectionCallbacks(){
@Override
public void onConnected(Bundle connectionHint) {
Log.i("GEOFENCE","onConnected");
// Create an explicit Intent
Intent intent = new Intent(getBaseContext(), ReceiveTransitionsIntentService.class);
/*
* Return the PendingIntent
*/
PendingIntent pendingIntent = PendingIntent.getService(
getBaseContext(),
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
locationClient.addGeofences(list,pendingIntent, new OnAddGeofencesResultListener(){public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
Log.i("GEOFENCE","onAddGeofencesResult");
}});
LocationRequest locationrequest = LocationRequest.create();
locationrequest.setPriority(locationrequest.PRIORITY_HIGH_ACCURACY);
locationrequest.setInterval(5000);
locationClient.requestLocationUpdates(locationrequest, new LocationListener(){
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}});
}
@Override
public void onDisconnected() {
Log.i("GEOFENCE","onDisconnected");
}
};
GooglePlayServicesClient.OnConnectionFailedListener onConnectionFailedListener = new GooglePlayServicesClient.OnConnectionFailedListener(){
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("GEOFENCE","onConnectionFailed");
}
};
locationClient = new LocationClient(getBaseContext(), connectionCallbacks, onConnectionFailedListener);
locationClient.connect();