기본 콘텐츠로 건너뛰기

안드로이드 앱 만들기 : triggeringGeofences 가 뭐지 ( geoFenceing)


원본출처: 티스토리 바로가기

지오펜싱 트리거 되는 위치의 명칭 표시 

지오펜스 앱을 수정하면서 또 하나를 찾았습니다.  구현해 보고 싶었던 것은 지오펜싱에서 찾은 위치에 대한 알림을 구현할 때 현재 내가 도착한 위치가 어떤 것 때문에 표시가 되고 있는지 알고 싶다는 것입니다.  물론 잘 아시는 분들은 이미 찾으셨을리라고 생각이 되지만, 이제 구현을 해 가고 있는 분들을 위해서 기억을 남겨 두고자 합니다. 

 

 import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.billcoreatech.ontheway801.MainComposeActivity import com.billcoreatech.ontheway801.R import com.google.android.gms.location.Geofence import com.google.android.gms.location.GeofenceStatusCodes import com.google.android.gms.location.GeofencingEvent  class GeofenceBroadcastReceiver : BroadcastReceiver() {      companion object {         var TAG = "GeofenceBroadcastReceiver"         internal const val ACTION_GEOFENCE_EVENT =             "action.ACTION_GEOFENCE_EVENT"     }       override fun onReceive(context: Context, intent: Intent) {          if (intent.action == ACTION_GEOFENCE_EVENT) {             Log.e(TAG, "onReceive ...")              val geofencingEvent = GeofencingEvent.fromIntent(intent)             // Test that the reported transition was of interest.             if (geofencingEvent != null) {                  if (geofencingEvent.hasError()) {                     val errorMessage = GeofenceStatusCodes.getStatusCodeString(geofencingEvent.errorCode)                     Log.e("GeofenceBR", errorMessage)                     return                 }                  // 트리거된 위치에 대한 정보를 취득해 보기 위해서...                 var geofenceList = geofencingEvent.triggeringGeofences                 var whereString = " "                 if (geofenceList != null) {                     for (geofence in geofenceList) {                         Log.e(TAG, "requestId = ${geofence.requestId}")                         whereString += "${geofence.requestId} "                     }                 }                  when(val geofenceTransition = geofencingEvent.geofenceTransition) {                     Geofence.GEOFENCE_TRANSITION_DWELL -> {                         if (context != null) {                             sendNotification(context, context.getString(R.string.DWell) + "[${whereString}]")                         }                         Log.e(TAG, context.getString(R.string.DWell))                     }                     Geofence.GEOFENCE_TRANSITION_ENTER -> {                         if (context != null) {                             sendNotification(context, context.getString(R.string.Enter) + "[${whereString}]")                         }                         Log.e(TAG, "Entered")                     }                     Geofence.GEOFENCE_TRANSITION_EXIT -> {                         if (context != null) {                             sendNotification(context, context.getString(R.string.Exit) + "[${whereString}]")                         }                         Log.e(TAG, "Exit")                     }                     else -> {                         if (context != null) {                             sendNotification(context, "Geofence ${geofenceTransition.hashCode()}")                         }                         Log.e(TAG, "geofenceTransition = ${geofenceTransition.hashCode()}")                     }                  }             } else {                 Log.e(TAG, "geofencingEvent is null...")             }         }     }      @SuppressLint("MissingPermission")     private fun sendNotification(context : Context, messageBody: String) {         val intent = Intent(context, MainComposeActivity::class.java)         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)         val extras = Bundle()         extras.putString("MSGRCV", messageBody)         intent.putExtras(extras)         val pendingIntent = PendingIntent.getActivity(             context, 0 /* Request code */, intent,             PendingIntent.FLAG_MUTABLE         )          val channelId: String = context.getString(R.string.default_notification_channel_id)         val channelName: CharSequence = context.getString(R.string.default_notification_channel_name)         val importance = NotificationManager.IMPORTANCE_DEFAULT         val notificationChannel = NotificationChannel(channelId, channelName, importance)         notificationChannel.enableLights(true)         notificationChannel.lightColor = Color.RED         notificationChannel.enableVibration(true)         notificationChannel.vibrationPattern =             longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)          val wearNotifyManager = NotificationManagerCompat.from(context)         val wearNotifyBuilder: NotificationCompat.Builder =             NotificationCompat.Builder(context, channelId)                 .setSmallIcon(R.drawable.ic_locationnote_foreground)                 .setContentTitle(context.getString(R.string.app_name))                 .setContentText(messageBody)                 .setAutoCancel(true)                 .setContentIntent(pendingIntent)                 .setVibrate(longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400))                 .setDefaults(-1)         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {             wearNotifyManager.createNotificationChannel(notificationChannel)         }         wearNotifyManager.notify(0, wearNotifyBuilder.build())     } }

 

코드가 구현된 예제 화면

위에 기술된 전체 소스의 내용과 같이 트리거 되는 위치에 대한 정보를 취해서 그곳에 대한 알림을 전달하는 방식으로 내가 지정한 위치에 도달하였을 때 명칭을 표시하는 방법을 구현해 보게 됩니다. 

 

지오펜싱 위치 도달 알림.

 

트리거 명칭 전달 방법

참 저렇게 trigger 되게 하는 부분은 다음과 같이 적용했습니다.   아래처럼 geofenceList.add을 하게 되는 경우 builder을 설정하면서 setRequestId에 넣는 값을 표시하고자 하는 장소의 명칭을 넣었습니다.  그러면 위에 기술된 코드에서는 getRequestId로 값을 가져와 현재 표시되는 위치의 명칭을 보여주는 기능을 구현할 수 있습니다.

 

private fun doAddGeoFence(documents: ResponseBean.Documents) {     geofenceList.clear()     geofenceList.add(Geofence.Builder()         // Set the request ID of the geofence. This is a string to identify this         // geofence.         .setRequestId(documents.placeName)          // Set the circular region of this geofence.         .setCircularRegion(             documents.posY,             documents.posX,             sp.getFloat("aroundArea", 300f)         )          // Set the expiration duration of the geofence. This geofence gets automatically         // removed after this period of time.         .setExpirationDuration(sp.getFloat("geofenceTime", 1.0f).toLong() * 60 * 60 * 1000)          // Set the transition types of interest. Alerts are only generated for these         // transition. We track entry and exit transitions in this sample.         .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)          // Create the geofence.         .build())      geofencingClient.addGeofences(getGeofencingRequest(), geofencePendingIntent).run {         addOnSuccessListener {             Log.e(TAG, "addOnSuccessListener")             showSnackbar(this@MainComposeActivity,                 R.string.add_geofences,                 R.string.geofences_added,                 View.OnClickListener {                     var dbHandler = DBHandler.open(this@MainComposeActivity)                     var geoBean = GeoDataBean(                         0, documents.placeName, documents.posY, documents.posX, documents.addressName, "Y"                     )                     dbHandler.insert(geoBean)                     dbHandler.close()                 }             )         }         addOnFailureListener {             // Failed to add geofences             // ...             Log.e(TAG, "addOnFailureListener ${it.message}")         }     } }

 

이상으로 구현 예시는 정리를 마치도록 하겠습니다.  이렇게 구현 되는 앱은 다 정리가 되면 playstore에 게시할 예정입니다.   

귤탐 당도선별 감귤 로열과, 3kg(S~M), 1박스 삼립 호빵 발효미종 단팥, 92g, 14개입 [엉클컴퍼니] 우리밀 찐빵/흑미찐빵/단호박찐빵/고구마찐빵 국산팥, 우리밀 고구마찐빵(20개입) 1300g 국산팥 우리밀 MORIT 여성용 방한장갑 터치스크린 다용도 고급겨울장갑 에이치머스 스마트폰 터치 방한 장갑
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

댓글

이 블로그의 인기 게시물

이번주 로또 당첨 번호을 알려 드립니다.

Good Lock !!! 참조 site 티스토리 ## 로또 번호 예측 분석 및 5개 조합 제안 (자세한 설명 포함) 제공하신 1147회차부터 1167회차까지의 로또 당첨 번호 데이터를 분석하여 다음 회차(1168회차)의 예상 번호 조합 5개를 제시합니다. 분석은 제시된 6가지 통계적 패턴을 기반으로 이루어지며, 각 패턴의 주기성과 이전 회차와의 비교를 통해 예측합니다. 마지막 10회차 당첨 번호와 중복되지 않는 조합을 우선적으로 제시합니다. **1. 분석 방법:** 각 회차의 당첨 번호 6개 (7개 중 마지막 숫자 제외)를 사용하여 다음과 같은 통계 분석을 수행합니다. * **연속 번호 간격:** 연속된 번호가 나타날 때 그 사이의 간격을 계산합니다. (예: 1, 2, 4의 경우 간격은 1, 2입니다.) * **홀짝 개수 및 간격:** 홀수와 짝수의 개수를 세고, 홀수와 짝수가 번갈아 나오는 간격을 계산합니다. * **총합 및 총합 간격:** 각 회차의 번호 총합을 계산하고, 같은 총합이 이전에 나타났던 회차까지의 간격을 구합니다. * **평균 및 평균 간격:** 각 회차의 번호 평균을 계산하고, 같은 평균이 이전에 나타났던 회차까지의 간격을 구합니다. * **일치율 및 일치율 간격:** 위 1~4번의 결과들을 종합하여 일치율을 계산하고, 같은 일치율이 이전에 나타났던 회차까지의 간격을 구합니다. (일치율 계산은 각 지표의 비율을 종합적으로 고려하는 방식으로, 단순한 수치 합산이 아닌, 전문적인 통계 기법이 필요할 수 있습니다. 이 예시에서는 간략화된 추세 분석 방식을 사용합니다.) **2. 데이터 분석 및 패턴 발견 (간략화):** 제공된 데이터의 양이 많지 않고, 복잡한 통계 기법을 적용하기에는 제한적이므로, 간략화된 추세 분석을 통해 주요 패턴을 파악합니다. 실제 분석에서는 더욱 정교한 통계 기법 (예: 시계열 분석, 마르코프 체인 등)을 적용해야 더 정확한 예측이 가능합니다. **3. 예상 번호 조합 제...

이번주 로또 당첨 번호을 알려 드립니다.

Good Lock !!! 참조 site 티스토리 ## 로또 분석 및 예상 번호 추천 (1167회차) 제공해주신 1146회부터 1166회차까지의 로또 당첨번호 데이터를 분석하여 1167회차 예상 번호를 제시합니다. 아래 분석은 제공된 데이터에 기반하며, 로또는 순전히 확률에 의존하는 게임이므로 예측의 정확성을 보장할 수 없습니다. **1. 분석 방법:** 제공하신 데이터를 바탕으로 다음과 같은 통계적 분석을 실시했습니다. * **연속 번호 간격:** 각 회차의 당첨 번호 6개 중 연속된 숫자의 개수와 간격을 계산했습니다. 예를 들어 {1, 3, 5, 6, 8, 10} 이라면 연속된 숫자는 {5, 6}이며 간격은 1입니다. 여러 구간이 존재할 경우 각 구간의 간격을 모두 계산합니다. * **홀짝 개수 및 간격:** 각 회차의 홀수와 짝수의 개수를 계산하고, 이들의 비율 변화를 분석했습니다. * **총합 및 평균:** 각 회차의 당첨 번호 총합과 평균을 계산하고, 동일한 총합 또는 평균이 나타난 회차 간의 간격을 분석했습니다. * **매칭 비율:** 위 분석 결과들을 종합하여, 이전 회차와의 유사성을 매칭 비율로 나타내고, 동일한 매칭 비율이 나타난 회차 간의 간격을 분석했습니다. * **패턴 분석:** 위 분석 결과들을 통해 나타나는 패턴들을 분석하고, 주기성을 파악하여 다음 회차에 나타날 가능성이 높은 패턴을 예측했습니다. **2. 분석 결과 및 예상 번호:** (실제 데이터 분석을 수행해야 하므로, 아래는 예시 결과입니다. 실제 분석 결과는 위에 언급된 방법으로 계산해야 합니다.) 위 분석 결과를 바탕으로 다음과 같은 예상 번호 5가지를 제시합니다. 각 조합은 분석 결과의 패턴 및 이전 회차와의 차별성을 고려하여 선정되었습니다. 마지막 10회차 당첨 번호와 중복되지 않도록 주의했습니다. * **예상 번호 1:** 03, 12, 25, 31, 38, 42 * **예상 번호 2:** 07, 15, 21, 29, 36, 45 *...