这是我编写的示例代码,对我来说效果很好
public class LocationClientService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationClient.OnAddGeofencesResultListener {
private LocationClient mLocationClient;
private List<Geofence> mGeofenceLists = new ArrayList<Geofence>();
@Override
public void onCreate() {
super.onCreate();
Geofence geofence1 = new Geofence.Builder()
.setRequestId("your target place")
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(0.0, 0.0, 2000.0f)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofenceLists.add(geofence1);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(this, TransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void onConnected(Bundle bundle) {
mLocationClient.addGeofences(mGeofenceLists, getPendingIntent(), this);
}
@Override
public void onDisconnected() {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onDestroy() {
mLocationClient.disconnect();
super.onDestroy();
}
@Override
public void onAddGeofencesResult(int i, String[] strings) {
if (LocationStatusCodes.SUCCESS == i) {
//todo check geofence status
} else {
}
}
}
然后编写一个 IntentService 来接收地理围栏进入或退出:
public class TransitionsIntentService extends IntentService {
public static final String TRANSITION_INTENT_SERVICE = "ReceiveTransitionsIntentService";
public TransitionsIntentService() {
super(TRANSITION_INTENT_SERVICE);
}
@Override
protected void onHandleIntent(Intent intent) {
if (LocationClient.hasError(intent)) {
//todo error process
} else {
int transitionType = LocationClient.getGeofenceTransition(intent);
if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ||
transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
for (Geofence geofence : triggerList) {
Log.i("test", "triggered Id " + geofence.getRequestId());
}
}
generateNotification(transitionType);
}
}
private void generateNotification(int type) {
}
}