您应该使用目标坐标(F 位)注册一个GEOFENCE_TRANSITION_ENTER
或地理围栏。GEOFENCE_TRANSITION_DWELL
在您的 Activity/Fragment onCreate 中,您应该创建 Api 客户端:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
还要记住连接/断开连接:
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
然后,onConnected
您应该执行以下操作:
LocationServices.GeofencingApi.addGeofences(mGoogleApiClient,
geofenceRequest,
pendingIntent)
您应该只添加一次地理围栏。
使用 GeofencingRequest.Builder 构建 geofenceRequest 的位置:
geofenceRequest = new GeofencingRequest.Builder().addGeofence(yourGeofence).build()
你的Geofence和pendingIntent在哪里:
yourGeofence = new Geofence.Builder()....build(); // Here you have to set the coordinate of Place F and GEOFENCE_TRANSITION_ENTER/GEOFENCE_TRANSITION_DWELL
pendingIntent = PendingIntent.getService(this,
(int)(System.currentTimeMillis()/1000),
new Intent(this, GeofenceTransitionsIntentService.class),
PendingIntent.FLAG_UPDATE_CURRENT);
GeofenceTransitionsIntentService 可能是这样的:
public class GeofenceTransitionsIntentService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (!geofencingEvent.hasError()) {
int geofenceTransition = geofencingEvent.getGeofenceTransition();
if (geofenceTransition != -1) {
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
if (triggeringGeofences != null && triggeringGeofences.size() > 0) {
Geofence geofence = triggeringGeofences.get(0);
// Do something with the geofence, e.g. show a notification using NotificationCompat.Builder
}
}
}
}
}
请记住在您的清单中注册此服务:
<service android:name=".GeofenceTransitionsIntentService"/>
GeofenceTransitionsIntentService.onHandleIntent()
即使应用程序关闭也会被调用。
希望能帮助到你。