Fence API 개요
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Awareness API에서 펜스 개념은 지리적 지역 또는 지오펜스가 정의되고 사용자가 지오펜스 지역에 진입하거나 이 지역을 벗어날 때 앱이 콜백을 수신하는 지오펜싱에서 가져옵니다. Fence API는 지리적 근접성 외에도 다른 여러 컨텍스트 조건을 포함하도록 지오펜싱 개념을 확장합니다. 앱은 컨텍스트 상태가 전환될 때마다 콜백을 수신합니다. 예를 들어 앱에서 헤드폰의 울타리를 정의하면 헤드폰이 연결될 때와 연결 해제될 때 콜백을 수신합니다.
Fence API를 사용하여 다음과 같은 컨텍스트 신호를 기반으로 울타리를 정의할 수 있습니다.
- 사용자의 현재 위치 (위도/경도)
- 걷기, 운전 등 사용자의 현재 활동
- 헤드폰 연결 여부와 같은 기기별 조건
- 주변 비콘과의 근접성
Fence API를 사용하면 여러 컨텍스트 신호를 결합하여 AND
, OR
, NOT
불리언 연산자로 울타리를 만들 수 있습니다. 그러면 앱은 펜스 조건이 충족될 때마다 콜백을 수신합니다. 가능한 울타리의 예는 다음과 같습니다.
- 사용자가 헤드폰을 연결하고 걷기 시작합니다.
- 사용자가 평일 오후 5시 이전에 100m 지오펜스를 진입합니다.
- 사용자가 특정 BLE 비콘의 범위에 진입합니다.
다음 예는 사용자가 걸을 때마다 활성화되는 울타리를 정의하는 방법을 보여줍니다.
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
펜스를 정의한 후에는 다음을 실행해야 합니다.
updateFences
를 호출하여 콜백을 수신하도록 펜스를 등록합니다.
- 울타리 상태가 변경될 때 호출할 수 있는 콜백을 정의합니다.
다음 예는 펜스를 만들고 등록하는 메서드를 보여줍니다. 이 예에서는 펜스가 트리거될 때 인텐트를 처리하는 데 BroadcastReceiver
의 맞춤 서브클래스가 사용됩니다.
Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder()
.addFence(FENCE_KEY, exercisingWithHeadphonesFence, mPendingIntent)
.build())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "Fence was successfully registered.");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Fence could not be registered: " + e);
}
});
public class FenceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
FenceState fenceState = FenceState.extract(intent);
if (TextUtils.equals(fenceState.getFenceKey(), FENCE_KEY)) {
String fenceStateStr;
switch (fenceState.getCurrentState()) {
case FenceState.TRUE:
fenceStateStr = "true";
break;
case FenceState.FALSE:
fenceStateStr = "false";
break;
case FenceState.UNKNOWN:
fenceStateStr = "unknown";
break;
default:
fenceStateStr = "unknown value";
}
mLogFragment.getLogView().println("Fence state: " + fenceStateStr);
}
}
}
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-31(UTC)
[null,null,["최종 업데이트: 2025-08-31(UTC)"],[[["\u003cp\u003eThe Awareness API uses fences, inspired by geofencing, to trigger app callbacks based on various context signals like location, user activity, and device conditions.\u003c/p\u003e\n"],["\u003cp\u003eYou can define fences using the Fence API by combining context signals with boolean operators (AND, OR, NOT) to create specific conditions.\u003c/p\u003e\n"],["\u003cp\u003eApps receive callbacks when a fence's conditions are met, such as when a user starts walking while wearing headphones or enters a designated area.\u003c/p\u003e\n"],["\u003cp\u003eTo utilize fences, register them using \u003ccode\u003eupdateFences\u003c/code\u003e and define a callback (e.g., using a \u003ccode\u003eBroadcastReceiver\u003c/code\u003e) to handle fence state changes.\u003c/p\u003e\n"]]],["The Fence API expands upon geofencing by allowing apps to define fences based on various context conditions. These include user location, activity, device status, and proximity to beacons. Fences can combine multiple context signals using boolean operators, triggering callbacks when conditions are met. To use a fence, you define it, register it via `updateFences`, and create a callback (like a `BroadcastReceiver`) to respond to state changes. The callback's state will reflect `TRUE`, `FALSE`, or `UNKNOWN`.\n"],null,["# Fence API overview\n\nIn the Awareness API, the concept of *fences* is taken from\n[geofencing](https://developer.android.com/training/location/geofencing),\nin which a geographic region, or *geofence*, is defined, and an app receives\ncallbacks when a user enters or leaves the geofence region. The Fence API expands on\nthe concept of geofencing to include many other context conditions in addition\nto geographical proximity. An app receives callbacks whenever the context\nstate transitions. For example, if your app defines a fence for headphones,\nit gets callbacks when the headphones are plugged in and when they're\nunplugged.\n\nYou can use the\n[Fence API](/android/reference/com/google/android/gms/awareness/Awareness#getFenceClient(android.app.Activity))\nto define fences based on context signals, such as the following:\n\n- The user's current location (latitude/longitude)\n- The user's current activity, like walking or driving.\n- Device-specific conditions, such as whether the headphones are plugged in.\n- Proximity to nearby beacons\n\nThe Fence API lets you combine multiple\n[context signals](/awareness/overview#context-types)\nto create fences with `AND`, `OR`, and `NOT` boolean operators. Your app then\nreceives callbacks whenever the fence conditions are met. Some examples of\npossible fences include the following:\n\n- User plugs in headphones and starts to walk.\n- User enters a 100-meter geofence before 5 PM on a weekday.\n- User enters range of a specific BLE beacon.\n\nThe following example shows how to define a fence that activates whenever\nthe user walks: \n\n AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);\n\nOnce you've defined a fence, you must do the following:\n\n- Call [`updateFences`](/android/reference/com/google/android/gms/awareness/FenceClient#updateFences(com.google.android.gms.awareness.fence.FenceUpdateRequest)) to register the fence to receive callbacks.\n- Define a callback that can be invoked when the fence state changes.\n\nThe following example shows a method that creates and registers a fence. In\nthis example, a custom subclass of `BroadcastReceiver` is used to handle the\nintent when the fence is triggered. \n\n Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder()\n .addFence(FENCE_KEY, exercisingWithHeadphonesFence, mPendingIntent)\n .build())\n .addOnSuccessListener(new OnSuccessListener\u003cVoid\u003e() {\n @Override\n public void onSuccess(Void aVoid) {\n Log.i(TAG, \"Fence was successfully registered.\");\n }\n })\n .addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n Log.e(TAG, \"Fence could not be registered: \" + e);\n }\n });\n public class FenceReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n\n FenceState fenceState = FenceState.extract(intent);\n\n if (TextUtils.equals(fenceState.getFenceKey(), FENCE_KEY)) {\n String fenceStateStr;\n switch (fenceState.getCurrentState()) {\n case FenceState.TRUE:\n fenceStateStr = \"true\";\n break;\n case FenceState.FALSE:\n fenceStateStr = \"false\";\n break;\n case FenceState.UNKNOWN:\n fenceStateStr = \"unknown\";\n break;\n default:\n fenceStateStr = \"unknown value\";\n }\n mLogFragment.getLogView().println(\"Fence state: \" + fenceStateStr);\n }\n }\n }"]]