geofencingClient = LocationServices.getGeofencingClient(this)
<receiver
android:name="kr.kro.fatcats.maptest.geofence.receiver.GeofenceBroadcastReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.location.MODE_CHANGED" />
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>
geofenceList.add(Geofence.Builder()
.setRequestId("1")
.setCircularRegion(37.4826524,126.8842739,1000F)
.setExpirationDuration(100000)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER).build())
geofencingClient.addGeofences(getGeofencingRequest(),geofencePendingIntent)?.run{
addOnSuccessListener{
// 성공 시 동작
}
addOnFailureListener{
// 실패 시 동작
}
}
setCircularRegion 에 위경도 값과, geofence의 범위를 정해줌 ( 미터단위, Float )
setExpirationDuration 는 선언 하지 않아도 무관하나 문서에선
선언하여 사용하는 것 이 권장 사항
배터리 소모로부터 기기를 보호하려면 위치 업데이트를 중단해야 할 시점에 적절한 시간 초과를 설정해야함. 이렇게 시간 초과를 설정하면 업데이트가 무한히 계속되지 않도록 하고, (가령 코드의 버그로 인해) 업데이트를 요청했지만 삭제되지 않은 시나리오에서 앱을 함.
융합된 위치 제공자 요청의 경우 setExpirationDuration() 을 호출해서 시간 초과를 추가. 이는 이 메서드를 마지막으로 호출한 시점 이후부터의 시간을 밀리초 단위로 나타내는 매개변수를 수신. 또한 setExpirationTime()을 호출해도 시간 초과를 추가할 수 있음. 이는 시스템이 마지막으로 부팅된 시점 이후부터의 만료 시간을 밀리초 단위로 나타내는 매개변수를 수신함.
지오펜스 위치 요청에 시간 초과를 추가하려면 setExpirationDuration()메서드를 호출함.
getGeofencingRequest()
private fun getGeofencingRequest(): GeofencingRequest {
return GeofencingRequest.Builder().apply {
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
addGeofences(geofenceList)
}.build()
}
트리거는
INITIAL_TRIGGER_ENTER( 들어갈때 )
INITIAL_TRIGGER_EXIT (나올때)
INITIAL_TRIGGER_DWELL (일정 시간 머무를 때 ) → 객체 생성시 setLoiteringDelay() 를 정의하고
setTransitionTypes 의 값을 Geofence.*GEOFENCE_TRANSITION_DWELL 로 정의
geofencePendingIntent
private val geofencePendingIntent: PendingIntent bylazy{
val intent = Intent(requireContext(), GeofenceBroadcastReceiver::class.java)
val pendingIntent: PendingIntent =
PendingIntent.getBroadcast(
requireContext(), 0, intent, PendingIntent.FLAG_MUTABLE
)
pendingIntent
}
BroadcastReceiver
override fun onReceive(context: Context, intent: Intent) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
val geofenceList = geofencingEvent?.triggeringGeofences
if (geofencingEvent != null) {
if (geofencingEvent.hasError()) {
val errorMessage = GeofenceStatusCodes
.getStatusCodeString(geofencingEvent.errorCode)
return
}
}
Toast.makeText(context, "도착 했습니다.", Toast.LENGTH_SHORT).show()
}
최종적으로 값을 처리 하면 됨.
내용에 문제가 있거나 다른 의견이 있으시다면 댓글 부탁드립니다.