Skip to content

Commit

Permalink
#195 [FEAT] : Firebase Cloud Message 설정 및 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
HJinhee committed Feb 14, 2022
1 parent b5af884 commit 0c3153a
Show file tree
Hide file tree
Showing 8 changed files with 227 additions and 11 deletions.
3 changes: 3 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ dependencies {
implementation("com.squareup.okhttp3:okhttp:5.0.0-alpha.2")
implementation("com.google.firebase:firebase-common-ktx:20.0.0")
implementation("com.google.firebase:firebase-auth-ktx:21.0.1")
implementation("com.google.firebase:firebase-bom:29.1.0")
// implementation("com.google.firebase:firebase-analytics-ktx")
implementation("com.google.firebase:firebase-messaging:22.0.0")
kapt(KaptDependencies.hilt)

// DataStore
Expand Down
43 changes: 36 additions & 7 deletions app/google-services.json
Original file line number Diff line number Diff line change
@@ -1,33 +1,62 @@
{
"project_info": {
"project_number": "570607218249",
"project_id": "charo-c453f",
"storage_bucket": "charo-c453f.appspot.com"
"project_number": "273821551567",
"project_id": "charo-android",
"storage_bucket": "charo-android.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:570607218249:android:28f17d5a480df79742d998",
"mobilesdk_app_id": "1:273821551567:android:71081779a86829e57660ba",
"android_client_info": {
"package_name": "com.example.charo_android"
}
},
"oauth_client": [
{
"client_id": "273821551567-mu7ln5scos0nuffo78v50f161p70g66i.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyBhg8XQiG_v3HUQTkv2N679CygRxcBb8UM"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "273821551567-mu7ln5scos0nuffo78v50f161p70g66i.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:273821551567:android:a3ce90298ee43dea7660ba",
"android_client_info": {
"package_name": "com.hjinhee.android"
}
},
"oauth_client": [
{
"client_id": "570607218249-6osutorq2vh0q71gvcus4e6n6c5d4n5j.apps.googleusercontent.com",
"client_id": "273821551567-mu7ln5scos0nuffo78v50f161p70g66i.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAd08-9nqjDdEj6Bx-DTB0dxAPvch3lDdE"
"current_key": "AIzaSyBhg8XQiG_v3HUQTkv2N679CygRxcBb8UM"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "570607218249-6osutorq2vh0q71gvcus4e6n6c5d4n5j.apps.googleusercontent.com",
"client_id": "273821551567-mu7ln5scos0nuffo78v50f161p70g66i.apps.googleusercontent.com",
"client_type": 3
}
]
Expand Down
9 changes: 9 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@
android:theme="@style/Theme.ChaRoAndroid"
android:usesCleartextTraffic="true"
tools:replace="android:appComponentFactory">
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>

<activity
android:name=".presentation.ui.follow.FollowActivity"
android:exported="false" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package com.example.charo_android

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import com.example.charo_android.presentation.ui.alarm.AlarmActivity
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService : FirebaseMessagingService() {
private val TAG = "MyFirebaseMessagingService"

override fun onNewToken(token: String) {
Log.d(TAG, "new Token: $token")
sendRegistrationToServer(token)
}

private fun sendRegistrationToServer(token : String) {

}

override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage != null) {
Log.d(TAG, "From: " + remoteMessage.data)
Log.i("notice 바디: ", remoteMessage.notification?.title.toString())
Log.i("notice 타이틀: ", remoteMessage.notification?.body.toString())
sendMainNotification(remoteMessage)
sendNotification(remoteMessage)
} else {
Log.i("notice 수신에러: ", "data가 비어있습니다. 메시지를 수신하지 못했습니다.")
Log.i("notice data 값: ", remoteMessage.data.toString())
}
}

private fun sendMainNotification(remoteMessage: RemoteMessage) {
val uniId = remoteMessage.sentTime.toInt()

val intent = Intent(this, AlarmActivity::class.java)
intent.putExtra("isOpenFromPushAlarm", true)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

val pendingIntent = PendingIntent.getActivity(
this, uniId, intent, PendingIntent.FLAG_ONE_SHOT
)

val channelId = "Notification Main Message"

val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

val notificationBuilder =
NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_main_logo_blue)
.setContentTitle(remoteMessage.notification?.title.toString())
.setContentText(remoteMessage.notification?.body.toString())
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)

val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel =
NotificationChannel(channelId, "Notice", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(uniId, notificationBuilder.build())
}


private fun sendNotification(remoteMessage: RemoteMessage) {
val uniId = remoteMessage.sentTime.toInt()

val intent = Intent(this, MyFirebaseMessagingService::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

val pendingIntent = PendingIntent.getActivity(
this, uniId, intent, PendingIntent.FLAG_ONE_SHOT
)

val channelId = "Notification Message"

val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

val notificationBuilder =
NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_main_logo_blue)
.setContentTitle(remoteMessage.notification?.title.toString())
.setContentText(remoteMessage.notification?.body.toString())
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)

val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel =
NotificationChannel(channelId, "Notice", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(uniId, notificationBuilder.build())
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
package com.example.charo_android.presentation.ui.alarm

import android.app.NotificationChannel
import android.app.NotificationManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.recyclerview.widget.ItemTouchHelper
import com.example.charo_android.R
import com.example.charo_android.data.api.ApiService
import com.example.charo_android.data.model.response.alarm.ResponseAlarmDeleteData
import com.example.charo_android.data.model.response.alarm.ResponseAlarmListData
Expand All @@ -24,6 +31,10 @@ class AlarmActivity : AppCompatActivity() {
super.onCreate(savedInstanceState)
binding = ActivityAlarmBinding.inflate(layoutInflater)
setContentView(binding.root)

//fcm test
sendFCM()

goHome()
alarmViewModel = AlarmViewModel()

Expand Down Expand Up @@ -184,6 +195,41 @@ class AlarmActivity : AppCompatActivity() {
})
}

private fun sendFCM(){
var NOTIFICATION_CHANNEL_ID = "0000"
var NOTIFICATION_CHANNEL_NAME = "ChaRo-Android"
var notificationManager = getSystemService(NotificationManager::class.java) as NotificationManager?

val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_LOW
val notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
importance
)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.vibrationPattern =
longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
notificationManager?.createNotificationChannel(notificationChannel)
}

val mNotificationBuilder: NotificationCompat.Builder =
NotificationCompat.Builder(applicationContext,NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_main_logo_blue)
.setContentTitle("ChaRo")
.setContentText("새로운 드라이브 코스를 확인하세요!")
// .setAutoCancel(false)

notificationManager!!.notify(0, mNotificationBuilder.build())
}
}, 0)
}

private fun goHome() {
binding.imgBackHomeAlarm.setOnClickListener {
onBackPressed()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import com.example.charo_android.presentation.ui.write.WriteShareActivity
import com.example.charo_android.presentation.util.LoginUtil
import com.example.charo_android.presentation.util.SharedInformation
import com.example.charo_android.presentation.util.replaceFragment
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.messaging.FirebaseMessaging
import org.koin.androidx.viewmodel.ext.android.viewModel

class MainActivity : AppCompatActivity() {
Expand Down Expand Up @@ -70,6 +72,7 @@ class MainActivity : AppCompatActivity() {
initNavView()
lookFor()

initFirebase()

}

Expand Down Expand Up @@ -211,4 +214,21 @@ class MainActivity : AppCompatActivity() {
}
}
}

private fun initFirebase(){
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(
"FirebaseTAG",
"Fetching FCM registration token failed",
task.exception
)
return@OnCompleteListener
} else {
val token = task.result
val msg = getString(R.string.msg_token_fmt, token)
Log.d("Firebase Success", msg)
}
})
}
}
1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -202,5 +202,6 @@
<string name="detail_menu_edit">수정하기</string>
<string name="detail_menu_delete">삭제하기</string>
<string name="no_select">선택안함</string>
<string name="msg_token_fmt">fcm token: %s</string>

</resources>
6 changes: 2 additions & 4 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,15 @@ buildscript {
repositories {
google()
mavenCentral()


}

dependencies {
classpath("com.android.tools.build:gradle:7.0.4")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10")
// classpath(ClassPathDependencies.hilt)
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin_version}")
classpath(ClassPathDependencies.hilt)
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files

classpath("com.google.gms:google-services:4.3.10")
}
}
Expand Down

0 comments on commit 0c3153a

Please sign in to comment.