Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

Dev_R

안드로이드 스튜디오 + FCM Notification 푸시기능 추가하기 본문

개발 Project/Android

안드로이드 스튜디오 + FCM Notification 푸시기능 추가하기

Dave(데이브) 2020. 6. 3. 03:13
반응형

이번에는 안드로이드 앱에 Firebase의 Clode Messaging 기능을 이용하는 방법에 대해 포스팅하겠습니다.

 

우선 firebase는 모바일,웹 환경에서 DB, 인증, 클라우드와 같은 서비스를 제공해주고 있는데요

 

 

 

요금제가 위 처럼 나눠져 있기는 하지만, 이번에 저희가 쓰려는 Firebase Cloude Messaging의 경우 무료 요금제로 무제한 사용가능하기 때문에 무료 Spark 요금제를 이용하겠습니다.

 

 

우선 firebase에 회원가입을 하시고

프로젝트 생성을 아직 못하셨다면 

 

 

 

프로젝트 추가버튼을 눌러서 프로젝트를 등록하세요

 

1단계

 

프로젝트 만들기 총 3단계를 진행하시면 되구요

 

 

2단계

 

 

 

 

우선 애널리틱스도 사용 설정하도록 할게요

 

 

3단계

 

 

그러면 위처럼 애널리틱스 계정을 선택할 수 있는데요

 

 

계정선택을 누르셔서 새 계정 만들기를 눌러주세요

 

저는 이미 만들어놓은 FCM-Client를 선택하고 '프로젝트 만들기' 버튼을 클릭하겠습니다.

 

 

 

 

 

 

그러면 이제 위와같은 창이 뜨는데요

현재 저는 이미 앱을 등록해놓은 상태지만 여러분들은 프로젝트 제목 아래에 '+앱추가' 버튼만 있을거예요

 

 

FCM 푸시메세지를 받을 앱을 등록해보겠습니다.

 

 

 

 

 

플랫폼은 당연히 안드로이드죠

 

 

 

그러면 이렇게 화면이 바뀌는데요

안드로이드 패키지 이름을 적어주셔야 합니다.

 

패키지 이름을 알기위해서

만들어놓은 안드로이드 프로젝트를 열어볼게요

 

 

 

 

저 빨간 package 옆에 써있는걸 적어주시면 되구요

 

 

 

 

 

저는 이미 등록된게 있어서 빨간색으로 뜨지만 여러분들은 계속 진행이 가능하실거예요

 

그다음 '앱 닉네임'을 적어주시고 앱 등록을 누릅니다.

 

 

 

 

다음 버튼을 누르니 google-services.json파일을 다운받으라고 하네요

파일을 받아서 app 디렉토리에 잘 넣어주도록 합니다.

 

 

 

 

이렇게 app 폴더 안에 잘 넣어주었구요 '다음'버튼을 클릭할게요

 

 

 

 

이제 firebase sdk를 추가할 차례입니다.

 

우리가 건드려야할 파일은 총 2개입니다.

 

 

 

이렇게 build.gradle 파일 2개의 내용을 변경해 볼게요

 

먼저 1번 build.gradel(Project: )를 열어서 

 

 

buildscript {
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
  }
  dependencies {
    ...
    // Add this line
    classpath 'com.google.gms:google-services:4.3.3'
  }
}

allprojects {
  ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    ...
  }
}

 

 

위에서 추가하라는 내용을 추가해줍니다.

 

 

 

 

저 한줄을 추가해 주었구요 다른 곳도 firebase 안내와 다른지 확인을 하고, 다르다면 내용을 추가해줍니다.

 

그다음 2번째 build.gradle 파일을 변경할게요

 

 

apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'

dependencies {
  // add the Firebase SDK for Google Analytics
  implementation 'com.google.firebase:firebase-analytics:17.2.2'
  // add SDKs for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries
}

 

위 내용을 추가해주면 됩니다.

 

파일 맨위 한줄

 

파일 아래쪽 한줄

이렇게 두줄 추가해주시면 됩니다.

 

그리고!! 중요한 점은

build.gradle을 변경했다면 꼭 우측 상단의 sync now 버튼을 클릭해야 한다는 점입니다!

 

 

 

 

Sync가 끝났다면 firebase 페이지에서 '다음 버튼을 누릅니다.'

 

 

 

 

 

그러면 이제 서버와 통신했는지 확인을 하는데요

안드로이드 스튜디오의 앱을 실행시키시기만 하면 됩니다.

안드로이드 스튜디오 앱의 내용이 없더라도 우측 상단의 ▶ 버튼을 클릭해 Run 시켜주세요

 

 

그렇게 에뮬레이터나 스마트폰에 앱을 설치한 후 실행시킨 상태로 잠시 기다리시면 firebase 페이지에서도 앱 설치를 확인했다면서 Firebase 안드로이드 앱을 추가하실 수 있습니다.

 

 

 

그다음 안드로이드 스튜디오에 FCM관련 Notification 코드를 추가할 차례입니다.

 

 

우선 MainActivity가 있는 곳에 MyFireBaseMessagingService.java로 파일을 하나 만듭니다.

그리고 나서 아래 내용을 추가해주세요

 

package com.devr.fcm_client;

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.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

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

public class MyFireBaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String token) {
        Log.d("FCM Log", "Refreshed token: " + token);
    }
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getNotification() != null) {                      //포어그라운드
            sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
        }else if (remoteMessage.getData().size() > 0) {                           //백그라운드
            sendNotification(remoteMessage.getData().get("body"), remoteMessage.getData().get("title"));
            /* 백그라운드 작동 내용 */
        }
    }

        private void sendNotification(String messageBody, String messageTitle)  {
            Log.d("FCM Log", "알림 메시지: " + messageBody);
          
            /* 알림의 탭 작업 설정 */
            Intent intent = new Intent(this, MainActivity.class);

            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            String channelId = "Channel ID";
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            /* 알림 만들기 */
            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(messageTitle)
                            .setContentText(messageBody)
                            .setAutoCancel(true)
                            .setFullScreenIntent(pendingIntent, true);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            /* 새로운 인텐트로 앱 열기 */
            Intent newintent = new Intent(this, MainActivity.class);
            newintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity( newintent );

            /* 채널 만들기*/
            /* Android 8.0 이상에서 알림을 게시하려면 알림을 만들어야 함 */
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String channelName = "Channel Name";
                NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
                notificationManager.createNotificationChannel(channel);
            }

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

}

 

주석 내용을 보시면 아시겠듯이 알림을 받으면 MainActivity가 자동으로 start해서 바로 실행되도록 설정을 해두었는데요. 제가 만들려는 앱이 비상 알림 앱이기 때문에 바로바로 앱이켜져서 내용이 보여지게하기위해서 이렇게 만들었습니다.

 

그다음은 MainActivity에 내용을 추가할 차례입니다.

 

FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if (!task.isSuccessful()) {
                    Log.w(TAG, "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = task.getResult().getToken();

                // Log and toast
                String msg = getString(R.string.msg_token_fmt, token);
                Log.d(TAG, msg);
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

MainActivity.java 파일 안의 onCreate안에 이 내용을 넣어주세요

 

 

 

저는 요렇게 ALL 주제구독까지 추가해 두었어요

 

마지막으로 남은 하나는 AndroidManifest.xml 파일에 아래 내용을 추가하는 일입니다.

 

 

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

 

 

 

이렇게 추가하면 끝인데요

이 상태로 다시 에뮬레이터나 스마트폰에 앱을 설치해 둡니다.

 

그 다음 firebase 웹페이지로 돌아가 성장> Cloud Messaging을 들어갑니다.

 

 

위와 같은 창이 뜨면 '새 알림' 버튼을 클릭하구요

 

 

 

 

 

 

 

이렇게 간단하게 test 메시지를 만들어 주고

 

 

 

 

검토 > 게시

누르면 끝!

 

 

그러면 거의 딜레이 없이 아래와 같은 push Notification을 스마트폰에서 받아볼 수 있습니다.

 

 

 

정말 유용한 기능이 많은 Firebase인데요.

이것저것 살펴보면 앱, 웹 개발에 필수적이거나 큰 도움이 되는 기능들을 간편하고 쉽게 추가할 수 있는것 같아요.

 

반응형
Comments