简介

Expo 是一个非常有用的开发 Android 应用程序的框架。

文档清晰明了,但我观察到没有好的文章或博客存在,所以在这篇文章中,我将解释如何在你的应用程序中获取本地通知。

我正在开发一个名为Timely的时间表管理应用程序,它会在课程开始前 5 分钟发送通知。

我花了很多时间浏览 GitHub 和 Stack Overflow,寻找一些答案,以找到每周在特定时间发送通知的方法。

展会通知

我们将使用 Expo Notifications,因为该项目是在 Expo 上构建的。

最好的方法显然是阅读提供的文档

世博会

**注意 - 通知在模拟器上不起作用,**因此请确保使用物理设备。

第 1 步:安装 Expo Notifications

第一步是安装包

expo install expo-notifications

进入全屏模式 退出全屏模式

第二步:初始化通知处理程序

import * as Notifications from "expo-notifications";

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

进入全屏模式 退出全屏模式

这将启用应用程序的通知。

这可以在您的入口点文件(如 App.js)或单独的文件中完成,甚至可以使用 Context API。

现在,expo 通知的工作原理是我们创建一个分配了唯一 ID 的通知,该 ID 可用于稍后删除它。每个推送通知都分配有一个推送令牌 ID。

第三步:编写通知函数

此功能添加通知侦听器和订阅者以及为您的 Expo 应用程序获取本地通知所需的所有必要内容。

export default function Notification() {
  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 (
    null
  );
}

进入全屏模式 退出全屏模式

此代码可以按原样用于大多数项目。

第四步:日程通知功能

这将被调用以安排通知。由于我正在开发一个时间表管理器应用程序,因此通知需要在通知中显示星期几、小时和分钟的时间以及其他信息。

export async function schedulePushNotification(
  className,
  slot,
  type,
  time,
  day
) {
  time = new Date(time.getTime() - 5 * 60000);
  var days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  const weekday = days.indexOf(day) + 1;
  const hours = time.getHours();
  const minutes = time.getMinutes();
  const id = await Notifications.scheduleNotificationAsync({
    content: {
      title: className + " " + type,
      body: slot,
      // sound: 'default',
    },
    trigger: {
      weekday: weekday,
      hour: hours,
      minute: minutes,
      repeats: true,
    },
  });
  console.log("notif id on scheduling",id)
  return id;
}

进入全屏模式 退出全屏模式

您在内容中放置的内容将是通知中显示给您的内容。

触发对象包含必要的触发条件。

你可以在这里找到更多关于的信息

第五步:注册推送通知功能

该函数再次可以按原样使用,因为它向用户请求发送通知的权限并注册通知。

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.getExpoPushTokenAsync()).data;
    console.log(token);
  } 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],
      sound: true,
      lightColor: "#FF231F7C",
      lockscreenVisibility: Notifications.AndroidNotificationVisibility.PUBLIC,
      bypassDnd: true,
    });
  }

  return token;
}

进入全屏模式 退出全屏模式

在 Android 设备的条件检查中,我们可以为通知指定我们想要的各种内容,例如声音真假或振动模式,是否绕过免打扰等,这些也可以在为 Expo Notifications 提供的文档中找到。

第 6 步:取消通知

假设用户为课程创建了提醒,但后来想要将其关闭。如果我们没有这个功能,用户即使在删除提醒之后,也会永远收到通知,因为通知是在设备本身注册的。 (可能擦除数据和缓存会起作用)因此,如果我们向它提供创建通知时生成的通知 ID,此功能将使我们能够取消任何通知。

export async function cancelNotification(notifId){
  await Notifications.cancelScheduledNotificationAsync(notifId);
}

进入全屏模式 退出全屏模式

结论

现在我们可以在需要时调用创建通知函数或取消通知函数。

我将链接 GitHub 以获取应用程序的整个代码。随时查看并发送任何 PR 以进行改进!

另外,如果您能建议改进这篇文章以及代码,我会很高兴。

谢谢!

GitHub Repo 链接供参考

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐