要触发Android围栏,必须在应用程序中请求位置更新。一种常见的方法是在位置服务中注入LocationListener并使用PendingIntent将其与围栏关联。以下是代码示例:
// 注入位置服务
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// 创建围栏
Geofence geofence = new Geofence.Builder()
.setRequestId("myGeofence") // 给围栏一个ID
.setCircularRegion(latitude, longitude, radius) // 指定围栏中心点和半径
.setExpirationDuration(Geofence.NEVER_EXPIRE) // 指的是围栏有效期,这样指定代表永久存在
.setNotificationResponsiveness(1000)// 指定回调时间
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) // 监听进出事件
.build();
// 创建PendingIntent
Intent intent = new Intent(context, GeofenceIntentService.class);
intent.putExtra(GeofenceUtils.EXTRA_GEOFENCE_ID, geofence.getRequestId());
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 注入位置监听器
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 1000, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 添加围栏
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
geofencingClient.addGeofences(getGeofencingRequest(geofence), pendingIntent);
}
});