어서와, 개발은 처음이지?

React Native Firebase 푸시 알림(push notification), background listener - 1.Android 세팅 본문

React/React Native

React Native Firebase 푸시 알림(push notification), background listener - 1.Android 세팅

오지고지리고알파고포켓몬고 2019. 4. 8. 00:36
반응형



이 글은

React Native Firebase 푸시 알림(push notification), background listener - 1.Android 세팅(현재글)

React Native Firebase 푸시 알림(push notification), background listener - 2.firebase 리스너 구현

React Native Firebase 푸시 알림(push notification), background listener - 3.서버 구현로 구성되어 있습니다.



최근에 제품에 푸쉬 알림 기능을 넣어야 했는데, 개인적인 생각으로는 푸쉬 알림이 navigation 처럼 범용적인 기능임에도 한글로 된 자료를 찾기 힘들어서 오랜만에 React Native에 관한 글을 작성하게 됐습니다.


push 알림은 쉽게 말하자면 카톡 알림과 같습니다.


클라이언트의 요청 -> 서버의 응답으로 이루어지는 것이 아닌, 서버 -> 클라이언트로 통신이 이루어지며, 앱 활성/비활성과 관계없이 알림이 표시됩니다.


보통의 상황이라면 소캣 서버를 구축해야 하겠지만 Google에서 제공하는 Firebase를 사용하면 FCM(Firebase Cloud Messaging, 구 Google Cloud Messaging. GCM) 푸쉬 기능을 쉽게 사용할 수 있습니다.


지금부터 React Native에서 Firebase를 사용하는 법을 알아보겠습니다.



1. Firebase 프로젝트 생성


우선 구글 계정에 로그인 한 뒤, 이곳에서 아래와 같이 프로젝트를 생성합니다.



2. React Native 프로젝트 생성


다음은 React Native Cli를 사용하여 프로젝트를 생성합니다.

저는 개인적으로 latest 버전을 선호하지 않으므로 0.57.8 버전으로 생성하겠습니다.

> react-native init FirebaseTest --version=react-native@0.57.8
> cd FirebaseTest

최신 Firebase와 0.57.8 버전을 호환하기 위해서는 sdk 28, gradle 4.6을 필요로 합니다.

이전에 compileSdkVersion 28 이상을 빌드하셨던 적이 있다면 매그럽게 실행 될 것이오나, 아래 세팅 부분을 잘 숙지하시되, 에러가 나는 부분이 있다면 댓글로 남겨주세요. 



3. React-Native-Firebase 설치, 안드로이드 세팅


다음 명령어를 사용하여 React-Native-Firebase를 설치하고 기본 세팅을 합니다.

> npm install --save react-native-firebase
> react-native link react-native-firebase


그리고 설정이 정확히 이루어졌는지 아래 파일들을 확인해봅니다.

buildscript {
  // ...
  dependencies {
    // ...
    classpath 'com.android.tools.build:gradle:3.2.0'
    classpath 'com.google.gms:google-services:4.0.1'
  }
}
task wrapper(type: Wrapper) {
    gradleVersion = '4.6'
    distributionUrl = distributionUrl.replace("bin", "all")
}

<FirebaseTest/android/build.gradle>


com.google.gms:google-services이 있는지 확인하고, 만약 com.android.tools.build:gradle 버전이 3.2.0보다 낮다면 3.2.0으로 수정해줍니다.

gradleVersion도 4.6버전인지 확인합니다.

dependencies {
    implementation project(':react-native-firebase')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules

    implementation "com.google.android.gms:play-services-base:16.0.1"
    implementation "com.google.firebase:firebase-core:16.0.6"
    implementation "com.google.firebase:firebase-messaging:17.3.4"
    implementation 'me.leolin:ShortcutBadger:1.1.21@aar'

  ...
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

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

<FirebaseTest/android/app/build.gradle>


implementation project(':react-native-firebase')

implementation "com.google.android.gms:play-services-base:16.0.1"

implementation "com.google.firebase:firebase-core:16.0.6" 

implementation "com.google.firebase:firebase-messaging:17.3.4"

implementation 'me.leolin:ShortcutBadger:1.1.21@aar'

이 위치하고 있는지 확인합니다.


그리고 build.gradle파일 최하단에 apply plugin: 'com.google.gms.google-services'을 입력해줍니다.

// ...
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; 
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;

public class MainApplication extends Application implements ReactApplication {
    // ...

    @Override
    protected List getPackages() {
      return Arrays.asList(
          new MainReactPackage(),
          new RNFirebasePackage(),
          new RNFirebaseMessagingPackage(),
          new RNFirebaseNotificationsPackage()
      );
    }
  };
  // ...
}

<FirebaseTest/android/app/src/main/java/com/firebasetest/MainApplication.java>


import io.invertase.firebase.RNFirebasePackage;

import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; 

import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;


new RNFirebasePackage(),

new RNFirebaseMessagingPackage(),

new RNFirebaseNotificationsPackage()

이 위치하고 있는지 확인합니다.

<application ...>

  <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
    <intent-filter>
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
  </service>
  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

</application>

<FirebaseTest/android/app/src/main/java/AndroidManifest.xml>


application 태그 안에 아래 태그가 삽입되어있는지 확인합니다.

<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">

        <intent-filter>

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

        </intent-filter>

</service>

<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

      




4. 인증파일 다운로드


다시 Firebase 콘솔로 이동해서 1번에서 생성한 프로젝트를 열어봅니다.


프로젝트 화면의 좌측 메뉴에 Cloud Messaging을 선택하고, 다음 화면에서 안드로이드 아이콘을 클릭합니다.


다음으로 Android 패키지 이름을 입력하고, 앱 등록을 누릅니다.

Android 패키지 이름은 FirebaseTest/android/build.gradle의 android -> defaultConfig -> applicationId에 있습니다.


다음으로 google-services.json 다운로드를 선택한 뒤, 다운로드 받은 파일이 Firebase/android/app에 위치하도록 이동시킵니다.

그리고 다음을 눌러 4.앱을 실행하여 설치 확인 항목으로 넘어갑니다.



5. React Native 앱 실행


앱이 정상적으로 실행되면 수 초 ~ 수 분 뒤에 Firebase 콘솔에서 인증 된 모습을 확인할 수 있습니다.


0.57.8 버전과는 몇가지 버전 설정에 관한 문제가 있을 수 있으니 에러가 발생하신다면 댓글을 남겨주시거나, 상위 버전의 React Native로 실행해보시길 바랍니다. 



6. Push 알림 테스트



이제 Firebase 콘솔에서 push 알림을 보내보겠습니다.


우선 back 버튼으로 종료, 앱 프로세스 종료 중 편하신 방법으로 앱을 종료시킵니다.


다음으로, 콘솔로 돌아가서 Send your first message라는 버튼을 누릅니다.


다음으로 push 알림에 띄우고 싶은 메세지를 입력합니다.


다음으로 target이 될 app(com.firebasefest)을 선택하고, 검토를 눌러줍니다.


마지막으로 게시를 눌러줍니다.


게시가 완료되면 아래 화면처럼 메세지 창에 push 메세지가 도착합니다.



7. 마치며


여기까지 android 디바이스에서 React Native Firebase 설정방법에 대해 알아봤습니다.


그러나 push 정보를 핸들링하거나, background에서 push 정보를 핸들링 하기 위해서는 앱 코드에서 listener를 등록해주어야 합니다.


다음 글에서는 listener를 등록하고, Firebase 콘솔을 사용하지 않고 특정 사용자에게 push 알림을 보내는 코드를 구현해보도록 하겠습니다.



8. 참조(reference)


React Native Firebase 공식 홈페이지(rnfirebase.io)




Comments