freddy
느낌으로 남지않기
freddy
전체 방문자
오늘
어제
  • 분류 전체보기 (28)
    • HTML (2)
    • CSS (1)
    • JavaScript (8)
    • WebGL (0)
    • 개념정리 (0)
    • React (2)
    • ReactNative (4)
    • ERROR.LOG (3)
    • 설치 (2)
    • 챌린지 (0)
    • 책 (0)
    • 세미나 (2)
    • 일기장 (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • javascript 최신문법
  • react
  • 앱이 계속 중지됨
  • 프론트엔드
  • es11
  • react 기초
  • css variables
  • 리액트의 필요성
  • React-Native
  • evnet 위임
  • react 특징
  • Spread syntax
  • JS
  • Optional chainning
  • Github Actions
  • BOM 이란?
  • react 사용하는 이유
  • 값식문
  • javscript 기초
  • bitnami ubuntu
  • em과rem차이
  • javascript30
  • React Native
  • Nullish coalescing operator
  • javascript 이벤트 위임
  • 브라우저 동작 원리
  • Destructuring assignment
  • 최신JS문법
  • JavaScript
  • Shorthand property names

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
freddy

느낌으로 남지않기

ReactNative

React-native 에서 push 알림 사용하기

2020. 2. 22. 21:04
반응형

현재글은 RN - v0.60 이상에서 android 기준 입니다.

android에서 push알림을 사용하려면 firebase를 설정한 후 firebase console에서 사용이 가능합니다. firebase를 설정한후 messaging,notifications 기능을 추가하는 순서로 작성하였습니다.

1. firebase console 사이트에 자신이 만든 앱을 등록합니다.(등록방법은 검색)

2. npm install --save react-native-firebase 를 설치합니다.

3. anroid/build.gradle 경로에 Buildscript{.. Dependencies{… }} Dependencies 안에 classpath 'com.google.gms:google-services:4.2.0' 를 추가합니다.

4. android/app/build.gradle 파일에 apply plugin: 'com.google.gms.google-services' 를 적어준다. 이어서 같은파일Dependencies에

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

implementation "com.google.firebase:firebase-core:16.0.9" 를 추가합니다 여기까지가 firebase를 설정하는 부분입니다. npm run android 하여 build를 하고 성공적으로 build가 됐는지 확인 후 이어서 진행합니다.

5. Android/app/build.gradle에 Dependencies에 implementation "com.google.firebase:firebase-messaging:18.0.0" 추가합니다.

6. android/src/main/java 에 있는 MainApplication.java 에

import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;  <-- 추가

private final ReactNativeHost mReactNativeHost =

      new ReactNativeHost(this) {

        @Override

        public boolean getUseDeveloperSupport() {

          return BuildConfig.DEBUG;

        }

        @Override

        protected List<ReactPackage> getPackages() {

          @SuppressWarnings("UnnecessaryLocalVariable")

          List<ReactPackage> packages = new PackageList(this).getPackages();

          // Packages that cannot be autolinked yet can be added manually here, for example:

          // packages.add(new MyReactNativePackage());

          packages.add(new RNFirebaseMessagingPackage());  <-- add This Line !!

          return packages;

        }

여기까지가 messaging 설정입니다. 이어서 notifications 설정입니다

7. android/src/main/java 에 있는 MainApplication.java 에

import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; <-- 추가 

private final ReactNativeHost mReactNativeHost =

      new ReactNativeHost(this) {

        @Override

        public boolean getUseDeveloperSupport() {

          return BuildConfig.DEBUG;

        }

        @Override

        protected List<ReactPackage> getPackages() {

          @SuppressWarnings("UnnecessaryLocalVariable")

          List<ReactPackage> packages = new PackageList(this).getPackages();

          // Packages that cannot be autolinked yet can be added manually here, for example:

          // packages.add(new MyReactNativePackage());

          packages.add(new RNFirebaseMessagingPackage());  <-- add This Line !!

          packages.add(newRNFirebaseNotificationsPackage());// <-- Add this line

          return packages;

        }

여기까지 적용한 뒤 npm run android 로 build를 합니다. 성공적으로 build 됐으면 종료 후 이어서 진행합니다.

8. npm install --save react-native-push-notification    설치

9. android/app/src/main 에 있는 AndroidManifest.xml 에 

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

   <permission

        android:name="${applicationId}.permission.C2D_MESSAGE"

        android:protectionLevel="signature" />

    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />

    <!-- < Only if you're using GCM or localNotificationSchedule() > -->

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

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

를 추가

 

<Application … 에

<meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                android:value="YOUR NOTIFICATION CHANNEL NAME"/>
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                    android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
        <!-- Change the resource name to your App's accent color - or any other color you want -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@android:color/white"/>

<!-- < Only if you're using GCM or localNotificationSchedule() > -->
        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
        <!-- < Only if you're using GCM or localNotificationSchedule() > -->

<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>

<!-- < Only if you're using GCM or localNotificationSchedule() > -->
        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <!-- </ Only if you're using GCM or localNotificationSchedule() > -->

<!-- < Else > -->
        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <!-- </Else> -->

추가 한다.

10 . android/app/src/res/values/colors.xml (없으면 생성)

<resources>
    <color name="white">#FFF</color>
</resources>

11. App.js에 아래 내용 추가합니다.

import PushNotification from 'react-native-push-notification';

async componentDidMount() { 

    PushNotification.configure({

      onNotification: function(notification) {

        console.log('notification', notification);

      },

    });

  }

여기까지가 설정 마무리입니다. build 후 에뮬레이터를 실행 합니다.

12. Firebase console 에 cloud messaging 에서 푸쉬 메세지를 보냅니다. 그럼 등록한 앱으로 push 알림이 뜹니다.

 

 

 

참고 사이트 :https://www.youtube.com/watch?v=03-A9HdyB-Y 이 영상 내용 기반으로 설명하였습니다.

부족한부분은 참고하시길 바랍니다.

RN - push 알림 설정법

https://github.com/zo0r/react-native-push-notification

https://rnfirebase.io/docs/v5.x.x/getting-started

반응형

'ReactNative' 카테고리의 다른 글

api 호출시 Network-request-failed 해결방법  (0) 2020.03.04
React Native 에서 Icon(아이콘) 사용하기 , 아이콘 깨짐현상 해결  (1) 2020.02.22
D8: Cannot fit requested classes in a single dex file (# methods: 66026 > 65536) 오류해결  (0) 2020.02.18
    'ReactNative' 카테고리의 다른 글
    • api 호출시 Network-request-failed 해결방법
    • React Native 에서 Icon(아이콘) 사용하기 , 아이콘 깨짐현상 해결
    • D8: Cannot fit requested classes in a single dex file (# methods: 66026 > 65536) 오류해결
    freddy
    freddy

    티스토리툴바