Push notifications via FCM on standalone expo android build not triggering

Please provide the following:

  1. SDK Version: 42
  2. Platforms(Android/iOS/web/all): Android
  3. Add the appropriate “Tag” based on what Expo library you have a question on.

I’m using “expo-notifications”, and Listeners working perfectly as I’m expecting with “scheduleNotificationAsync” only, not with the FCM notifications.

I’m getting notifications from FCM requests (PHP code) when APP in the background only, But nothing happens when I clicking on a notification even APP not opening and listening to notification listeners.

Please help me ASAP :pray: :pray:
Using following code - app.js

import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import React, { useState, useEffect, useRef } from "react";
import { Text, View, Button, Platform, Clipboard, Alert } from "react-native";

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

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) => {
        Alert.alert("notification ==>>", JSON.stringify(notification));
        setNotification(notification);
      });

    responseListener.current =
      Notifications.addNotificationResponseReceivedListener((response) => {
        Alert.alert("notification response ==>>", JSON.stringify(response));
        setNotification(response);
      });

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

  const copyToClipboard = () => {
    Clipboard.setString(expoPushToken);
  };

  return (
    <View
      style={{
        flex: 1,
        alignItems: "center",
        justifyContent: "space-around",
      }}
    >
      <Text>Your expo push token: {expoPushToken}</Text>
      <View style={{ alignItems: "center", justifyContent: "center" }}>
        <Text>
          CompleteContent: {notification && JSON.stringify(notification)}{" "}
        </Text> 
      </View>
      <Button title="Press to Copy" onPress={copyToClipboard} />
      <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 (Constants.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;
    }
    token = (await Notifications.getDevicePushTokenAsync()).data;
  } else {
    alert("Must use physical device for Push Notifications");
  }

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

  return token;
}

Using following code in app.json

{

  "expo": {

    "name": "Coin",

    "slug": "Coin",

    "version": "1.0.0",

    "orientation": "portrait",

    "icon": "./assets/icon.png",

    "notification": {

      "iosDisplayInForeground": true

    },

    "splash": {

      "image": "./assets/splash.png",

      "resizeMode": "contain",

      "backgroundColor": "#ffffff"

    },

    "updates": {

      "fallbackToCacheTimeout": 0,

      "enabled": false

    },

    "assetBundlePatterns": ["**/*"],

    "ios": {

      "supportsTablet": true

    },

    "android": {

      "useNextNotificationsApi": true,

      "package": "com..........",

      "googleServicesFile": "./google-services.json",

      "adaptiveIcon": {

        "foregroundImage": "./assets/adaptive-icon.png",

        "backgroundColor": "#FFFFFF"

      }

    },

    "web": {

      "favicon": "./assets/favicon.png"

    }

  }

}

Im having the same issue I believe. use the following modified code to print out the results of the push notification send. Mine says “Failed to authenticate with the FCM server. Ensure the FCM server key you uploaded is correct.”, even thought i’ve made sure my API is correct manually uploading it via expo push:android:upload --api-key

async function sendPushNotification(expoPushToken) {
    const message = {
        to: `${expoPushToken}`,
        sound: 'default',
        title: 'Original Title',
        body: 'And here is the body!',
        data: { someData: 'goes here' },
    }

    const response = await fetch('https://exp.host/--/api/v2/push/send', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Accept-encoding': 'gzip, deflate',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(message),
    })

    const data = await response.json()
    console.log(
        '🚀 ~ file: NotificationTest.js ~ line 111 ~ sendPushNotification ~ data',
        data
    )
}

Using the following PHP code to send FCM notifications to mobile devices based on Device Token. Getting successful notification, but not able to get notification data after clicking on the notification in android device.

<?php
$deviceToken ="eUq89SicREKdibUoPYrwUv.............";
$url = 'https://fcm.googleapis.com/fcm/send';
$msg = array
                        ( 'body'  => 'body msg AK',
                        'title' => 'title AK',
                        );

$fields = array (
        'to'            =>  $deviceToken,
        'notification'  => $msg,
        'data' => array (
                "description" => 'body msg AK', 
                'title' =>  'title AK'
        ), 
        'priority' =>  'high',
);
$fields = json_encode ( $fields );

$headers = array (
        'Authorization: key=' . "AAAAbKdNPXA...........", //This is the "Server key" above "Sender ID"
        //This matches "Project Settings" > "Cloud Messaging" > [Server Key]
        //If this is wrong it returns: INVALID_KEY error 401. So I know this is correct.
        'Content-Type: application/json'
);

$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );

?>

I had a similar issue. What worked for me was to get rid of the useEffect hook, I believe there are some problems with the time it takes to initialize the listener

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.