Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //// App.js
- const { permissions, schedulePushNotification } = useNotifications();
- return(
- <>
- <Button title="Enable notifications - onboarding screen only button" onPress={permissions} />
- <Button title="Schedule notification" onPress={schedulePushNotification} />
- </>
- )
- /// useNotifications.js hook
- import { View, Text, Platform } from "react-native";
- import React, { useEffect, useState, useRef } from "react";
- import * as Notifications from "expo-notifications";
- import * as Device from "expo-device";
- // import { useNavigation } from "@react-navigation/native";
- Notifications.setNotificationHandler({
- handleNotification: async () => ({
- shouldShowAlert: true,
- shouldPlaySound: true,
- shouldSetBadge: false,
- }),
- });
- export default function useNotifications() {
- const [expoPushToken, setExpoPushToken] = useState("");
- const [givenNotificationPerm, setGivenNotificationPerm] = useState(false);
- const [notification, setNotification] = useState(false);
- const notificationListener = useRef();
- const responseListener = useRef();
- useEffect(() => {
- // permissions(); - asks for permission
- givenPermissions(); // checks if has permissions
- getScheduled(); // get current notifications in pipeline
- notificationListener.current =
- Notifications.addNotificationReceivedListener((notification) => {
- setNotification(notification);
- console.log("--- notification received ---");
- // const show_time = notification?.request?.trigger?.dateComponents;
- // console.log(show_time);
- console.log(notification);
- console.log("------");
- });
- responseListener.current =
- Notifications.addNotificationResponseReceivedListener((response) => {
- console.log("--- notification tapped ---");
- const screen = response?.notification?.request?.content?.data?.screen;
- const show_time =
- response?.notification?.request?.content?.data?.show_time; // temp
- // navigation.navigate("Root", { screen: screen });
- console.log("this showed: " + show_time);
- console.log("------");
- });
- return () => {
- Notifications.removeNotificationSubscription(
- notificationListener.current
- );
- Notifications.removeNotificationSubscription(responseListener.current);
- };
- }, []);
- async function permissions() {
- registerForPushNotificationsAsync().then((token) =>
- setExpoPushToken(token)
- );
- }
- async function getScheduled() {
- console.log("getting schedfuled notifcation");
- const slay = await Notifications.getAllScheduledNotificationsAsync();
- console.log("scheduled:");
- console.log(slay);
- }
- async function schedulePushNotification() {
- console.log("reqested notifcation");
- const randomSeconds = Math.floor(Math.random() * 20) + 1;
- const months = [
- "January",
- "February",
- "March",
- "April",
- "May",
- "June",
- "July",
- ];
- const random = Math.floor(Math.random() * months.length);
- const trigger = await Notifications.getNextTriggerDateAsync({
- second: randomSeconds,
- repeats: true,
- });
- await Notifications.scheduleNotificationAsync({
- content: {
- title: "A test notif!",
- body: `${months[random]} is random`,
- data: { screen: "screenName", show_time: trigger.second },
- },
- trigger,
- });
- getScheduled();
- }
- 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;
- }
- token = (await Notifications.getExpoPushTokenAsync()).data;
- console.log(token);
- } else {
- alert("Must use physical device for Push Notifications");
- }
- return token;
- }
- async function givenPermissions() {
- if (Device.isDevice) {
- const { status: existingStatus } =
- await Notifications.getPermissionsAsync();
- if (existingStatus !== "granted") {
- setGivenNotificationPerm(false);
- }
- setGivenNotificationPerm(true);
- } else {
- alert("Must use physical device for Push Notifications");
- }
- }
- return {
- expoPushToken,
- notification,
- permissions,
- schedulePushNotification,
- givenNotificationPerm,
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement