這裏是樣品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