공부방/Android

Android Notification for Oreo

soycrab 2018. 12. 13. 17:58

안드로이드 Oreo 버전  Notification 적용 하면서 알게된 점 정리 



1.  앱 알림 설정에서 기타 설정이 있는데, 

이부분은 FCM 에서 기본으로 정의한 채널이다.  

해당 채널을 없애고 싶다면, 



AndroidManifest 에서 

         <meta-data

            android:name="com.google.firebase.messaging.default_notification_channel_id"

            android:value="@string/default_notification_channel_id" />

        <meta-data

이 부분을 지워주고 별도의 채널을 만들어 주면 된다. 

* 사용자가 이미 설치 된 상태이면 재설치 전까지 
기본 채널이 없어지지 않습니다. 

2. FCM 콘솔창에서 PUSH 테스트를 할때, 
백그라운드 상태에서 앱 알림을 받으면  Custom FirebaseMessagingService
클래스의 onMessageReceived 함수를 호출하지 않는데 
이부분은 FCM 콘솔창을 사용하지 말고, 
메시지 데이터를 자신의 웹서버 쪽에서 따로 data에 감싸서 보내주어야 한다. 
* 이부분 때문에 앱이 백그라운드 상태일때 정의 해놓은 Notification 형태로 보여지지 않고 기본 형태로 보여지게 됩니다.

{


!!Push 데이터에 notification 이 포함 되어 있으면 백그라운드에서 onMessageReceived 를 

호출하지 않기 때문에 백그라운드 상태에서 위 함수를 호출하실분은  

notification 데이터를 지워주세요 

//"notification": {       

                        //title: 'Title of your push notification', 

                       // body: tempMsg 

                    //},



"data" : {
"message" : {
"channel": "1",
"title" : "tes1t111",
"content": "content",
"imageUrl" : "url"
}
}
"to" : "UsertokenID"
}


이런 형식으로 보내주면 App 이  BackGround 상태에서도 onMessageReceived를 호출한다.


만약 웹서버가 없다면 Postman을 이용하여 post 방식으로 다음과 같이 호출하면 된다 .


Url : https://fcm.googleapis.com/fcm/send


Header 

1. key: Content-Type value: application/json

2. key: Authorization value: key= FCM Sever Key


body

{
"data" : {
"message" : {
"channel": "1",
"title" : "tes1t111",
"content": "content",
"imageUrl" : "url"
}
}
"to" : "UsertokenID"
}


3. 그룹 및 채널 설정 

그룹 및 채널은 아이디가 같으면 Create를 호출하여도 재생성 되지 않습니다.

val notifManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notifManager.createNotificationChannelGroup(NotificationChannelGroup(GroupID, GroupName)

val notificationChannel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(
true)
notificationChannel.enableVibration(
true)
notificationChannel.
vibrationPattern = longArrayOf(100, 200)
notificationChannel.
group = groupId
notifManager.createNotificationChannel(notificationChannel)


4 Full Source


위에서 보낸 데이터 형식을 Gson 을 이용하여 Message 클래스를 정의 후 아래와 같이 처리가 가능합니다. 

GroupId, GroupName, ChannelId, ChannelName 등은 각자 정의를 해주시면 됩니다. 


class MyFirebaseMessagingService : FirebaseMessagingService() {

override fun onNewToken(token: String?) {
super.onNewToken(token)
sendTokenToRegisterOnServer(token)
}

private fun sendTokenToRegisterOnServer(token: String?) {
// Handle your logic
}

override fun onMessageReceived(rMsg: RemoteMessage?) {
rMsg?.let {
createNotificationChannels()
sendNotification(it.data)
}
}

private fun sendNotification(data : Map<String, String>) {
val gson = Gson()

val message = gson.fromJson(data["message"], NotificationMessage::class.java)

val channelId = message.channel

val notifManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

val builder = NotificationCompat.Builder(applicationContext, channelId)

val notificationIntent = Intent(applicationContext, MainActivity::class.java)

notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP

val requestID = System.currentTimeMillis().toInt()

val pendingIntent = PendingIntent.getActivity(applicationContext, requestID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)


builder
.setContentTitle(message.title)
.setContentText(message.content)
.setGroup(GroupId)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
.setBadgeIconType(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)

notifManager.notify(0, builder.build())
}

private fun createNotificationChannels() {

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val notifManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notifManager.createNotificationChannelGroup(NotificationChannelGroup(GroupId, GroupName))

val notificationChannel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(true)
notificationChannel.enableVibration(true)
notificationChannel.vibrationPattern = longArrayOf(100, 200)
notificationChannel.group = GroupId
notifManager.createNotificationChannel(notificationChannel)

}
}

}



반응형