기본 콘텐츠로 건너뛰기

안드로이드 앱 만들기 : FCM Message 수신


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

앞에서 python 코드를 이용해서 random 숫자를 만들고 FCM 전송하는 코드를 구현해 보았다면, 이번에 그걸 이용해서 수신하는 앱을 하나 만들어 볼 차례다.

 

https://billcorea.tistory.com/179

 

자작 앱 설명서 : 로또에 관심 있으세요?

https://play.google.com/store/apps/details?id=com.billcoreatech.getLotto Get Lotto 로또 번호를 드립니다. - Google Play 앱 매주 요청한 요일에 로또 번호를 무작위로 보내 드립니다. play.google.com 앱을..

billcorea.tistory.com

 

코드 구현은 kotlin으로 해 보았다.  이제 걸음마 단계이기 때문에 코드가 조금 길어질 수 도 있지만, 아직은 준비 중인 단계이기 때문에...

 

먼저 FCM을 수신하기 위해서는 firebase와 연동을 위한 gradle 구성이 필요하다.

 

import java.text.SimpleDateFormat  plugins {     id 'com.android.application'     id 'com.google.gms.google-services'     id 'com.google.firebase.crashlytics'     id 'kotlin-android-extensions'     id 'kotlin-android'     id 'kotlin-kapt' }  android {     compileSdk 32      defaultConfig {         applicationId "com.bi.......tto"         minSdk 28         targetSdk 32         versionCode 10         versionName "0.1.0"          testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"     }      buildTypes {         debug {             buildConfigField "Boolean", "DEBUG_MODE", "true"         }         release {             buildConfigField "Boolean", "DEBUG_MODE", "false"             minifyEnabled false             proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'         }     }      compileOptions {         sourceCompatibility JavaVersion.VERSION_1_8         targetCompatibility JavaVersion.VERSION_1_8     }      // jetPack compose add     buildFeatures {         viewBinding true     }      kotlinOptions {         jvmTarget = "1.8"     }      def archiveBuildType = ["release"]     applicationVariants.all { variant ->         variant.outputs.each { output ->             if (variant.buildType.name in archiveBuildType) {                 def df = new SimpleDateFormat("yyyyMMdd")                 df.setTimeZone(TimeZone.getDefault())                 if (variant.versionName != null) {                     String name = "GetLotto645_${df.format(new Date())}_${defaultConfig.versionCode}_${variant.versionName}.apk"                     output.outputFileName = name                 }             }         }     } }  dependencies {      implementation 'androidx.appcompat:appcompat:1.4.1'     implementation 'com.google.android.material:material:1.5.0'     implementation 'androidx.constraintlayout:constraintlayout:2.1.3'     implementation 'com.google.android.play:core:1.10.3'          // 파이어 베이스 연동을 위한 설정...     implementation platform('com.google.firebase:firebase-bom:29.2.1')     // 메시징     implementation 'com.google.firebase:firebase-messaging:23.0.2'     // 인증처리     implementation 'com.google.firebase:firebase-auth-ktx'     implementation 'com.google.android.gms:play-services-auth:20.1.0'     // realtime database     implementation 'com.google.firebase:firebase-database-ktx'     // crashlytics      implementation 'com.google.firebase:firebase-crashlytics-ktx'     implementation 'com.google.firebase:firebase-analytics-ktx'     // safetynet 앱 인증     implementation 'com.google.firebase:firebase-appcheck-safetynet:16.0.0-beta05'     implementation 'com.google.firebase:firebase-appcheck-debug:16.0.0-beta05'          implementation 'androidx.preference:preference-ktx:1.2.0'     testImplementation 'junit:junit:4.13.2'     androidTestImplementation 'androidx.test.ext:junit:1.1.3'     androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'     implementation "androidx.core:core-ktx:1.7.0"     implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"     implementation 'com.google.android.gms:play-services-ads:20.6.0'      implementation 'com.journeyapps:zxing-android-embedded:4.3.0'     implementation 'com.google.zxing:core:3.4.1'  }

 

다음은 manifest에 intenet 활용을 위한 permission 선언이 필요하고.

 

<uses-permission android:name="android.permission.INTERNET" />

그리고 service을 등록해야 한다. FCM 수신을 위한 리시버...

<service     android:name="com.billcoreatech.getLotto.utils.FcmReceiveService"     android:exported="true">     <intent-filter>         <action android:name="com.google.firebase.MESSAGING_EVENT" />     </intent-filter> </service>

 

다음은 kotlin으로 구현한 service 코드 (사실 개발자 문서의 내용을 그대로 옮겨 왔다고 해도 과언은 아닐 것이다.)

package com.b...................to.utils  import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.content.SharedPreferences import android.graphics.Color import android.media.RingtoneManager import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import com.billcoreatech.getLotto.MainActivity import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import getLotto.R  class FcmReceiveService : FirebaseMessagingService() {      var TAG:String = "FcmReceiveService"      override fun onMessageReceived(remoteMessage: RemoteMessage) {          // TODO(developer): Handle FCM messages here.         // Not getting messages here? See why this may be: https://goo.gl/39bRNJ         Log.e(TAG, "From: " + remoteMessage.from)          // Check if message contains a data payload.         if (remoteMessage.data.size > 0) {             Log.e(TAG, "Message data payload: " + remoteMessage.data)             sendNotification(remoteMessage.data["body"])             var sp = getSharedPreferences("Messageing", MODE_PRIVATE)             var editor = sp.edit()             editor.putString("SendMsg", remoteMessage.data["body"]);             editor.putBoolean("msgSet", true)             editor.commit()         }          // Check if message contains a notification payload.         if (remoteMessage.notification != null) {             Log.e(                 TAG, "Message Notification Body: " + remoteMessage.notification!!.body             )             sendNotification(remoteMessage.notification!!.body)         }         onDeletedMessages()     }      // [END receive_message]     override fun onNewToken(token: String) {         Log.e(TAG, "Refreshed token: $token")          // If you want to send messages to this application instance or         // manage this apps subscriptions on the server side, send the         // FCM registration token to your app server.         sendRegistrationToServer(token)     }     // [END on_new_token]     /**      * Handle time allotted to BroadcastReceivers.      */     private fun handleNow() {         Log.d(TAG, "Short lived task is done.")         val intent = Intent(this@FcmReceiveService, MainActivity::class.java)         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)         startActivity(intent)     }      /**      * Persist token to third-party servers.      *      * Modify this method to associate the user's FCM registration token with any      * server-side account maintained by your application.      *      * @param token The new token.      */     private fun sendRegistrationToServer(token: String) {         // TODO: Implement this method to send token to your app server.     }      /**      * Create and show a simple notification containing the received FCM message.      *      * @param messageBody FCM message body received.      */     private fun sendNotification(messageBody: String?) {         val intent = Intent(this, MainActivity::class.java)         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)         Log.e(TAG, "mesg=${messageBody}")          val pendingIntent = PendingIntent.getActivity(             this, 0 /* Request code */,             intent, PendingIntent.FLAG_IMMUTABLE         )         val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager         val channelId = getString(R.string.default_notification_channel_id)         val channelName: CharSequence = getString(R.string.default_notification_channel_name)         val importance = NotificationManager.IMPORTANCE_LOW         val notificationChannel = NotificationChannel(channelId, channelName, importance)         notificationChannel.enableLights(true)         notificationChannel.lightColor = Color.BLUE         notificationChannel.enableVibration(true)         notificationChannel.vibrationPattern =             longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)         notificationManager.createNotificationChannel(notificationChannel)         val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)         val notificationBuilder = NotificationCompat.Builder(this, channelId)             .setSmallIcon(R.mipmap.ic_logo645_foreground)             .setContentTitle(getString(R.string.fcm_message))             .setContentText(messageBody)             .setAutoCancel(true)             .setSound(defaultSoundUri)             .extend(                 NotificationCompat.WearableExtender()                     .setBridgeTag("Foo")                     .setContentIcon(R.mipmap.ic_logo645_foreground)             )             .setContentIntent(pendingIntent)          // Since android Oreo notification channel is needed.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {             val channel = NotificationChannel(                 channelId,                 "Channel human readable title",                 NotificationManager.IMPORTANCE_DEFAULT             )             notificationManager.createNotificationChannel(channel)         }          // Dismiss notification once the user touches it.         notificationBuilder.setAutoCancel(true)         notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())     }  }

필요한 부분만 일부 수정을 했다.

 

이번에 또 알게 된 부분이라면 전송할 때 코드 구현에 따라 수신되는 위치가 달라진다는 것이다. 

 

<data로 구현했을 때>

def lambda_handler(token, context):     FCMToken = token      Data = {'data': {'title': 'Lotto 보내 드립니다.', 'body': context}, 'to': FCMToken}     Headers = {'Content-type': 'application/json',                'Authorization': 'Key=AAAAR_..........................3uTasJ-DGfJKZkS-ccyNr0xhRHTepcuk4GaFoNMTADl4jvNFM1HYIRqzSLs219BxVA-T9frSd3VCSUIRXXn1PSxhOKgqroBVqTaxmWk'}     http = urllib3.PoolManager().request('POST', 'https://fcm.googleapis.com/fcm/send', headers=Headers,                                          body=json.dumps(Data))      return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}

 

<notification으로 구현했을 때>

def lambda_handler(token, context):     FCMToken = token      Data = {'notification': {'title': 'Lotto 보내 드립니다.', 'body': context}, 'to': FCMToken}     Headers = {'Content-type': 'application/json',                'Authorization': 'Key=AAAAR_0..........................uTasJ-DGfJKZkS-ccyNr0xhRHTepcuk4GaFoNMTADl4jvNFM1HYIRqzSLs219BxVA-T9frSd3VCSUIRXXn1PSxhOKgqroBVqTaxmWk'}     http = urllib3.PoolManager().request('POST', 'https://fcm.googleapis.com/fcm/send', headers=Headers,                                          body=json.dumps(Data))      return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}

같은 코드 이기는 하지만, 전송하는 parameter에 따라서 그걸 수신 앱에서는 다른 처리를 할 수 있다는 것이 된다. 

그래서 앞으로는 필요에 따라서 parameter을 다르게 해서 전송할 생각이다. 

 

 

notification 으로 호출할 때

 

body 로 호출 할 때

 

두 영상의 미묘한 차이를 찾을 수 있을까???   위에 기술한 fcmReceiceService 코드를 같이 보면서 이해를 해 보면 작은 차이을 알 수 있지 않을까 싶다.

 

오늘도 즐 코딩 ...

귤탐 당도선별 감귤 로열과, 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 *...