seops

[Firebase] 3. SimplePush 본문

Android/Android

[Firebase] 3. SimplePush

seops 2020. 10. 4. 22:53

추석 연휴가 지났다. 내일부터 다시 출근이라니... 이슈가 많이 쌓였겠지...

 

오늘은 Firebase를 활용한 SimplePush 앱을 개발해볼 예정이다.

 

우선, SimplePush 프로젝트에 Firebase를 연동한다.

기존에 "[Firebase] 1번 글"에서 언급했다시피, Firebase 페이지에서 시키는 대로 연동을 해본다.

 

이를 완료하고, Firebase 페이지에서 Push를 쏘면 정상 동작하지 않는다. FirebaseMessaging을 위해서는 아래 sdk를 추가해준다.

 

[ app > build.gradle ]

    implementation "com.google.firebase:firebase-analytics-ktx:$firebase_analytics_version"
    implementation "com.google.firebase:firebase-messaging-ktx:$firebase_messaging_version"

다시 테스트 해보니, 예상대로 앱의 포그라운드에서는 Push가 오지 않으나, 백그라운드 상태에서 Push가 오는 것을 확인했다.

앱을 죽이고 난 후에도 Push가 오지 않는 것을 확인했다.

 

위 상황을 처리해주기 위해서는, FirebaseMessaging을 상속받는 클래스를 생성해준다.

 

[ SimpleMsgService ]

package com.seosh.simplepush

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.provider.Settings
import android.util.Log
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class SimpleMsgService : FirebaseMessagingService() {
    companion object {
        const val TAG = "[SimpleMsgService]"
        const val REQ_CODE = 0
        const val NOTIFICATION_CHANNEL_ID = "SimplePush"
    }

    override fun onMessageReceived(msg: RemoteMessage) {
        super.onMessageReceived(msg)

        Log.d("seosh", "${TAG} message : ${msg.notification.toString()}")

        val title = msg.notification?.title ?: "No title"
        val message = msg.notification?.body ?: ""

        createPushMsg(title = title, msg = message)
    }

    private fun createPushMsg(title: String, msg: String) {
        val intent = Intent(this, LoginActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }

        val pendingIntent = PendingIntent.getActivity(this, REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val mBuilder = NotificationCompat.Builder(this).apply {
            setSmallIcon(R.mipmap.ic_launcher)
            setContentTitle(title)
            setContentText(msg)
            setAutoCancel(false)
            setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            setContentIntent(pendingIntent)
        }

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID,
                "Push", NotificationManager.IMPORTANCE_HIGH).apply {
                enableLights(true)
                lightColor = Color.RED
                enableVibration(true)
                vibrationPattern = longArrayOf(20L, 300L, 200L, 100L)

            }

            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID)
            notificationManager.createNotificationChannel(notificationChannel)
        }

        notificationManager.notify(REQ_CODE, mBuilder.build())
    }
}

 

[ Manifest ]

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seosh.simplepush">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--Firebase Messaging-->
        <service
            android:name=".SimpleMsgService"
            android:exported="false">

            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_launcher_background" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="SimplePush" />


        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".LoginActivity" />

    </application>

</manifest>

 

[ Full Source ]

github.com/Seops34/SimplePush

 

Seops34/SimplePush

Contribute to Seops34/SimplePush development by creating an account on GitHub.

github.com

 

직접 개발해보니, 글로 정리만하면 안 됨을 다시금 느낀다.

 

App Status
Background Foreground
Firebase 기본 설정으로 Push Msg 수신 가능 (구분선 기준 위)  
  Firebase 기본 설정으로 Push Msg 수신 불가능
1. FirebaseMessagingService 클래스를 상속 받는 클래스 생성
 - 단, 안드로이드 버전에 따른 구분 필요 (Android 8.0 - 오레오 버전)
 - Push 이미지, 진동 등 설정 가능
Push 이미지 설정을 위해, Manifest에 추가 필요
1. meta-data > default_notification_icon
2. meta-data > default_notification_color

Push Msg 수신에 따른, Bar 생성이 필요하다면?
1. meta-data > default_notification_channel_id 
 
  Push Msg를 누르면, Intent로 설정한 Activity로 이동
Push Msg를 누르면, Manifest에서 Main으로 설정한 Activity로 이동  

 

흠... 그리고 알림 채널에 대해서 좀 살펴봐야겠다.

 

developer.android.com/guide/topics/ui/notifiers/notifications?hl=ko

 

알림 개요  |  Android 개발자  |  Android Developers

알림은 사용자에게 알림, 다른 사용자로부터의 메시지 또는 앱의 기타 실시간 정보를 제공하도록 Android가 앱의 UI 외부에 표시하는 메시지입니다. 사용자는 알림을 탭하여 앱을 열거나 알림에서

developer.android.com

 

'Android > Android' 카테고리의 다른 글

[Callback] 2. Singleton Class  (0) 2020.10.12
[Callback] 1. SimpleCallback  (0) 2020.10.07
[Firebase] 2. Push Notification 로직 구상  (0) 2020.09.22
[Firebase] 1. Push Notification 연동  (0) 2020.09.21
[200301] [Works] [App] Grid-Layout  (0) 2020.03.01
Comments