안드로이드 앱을 개발하다보면 푸시알림 기능이 필요한 부분이 존재합니다.

기존의 GCM(Google Cloud Messaging) 서비스가 대표적이었는데, 최근 구글에서 

Firebase를 인수, FCM(Firebase Cloud Messaging) 서비스를 무료로 제공하고 있습니다.

현재 알려진 바로는 2019년까지 GCM 서비스를 제공하고 이후에는 모든 프로그램을 

FCM 서비스로 변경하라고 하네요!

자 그럼 이제 본격적으로 FCM 서비스를 사용해 봅시다.

먼저 FCM 서비스를 사용하려면 Firebase Console에 접속해야합니다.


접속하기 ☜ 클릭!

Firebase Console에 접속하면 아래와 같은 화면이 등장합니다.



프로젝트 추가를 눌러봅시다.



다음과 같이 화면이 나오면 프로젝트 이름을 기입하고, 약관에 동의를 하면 프로젝트 

만들기 버튼이 활성화됩니다. 프로젝트 만들기 버튼을 눌러 프로젝트를 생성합시다.

프로젝트 생성이 완료되면 새로운 화면이 나오는데 우측에 카테고리를 보시면 다음과 

같습니다.



우측 카테고리 메뉴 중 성장 - Cloud Messaging 을 선택합니다.





위 화면에서 iOS(아이폰), 안드로이드 중 원하는 버튼을 선택합니다.

본 포스팅은 안드로이드 기준으로 작성되었기 때문에 안드로이드를 선택했습니다.



안드로이드를 선택하면 다음과 같이 Android 앱에 Firebase를 추가하라고 나옵니다.

Android 패키지 이름을 작성해야하는데, 여기서 패키지 이름은 안드로이드 프로젝트 

생성시 설정한 패키지 이름을 작성합니다.

만약 패키지 이름을 모르시는 분은 프로젝트를 켜고 MainActivity로 들어갑니다.



그럼 가장 위에 package라고 적힌 부분이 있습니다.

이 부분이 이 프로젝트의 패키지 명입니다.

해당 부분을 복사해서 붙여넣기합니다.

그리고 나머지는 선택사항이므로 빈 칸으로 남겨두고 앱등록을 눌러줍니다.


앱등록이 끝나면 구성파일을 다운로드받습니다.

다운로드 받은 google-services.json 파일을 아래 사진과 같이 app 프로젝트 아래에

붙여넣기합니다.



프로젝트 폴더의 build.gradle의 dependencies에는 다음과 같은 코드를 추가합니다.

classpath 'com.google.gms:google-services:4.0.1'



그리고 app 프로젝트의 build.gradle의 dependencies 내에 다음과 같이 추가합니다.


implementation 'com.google.firebase:firebase-messaging:12.0.1'



그리고 나서 Sync Now버튼을 꼭 눌러주도록 합시다!


위의 과정을 모두 따라하셨다면 아래와 같이 앱에 Firebase를 성공적으로 추가했다는

화면이 나옵니다.



그리고 다시 안드로이드 스튜디오 프로젝트로 돌아와서 java 폴더 아래 패키지 폴더에 

Java Class 두개를 만들어줍니다.



첫번째는 FirebaseInstanceIDService입니다. 다음과 같이 작성합니다.

* 클래스명을 동일하게 만들어주세요


import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;

import com.google.firebase.iid.FirebaseInstanceIdService;



public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseInstanceIDService";


    @Override

    public void onTokenRefresh() {

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        Log.d(TAG, "Refreshed token: " + refreshedToken);

        sendRegistrationToServer(refreshedToken);

    }


    private void sendRegistrationToServer(String token) {

    }

}


두번째는 FireBaseMessagingService입니다. 다음과 같이 작성합니다.

* 클래스명을 동일하게 만들어주세요


import android.app.NotificationChannel;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Intent;

import android.media.RingtoneManager;

import android.net.Uri;

import android.os.Build;

import android.os.Vibrator;

import android.support.v4.app.NotificationCompat;

import android.util.Log;


import com.google.firebase.messaging.FirebaseMessagingService;

import com.google.firebase.messaging.RemoteMessage;


public class FireBaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";


    @Override

    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());


        if (remoteMessage.getData().size() > 0) {

            Log.d(TAG, "Message data payload: " + remoteMessage.getData());


            if (true) {

            } else {

                handleNow();

            }

        }

        if (remoteMessage.getNotification() != null) {

            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

            sendNotification(remoteMessage.getNotification().getBody());

        }

    }

    private void handleNow() {

        Log.d(TAG, "Short lived task is done.");

    }


    private void sendNotification(String messageBody) {

        Intent intent = new Intent(this, MainActivity.class);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,

                PendingIntent.FLAG_ONE_SHOT);


        String channelId = getString(R.string.default_notification_channel_id);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder =

                new NotificationCompat.Builder(this, channelId)

                        .setSmallIcon(R.mipmap.ic_launcher)

                        .setContentTitle("FCM Message")

                        .setContentText(messageBody)

                        .setAutoCancel(true)

                        .setSound(defaultSoundUri)

                        .setContentIntent(pendingIntent);


        NotificationManager notificationManager =

                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            String channelName = getString(R.string.default_notification_channel_name);

            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);

            notificationManager.createNotificationChannel(channel);

        }

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

    }

}


위와 같이 클래스를 만들어주셨다면 AndroidManifest.xml로 이동합니다.

activity가 끝나는 부분 </activity> 바로 밑에 다음과 같이 작성합니다.




<service

    android:name=".FireBaseMessagingService">

    <intent-filter>

        <action android:name="com.google.firebase.MESSAGING_EVENT"/>

    </intent-filter>

</service>


<service

    android:name=".FirebaseInstanceIDService">

    <intent-filter>

        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>

    </intent-filter>

</service>


자 여기까지 안드로이드 프로젝트내 모든 설정이 끝났습니다.

이제 푸시알람이 제대로 가는지 확인해야겠죠?


다시 Firebase Console로 돌아갑니다. 새 메시지를 선택하고 다음과 같이 작성합니다.

메시지 내용을 작성하고 대상을 앱의 패키지를 선택합니다.

그리고 메시지보내기 버튼을 누르면!!



짠!

다음과 같이 상태 알림창에서 푸시 알림이 오는것을 확인 할 수 있습니다.



또한 안드로이드 프로젝트 Run 화면에서 Log에 찍히는걸 확인하실 수 있습니다.




이상 '안드로이드 FCM 푸시알림'에 대해 알아보았습니다.

질문 또는 오타나 잘못된 정보가 있는 경우 댓글로 달아주세요!

공감♡ 버튼을 눌러주시면 더욱 유용하고 좋은 포스팅으로 찾아 뵙겠습니다.







to Top