React Native
...
Push Notifications
React Native Parse SDK로 Android 푸시 알림 전송
16 분
안드로이드에서 react native용 푸시 알림 소개 이 가이드는 parse를 사용하여 안드로이드의 react native 애플리케이션에 푸시 알림을 보내는 방법을 가르쳐줍니다 firebase를 설정하고 대시보드 및 cloud code 기능을 통해 푸시 알림을 보내도록 back4app 앱을 구성합니다 언제든지 이 튜토리얼로 구축된 전체 안드로이드 프로젝트에 접근할 수 있습니다 우리의 github 저장소에서 확인하세요 javascript 예제 저장소 typescript 예제 저장소 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 생성된 react native 앱과 back4app에 연결된 다음 방법을 이해하십시오 클라우드 기능 배포하기 back4app에서 google firebase를 사용할 수 있도록 google에 활성 계정이 필요합니다 목표 parse에서 react native 애플리케이션으로 android에 푸시 알림을 전송하려면 back4app의 대시보드와 cloud code 기능을 사용하세요 1 firebase 설정하기 firebase는 android에서 푸시 알림을 전송하고 수신하는 데 가장 많이 사용되는 서비스 제공업체입니다 현재 다양한 도구와 함께 많은 회사에서 사용하고 있습니다 다음 단계 1과 2를 따라 앱을 위한 firebase 프로젝트를 생성해 보겠습니다 이 문서 https //firebase google com/docs/android/setup#console 앱을 생성한 후 firebase 콘솔을 종료하기 전에 google services json 파일을 다운로드하여 저장하고, “cloud messaging” 탭에서 프로젝트 설정으로 이동하여 다음 키를 가져오세요 서버 키; 발신자 id 2 back4app에서 푸시 알림 활성화하기 firebase 프로젝트를 back4app과 연결하고 대시보드 및 클라우드 코드를 통해 푸시 알림을 전송할 수 있도록 하려면 다음 단계를 따르세요 back4app 웹사이트 , 로그인하고, 앱을 찾아 서버 설정 서버 설정 을 클릭하세요 “안드로이드 푸시 알림” 블록을 찾아 설정 설정 > 편집 편집 을 클릭하세요 “안드로이드 푸시 알림” 블록은 다음과 같습니다 3\ firebase 서버 키 서버 키 를 api 키 api 키 필드에 추가하고, 발신자 id 발신자 id 를 gcm 발신자 id gcm 발신자 id 필드에 추가하세요 4\ 저장하고 완료하세요 3 의존성 설치 및 설정 당신의 react native 프로젝트에서 react native push notification react native push notification 라이브러리를 설치합시다 이 라이브러리는 애플리케이션을 firebase와 통합하고 수신된 알림을 처리할 수 있게 해줍니다 프로젝트 루트 디렉토리에서 다음 명령어를 실행하세요 설치한 후, android/app/src/main/androidmanifest xml android/app/src/main/androidmanifest xml , android/build gradle android/build gradle 및 android/app/build gradle android/app/build gradle 에 라이브러리 문서 https //github com/zo0r/react native push notification 를 따라 몇 가지 구성을 추가해야 합니다 또한 androidmanifest xml androidmanifest xml 파일에 애플리케이션의 기본 알림 채널 id를 포함하는 meta data meta data 를 추가해야 합니다(예를 들어 guidechannel guidechannel 을 사용합시다) 이름을 지시문에 직접 추가하거나 strings xml strings xml 파일에 포함할 수 있습니다 또한 프로젝트의 google services json google services json 파일을 android/app android/app 디렉토리에 배치하세요 1 \<meta data 2 android\ name="com google firebase messaging default notification channel id" 3 android\ value="guidechannel" /> 4 \<! or > 5 \<meta data 6 android\ name="com google firebase messaging default notification channel id" 7 android\ value="@string/default notification channel id" /> 다음 단계에서는 이 라이브러리를 사용하는 방법과 parse와 결합하는 방법을 배울 것입니다 4 푸시 알림 처리 푸시 알림과 관련된 새로운 메서드를 포함하는 파일을 생성해 보겠습니다 파일 이름은 pushnotificationmethods js pushnotificationmethods js (또는 pushnotificationmethods tsx pushnotificationmethods tsx )로 하고, 다음 함수를 추가합니다 이 함수는 react native push notification react native push notification , 알림 채널을 생성하고, 또한 parse가 우리 기기의 푸시 구성을 인식하도록 설정하는 역할을 합니다 javascript 1 import pushnotification from 'react native push notification'; 2 import parse from 'parse/react native'; 3	 4 const channelid = 'guidechannel'; 5	 6 export async function configurepushnotifications() { 7 // initialize pushnotification 8 await pushnotification configure({ 9 // (required) called when a remote is received or opened, or local notification is opened 10 onnotification function (notification) { 11 // process the notification 12 console log('notification ', notification); 13 // if notification is remote and has data, trigger local notification to show popup 14 // this is needed for parse sent notifications because firebase doesn't trigger popup 15 // notifications with data by itself 16 if ( 17 notification data !== undefined && 18 notification data data !== undefined 19 ) { 20 try { 21 // notification data comes as a stringified json, so parsing is needed 22 const notificationdata = json parse(notification data data); 23 // json parse notifications from the dashboard and cloud code 24 // should contain the default `title` and `message` parameters 25 let title = 'notification title'; 26 if (notificationdata title !== undefined) { 27 title = notificationdata title; 28 } 29 let message = 'noticiation message'; 30 if (notificationdata message !== undefined) { 31 message = notificationdata message; 32 } 33 // text parse notifications from the dashboard only have an `alert` parameter 34 if (notificationdata alert !== undefined) { 35 message = notificationdata alert; 36 } 37 pushnotification localnotification({ 38 channelid channelid, 39 title title, 40 message message, 41 }); 42 } catch (error) { 43 console log(`error triggering local notification ${error}`); 44 } 45 } 46 }, 47	 48 onregister async function (token) { 49 console log(`registered with device token ${token token}`); 50 let devicetoken = token token; 51	 52 // create the notification channel, required for android notifications 53 await pushnotification createchannel({ 54 channelid channelid, 55 channelname 'guide channel', 56 }); 57 console log('notification channel created!'); 58	 59 // create a parse installation, that will link our application's push notification 60 // to the parse server 61 try { 62 const installationid = await parse getinstallationid(); 63 const installation = new parse installation(); 64 // make sure to change any needed value from the following 65 installation set('devicetype', 'android'); 66 installation set('gcmsenderid', 'your gcm sender id'); 67 installation set('pushtype', 'gcm'); 68 installation set('appidentifier', 'your app identifier(package name)'); 69 installation set('parseversion', '3 2 0'); 70 installation set('appname', 'back4appguidepushnotifications'); 71 installation set('appversion', '1 0'); 72 installation set('localeidentifier', 'pt br'); 73 installation set('badge', 0); // set initial notification badge number 74 installation set('timezone', 'america/sao paulo'); 75 installation set('installationid', installationid); 76 installation set('channels', \[channelid]); 77 installation set('devicetoken', devicetoken); 78 await installation save(); 79 console log(`created new parse installation ${installation}`); 80 } catch (error) { 81 console log(error message); 82 } 83 }, 84 popinitialnotification true, 85 requestpermissions true, 86 }); 87 }1 import pushnotification from 'react native push notification'; 2 import parse from 'parse/react native'; 3	 4 const channelid string = 'guidechannel'; 5	 6 export async function configurepushnotifications() { 7 // initialize pushnotification 8 await pushnotification configure({ 9 // (required) called when a remote is received or opened, or local notification is opened 10 onnotification function (notification object) { 11 // process the notification 12 console log('notification ', notification); 13 // if notification is remote and has data, trigger local notification to show popup 14 // this is needed for parse sent notifications because firebase doesn't trigger popup 15 // notifications with data by itself 16 if ( 17 notification data !== undefined && 18 notification data data !== undefined 19 ) { 20 try { 21 // notification data comes as a stringified json, so parsing is needed 22 const notificationdata = json parse(notification data data); 23 // json parse notifications from the dashboard and cloud code 24 // should contain the default `title` and `message` parameters 25 let title string = 'notification title'; 26 if (notificationdata title !== undefined) { 27 title = notificationdata title; 28 } 29 let message string = 'noticiation message'; 30 if (notificationdata message !== undefined) { 31 message = notificationdata message; 32 } 33 // text parse notifications from the dashboard only have an `alert` parameter 34 if (notificationdata alert !== undefined) { 35 message = notificationdata alert; 36 } 37 pushnotification localnotification({ 38 channelid channelid, 39 title title, 40 message message, 41 }); 42 } catch (error any) { 43 console log(`error triggering local notification ${error}`); 44 } 45 } 46 }, 47	 48 onregister async function (token {os string; token string}) { 49 console log(`registered with device token ${token token}`); 50 let devicetoken string = token token; 51	 52 // create the notification channel, required for android notifications 53 await pushnotification createchannel({ 54 channelid channelid, 55 channelname 'guide channel', 56 }); 57 console log('notification channel created!'); 58	 59 // create a parse installation, that will link our application's push notification 60 // to the parse server 61 try { 62 const installationid = await parse getinstallationid(); 63 const installation = new parse installation(); 64 // make sure to change any needed value from the following 65 installation set('devicetype', 'android'); 66 installation set('gcmsenderid', 'your gcm sender id'); 67 installation set('pushtype', 'gcm'); 68 installation set('appidentifier', 'your app identifier(package name)'); 69 installation set('parseversion', '3 2 0'); 70 installation set('appname', 'back4appguidepushnotifications'); 71 installation set('appversion', '1 0'); 72 installation set('localeidentifier', 'pt br'); 73 installation set('badge', 0); // set initial notification badge number 74 installation set('timezone', 'america/sao paulo'); 75 installation set('installationid', installationid); 76 installation set('channels', \[channelid]); 77 installation set('devicetoken', devicetoken); 78 await installation save(); 79 console log(`created new parse installation ${installation}`); 80 } catch (error) { 81 console log(error message); 82 } 83 }, 84 popinitialnotification true, 85 requestpermissions true, 86 }); 87 } 오픈 소스 문서 에 대한 더 많은 정보는 parse installation parse installation 클래스는 여기 https //docs parseplatform org/js/guide/#push notifications 에서 확인할 수 있습니다 이벤트 핸들러 onnotification onnotification 메서드는 원격 알림을 수신한 후 앱에서 로컬 알림을 트리거하는 코드를 포함하고 있습니다 parse는 firebase가 데이터로 팝업 알림을 자동으로 트리거하지 않기 때문에 이 코드를 요구합니다 이에 대한 더 많은 정보와 android 알림 유형은 여기 에서 읽을 수 있습니다 이 configurepushnotifications configurepushnotifications 메서드를 app js app js (또는 app tsx app tsx ) 파일에서 parse를 초기화한 후에 app app 콘텐츠를 선언하기 전에 호출하세요 app js 1 // other imports 2 // 3 import {configurepushnotifications} from ' /src/pushnotificationmethods'; 4	 5 // your parse initialization configuration goes here 6 // 7	 8 // initialize pushnotifications 9 configurepushnotifications(); 애플리케이션을 빌드하고 실행하세요 이제 앱의 back4app 대시보드에서 앱에 해당하는 항목이 있는 설치 설치 테이블을 볼 수 있습니다 5 대시보드를 통한 푸시 알림 전송 이제 앱에 첫 번째 푸시 알림을 보낼 준비가 되었습니다 back4app의 대시보드를 통해 푸시 메시지를 보내려면 아래 단계를 따르세요 back4app 웹사이트 , 로그인하고, 앱을 찾아 대시보드 대시보드 를 클릭하세요 푸시 푸시 > 새 푸시 전송 새 푸시 전송 을 클릭하고 푸시 알림을 위한 대상을 만드세요 3\ 메시지를 작성하고 안드로이드 안드로이드 옵션을 클릭하여 미리보기를 확인하세요 4\ 푸시 알림을 이미 검토했으며 전송하려면 푸시 전송 푸시 전송 을 클릭하십시오 푸시 알림에 대한 다른 옵션을 parse 대시보드 parse 대시보드 에서 탐색할 수 있습니다 거기에서 이전 푸시 이전 푸시 를 확인하고 대상 대상 을 확인할 수 있습니다 6 클라우드 코드를 통한 푸시 알림 전송 클라우드 함수 시작 가이드 https //www back4app com/docs/get started/cloud functions , 재사용 가능한 메서드를 프론트 엔드에서 분리하고 마스터 키를 통해 모든 백엔드 리소스를 완전히 제어할 수 있습니다 푸시 메시지를 전송하기 위해 클라우드 코드 함수를 사용해 보겠습니다 먼저 sendpush sendpush 라는 클라우드 함수를 생성하여 parse push send parse push send 메서드를 호출합니다 알림을 받을 사용자를 선택하는 방법은 두 가지가 있습니다 parse installation parse installation 클래스를 쿼리하거나 알림 채널 이름을 통해 선택하는 것입니다 android 앱에서는 사용자를 구분하기 위해 채널을 사용하는 것이 더 일반적이므로 이를 사용하겠습니다 진행하기 전에 이 함수를 back4app에 배포해야 합니다 오픈 소스 문서 오픈 소스 문서 https //docs parseplatform org/js/guide/#sending options 를 확인하여 전송 전송 메서드에 대한 자세한 내용을 확인하십시오 1 parse cloud define('sendpush', async (request) => { 2 try { 3 await parse push send({ 4 channels \[ 'guidechannel' ], 5 data { 6 message 'test message', 7 title 'back4app guide notification' 8 } 9 }, { usemasterkey true }); 10 return true; 11 } catch (error) { 12 return `error ${error}` 13 } 14 }); 이제 react native 앱에서 함수를 호출해 보겠습니다 이 함수를 pushnotificationmethods js pushnotificationmethods js (또는 pushnotificationmethods tsx pushnotificationmethods tsx ) 파일에 추가하고 애플리케이션의 메인 화면 내 버튼에서 호출하세요 1 export async function sendnotification() { 2 try { 3 await parse cloud run('sendpush'); 4 console log('success!'); 5 } catch (error any) { 6 console log(`error ${error}`); 7 } 8 } 사용자가 스스로 푸시 알림을 트리거할 수 있도록 허용하는 경우는 일반적이지 않다는 점에 유의하세요 여기서는 parse와 푸시 알림 전송을 통합하는 것이 얼마나 간단한지를 보여주기 위해 사용했습니다 결론 이 가이드의 끝에서, android에서 react native 애플리케이션에 parse를 사용하여 푸시 알림을 보내는 방법을 배웠습니다 다음 가이드에서는 ios에서 푸시 알림을 보내는 방법을 배울 것입니다