这里是样品c颂我写的,它的工作对我罚款
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) {
}
}
那么整个最后的项目有很多小时花费在后期工作,它被熟成Android。只是我的运气:)感谢您的建议,但可能会改写它。 – maschwenk 2013-05-16 21:52:13
你有没有参考100 geofences的限制?我无法找到有关此限制的任何信息或线索...... – usb79 2013-06-11 16:13:39
@ usb79虽然开发人员表示会对Geofences的限制做出澄清,但在Google I/O中提到了它。他们可能已经将其删除。我会编辑我的答案。 – Ejmedina 2013-06-11 19:51:25