Expo Notificationsで通知を受信する Android編

Expo Goでプッシュ通知を受信する

まずはインストール。

npx expo install expo-notifications

公式のサンプルコードをそのままコピペ。

import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

export default function App() {
  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      console.log(response);
    });

    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  return (
    <View
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'space-around',
      }}>
      <Text>Your expo push token: {expoPushToken}</Text>
      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
        <Text>Title: {notification && notification.request.content.title} </Text>
        <Text>Body: {notification && notification.request.content.body}</Text>
        <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
      </View>
      <Button
        title="Press to schedule a notification"
        onPress={async () => {
          await schedulePushNotification();
        }}
      />
    </View>
  );
}

async function schedulePushNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: "You've got mail! 📬",
      body: 'Here is the notification body',
      data: { data: 'goes here' },
    },
    trigger: { seconds: 2 },
  });
}

async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    // Learn more about projectId:
    // https://docs.expo.dev/push-notifications/push-notifications-setup/#configure-projectid
    token = (await Notifications.getExpoPushTokenAsync({ projectId: 'your-project-id' })).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  return token;
}

Expo Goを立ち上げて確認。トークンが表示され、ボタンをクリックすると通知が届きます。

アイコンや音を変えるには、下記コードをapp.jsonに追記します。

{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "icon": "./local/assets/notification-icon.png",
          "color": "#ffffff",
          "sounds": [
            "./local/assets/notification-sound.wav",
            "./local/assets/notification-sound-other.wav"
          ]
        }
      ]
    ]
  }
}

Android 13では正確な時間に通知を受け取るために、RECEIVE_BOOT_COMPLETEDSCHEDULE_EXACT_ALARMの権限が必要らしいのでapp.jsonに追記します。

"permissions": [
  "SCHEDULE_EXACT_ALARM",
  "RECEIVE_BOOT_COMPLETED"
]

ここまでは簡単ですね。

EASビルドでプッシュ通知を受信する

ここからがちょっとややこしい。ここまでの作業ではExpo Goで通知を受信することはできるのですが、開発ビルドやリリースビルドでは受信できないのです。

開発やリリース用のビルドで通知を受信するためには、Firebase Cloud Messaging の認証情報が必要になります。(Androidの場合)

Push notifications setup
Learn how to set up push notifications, get credentials for development and production, and send a testing push notifica...

公式サイトに丁寧に説明が載っているので書いてある通りにやれば大丈夫なのですが、毎回どこかを抜かしてしまい、無駄に無料ビルド回数を消費してしまいます。。。

忘れないようにまとめたいところですが、公式サイトを見ると今のやり方はすでに非推奨らしく、もうすぐ使えなくなるらしい。なので新しいやり方が公開されたらあらためて記事にまとめたいと思います!

タイトルとURLをコピーしました