프로그램/Android

안드로이드 FCM 푸시(1.프로젝트 셋팅 및 구현)

잡식성초보 2019. 1. 3. 10:11

안드로이드 FCM 관련 글입니다.


구글에서는 예전부터 지속적으로 GCM이 아닌 FCM사용을 권고하였습니다. 


그리고 안드로이드 신규 버전인 9.0파이버전부터는 GCM이 정상적인 작동을 하지 않습니다.

(관련 링크)


FCM프로젝트를 생성 및 푸시 테스트까지 진행해 보도록 하겠습니다.


FCM관련 콘솔 홈페이지로 접속합니다(링크)


구글계정이 로그인 되어있는 상태에서 위의 링크를 클릭하면 아래와 같은 화면으로 진입합니다.


화면에서 프로젝트 추가를 클릭합니다.




다음부터는 스크린샷을 따라서 해주시면 되겠습니다.








아래 디버그 서명 인증서는 선택사항이며 꼭 하지 않으셔도 됩니다.


하지만 밑줄친 기능을 사용하실려면 등록하시면 됩니다.







위의 스크린샷에서 처럼 google-service.json 파일을 다운받은 뒤 현재 FCM사용을 위해 


생성한 프로젝트 app폴더 안에 파일을 넣도록 합니다.





여기까지 하셨으면 기본적으로 FCM을 준비하는건 다되셨습니다.


이제 프로젝트 내부에 Gradle 셋팅과 FCM 구현이 남아있는데요.


먼저 Gradle 셋팅입니다.


프로젝트 내 dependencies 안에 아래 코드를 넣어줍니다.



implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.firebase:firebase-core:16.0.4'



dependencies 밖에 json파일 관련 아래 코드를 넣어줍니다.



apply plugin: 'com.google.gms.google-services'



두번째 앱 내의 denpendencies 안에 아래 코드를 넣어줍니다.



classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.0.1'



Gradle 스크린샷 입니다.







여기까지 준비가 되셨다면 이제 FCM을 구현해주면 됩니다.


프로젝트내에 FirebaseInstanceIDService 라는 클래스 파일을 생성한 뒤 아래와 같이 구현합니다. 


메소드에 대한 설명은 주석으로 되어있습니다.



package kr.com.fcmtarget.fcm;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import kr.com.fcmtarget.R;


public class FirebaseInstanceIDService extends FirebaseMessagingService {

    /**
     * 구글 토큰을 얻는 값입니다.
     * 아래 토큰은 앱이 설치된 디바이스에 대한 고유값으로 푸시를 보낼때 사용됩니다.
     * **/

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("Firebase", "FirebaseInstanceIDService : " + s);
    }

    /**
     * 메세지를 받았을 경우 그 메세지에 대하여 구현하는 부분입니다.
     * **/
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        if (remoteMessage != null && remoteMessage.getData().size() > 0) {
            sendNotification(remoteMessage);
        }
    }


    /**
     * remoteMessage 메세지 안애 getData와 getNotification이 있습니다.
     * 이부분은 차후 테스트 날릴때 설명 드리겠습니다.
     * **/
    private void sendNotification(RemoteMessage remoteMessage) {

        String title = remoteMessage.getData().get("title");
        String message = remoteMessage.getData().get("message");

        /**
         * 오레오 버전부터는 Notification Channel이 없으면 푸시가 생성되지 않는 현상이 있습니다.
         * **/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            String channel = "채널";
            String channel_nm = "채널명";

            NotificationManager notichannel = (android.app.NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel channelMessage = new NotificationChannel(channel, channel_nm,
                    android.app.NotificationManager.IMPORTANCE_DEFAULT);
            channelMessage.setDescription("채널에 대한 설명.");
            channelMessage.enableLights(true);
            channelMessage.enableVibration(true);
            channelMessage.setShowBadge(false);
            channelMessage.setVibrationPattern(new long[]{100, 200, 100, 200});
            notichannel.createNotificationChannel(channelMessage);

            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, channel)
                            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentTitle(title)
                            .setContentText(message)
                            .setChannelId(channel)
                            .setAutoCancel(true)
                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(9999, notificationBuilder.build());

        } else {
            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, "")
                            .setSmallIcon(R.drawable.ic_launcher_background)
                            .setContentTitle(title)
                            .setContentText(message)
                            .setAutoCancel(true)
                            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.notify(9999, notificationBuilder.build());

        }
    }
}



위의 소스를 완성 하셨다면AndroidManifest.xml에 아래 소스까지 해주시면 완성입니다.



        <service
            android:name=".fcm.FirebaseInstanceIDService"
            android:stopWithTask="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>



자 이제 테스트를 해봐야겠죠?


데이터를 보내는 페이로드 관련 및 테스트는 다음글에 적도록 하겠습니다.


반응형