[따라하며 배우는 리액트 네이티브 기초] 섹션 8 - 안드로이드 알림 기능

posinity·2023년 7월 4일
0

라이브러리 설치

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

npm install --save react-native-push-notification

깃허브 설치 따라하기

android/build.gradle

buildscript {
    ext {
      // 추가
        googlePlayServicesVersion = "+"
        firebaseMessagingVersion = "21.1.0" 

        buildToolsVersion = "33.0.0"
        minSdkVersion = 21
        compileSdkVersion = 33
        targetSdkVersion = 33

        // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
        ndkVersion = "23.1.7779620"
    }

android/app/src/main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

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

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
    <!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="false"/>
        <!-- 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="@color/white"/> <!-- or @android:color/{name} to use a standard color -->

        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:exported="false" android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

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

    </application>
</manifest>

android/app/src/main/res/values/colors.xml (없으면 새로 만들기)

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

index.js 코드 추가

 * @format
 */

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import PushNotification from 'react-native-push-notification';

PushNotification.configure({
  onNotification: function (notification) {
    console.log('notification', notification);
  },
  popInitialNotification: true,
  requestPermissions: Platform.OS === 'ios',
});

AppRegistry.registerComponent(appName, () => App);

이 상태에서 npm run android 해본다

관련해서 빌드 에러 나면 참고

[에러] Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

home.js에 채널 생성하기

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

const Home = () => {
  useEffect(() => {
    createChannel();
  }, []);

  const createChannel = () => {
    PushNotification.createChannel({
      channelId: 'insta-channel',
      channelName: 'insta Channel',
    });
  };
  return (

프로필 이미지 클릭 시 알림 뜨게 하기

/// PostItem.js

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

const PostItem = ({data}) => {
  const [like, setLike] = useState(data.isLiked);

  const handleNotification = title => {
    PushNotification.getChannels(function (channel_ids) {
      console.log(channel_ids);
    });

    PushNotification.localNotification({
      channelId: 'insta-channel',
      title: `${title}를 클릭했습니다.`,
      message: `메시지 입니다.`,
    });
  };

  return (
    ...
    //프로필이미지를 TouchableOpacity로 감싸주고 onPress 함수 추가
    <TouchableOpacity onPress={() => handleNotification(data.postTitle)}>
            <Image
              source={data.postPersonImage}
              style={{width: 40, height: 40, borderRadius: 100}}
            />
          </TouchableOpacity>

추가 옵션

나의 경우엔 먹히지 않았음

쌓여있는 알람을 지우고 새로 보내기

상태표시줄에 들어가보면 알람이 쌓여있는 것을 볼 수 있음

const handleNotification = title => {
    PushNotification.getChannels(function (channel_ids) {
      console.log(channel_ids);
    });

    PushNotification.cancelAllLocalNotifications(); //이부분 추가

    PushNotification.localNotification({
      channelId: 'insta-channel',
      title: `${title}를 클릭했습니다.`,
      message: `메시지 입니다.`,
      color: 'red',
      bigText: 'My big text',
    });
  };

일정 시간 후에 알람 오게 하기

PushNotification.localNotificationSchedule({
      channelId: 'insta-channel',
      title: `${title}를 클릭했습니다.`,
      message: `메시지 입니다.`,
      color: 'red',
      date: new Date(Date.now() + 5 * 1000), //시간 설정. 5초
      allowWhileIdle: true,
    });
profile
문제를 해결하고 가치를 제공합니다

0개의 댓글