Приложение Expo: воспроизводите звук на push -уведомление, пока приложение находится в фоновом режиме или закрытоAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Приложение Expo: воспроизводите звук на push -уведомление, пока приложение находится в фоновом режиме или закрыто

Сообщение Anonymous »

Я создаю приложение Expo для торговцев, чтобы получать заказы от веб -клиентов.
Когда приходит заказ (через push -уведомление), приложение должно воспроизводить звук или тревоги. React Native?
Должен ли я использовать AppState, фоновый сервис или что -то еще? Любые предложения или примеры будут оценены!import { AppState, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import Checkbox from 'expo-checkbox';
import { defineTask } from 'expo-task-manager';
import {
addNotificationReceivedListener,
addNotificationResponseReceivedListener,
AndroidImportance,
getExpoPushTokenAsync,
getNotificationChannelsAsync,
getPermissionsAsync,
Notification,
NotificationChannel,
NotificationResponse,
registerTaskAsync,
removeNotificationSubscription,
requestPermissionsAsync,
setNotificationChannelAsync,
setNotificationHandler,
EventSubscription,
useLastNotificationResponse,
} from 'expo-notifications';
import Constants from 'expo-constants';

// https://github.com/expo/expo/tree/main/ ... ations#api
// setNotificationHandler -- sets the handler function responsible for deciding what to do with a notification that is received when the app is in foreground
// Foreground
setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});

// Background task
// Reacts to data only notifications
// https://github.com/expo/expo/issues/296 ... 2166499879
// EXAMPLE: Send only "to" and "data" parameters
// {
// to: pushToken,
// data: { someLocalData: 'goes here' },
// }
// https://github.com/expo/expo/tree/main/ ... in-expo-go
const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
defineTask(BACKGROUND_NOTIFICATION_TASK, async ({ data, error, executionInfo }) => {
console.log(
`${Platform.OS} BACKGROUND-NOTIFICATION-TASK: App in ${AppState.currentState} state.`,
);

if (error) {
console.log(`${Platform.OS} BACKGROUND-NOTIFICATION-TASK: Error! ${JSON.stringify(error)}`);

return;
}

if (AppState.currentState.match(/inactive|background/) === null) {
console.log(
`${Platform.OS} BACKGROUND-NOTIFICATION-TASK: App not in background state, skipping task.`,
);

return;
}

console.log(
`${
Platform.OS
} BACKGROUND-NOTIFICATION-TASK: Received a notification in the background! ${JSON.stringify(
data,
null,
2,
)}`,
);
});

// Background task
// Reacts to data only notifications
// https://github.com/expo/expo/issues/296 ... 2166499879
// EXAMPLE: Send only "to" and "data" parameters
// {
// to: pushToken,
// data: { someLocalData: 'goes here' },
// }
registerTaskAsync(BACKGROUND_NOTIFICATION_TASK)
.then(() => {
console.log(
`${Platform.OS} Notifications.registerTaskAsync success: ${BACKGROUND_NOTIFICATION_TASK}`,
);
})
.catch((reason) => {
console.log(`${Platform.OS} Notifications registerTaskAsync failed: ${reason}`);
});

async function registerForPushNotificationsAsync() {
if (Platform.OS === 'android') {
console.log(`${Platform.OS} Set channel default setNotificationChannelAsync`);

// https://github.com/expo/expo/tree/main/ ... ations#api
// setNotificationChannelAsync -- saves a notification channel configuration
await setNotificationChannelAsync('default', {
name: 'default',
importance: AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}

// https://github.com/expo/expo/tree/main/ ... ations#api
// getPermissionsAsync -- fetches current permission settings related to notifications
const { status: existingStatus } = await getPermissionsAsync();
let finalStatus = existingStatus;

if (existingStatus !== 'granted') {
// https://github.com/expo/expo/tree/main/ ... ations#api
// requestPermissionsAsync -- requests permissions related to notifications
const { status } = await requestPermissionsAsync();
finalStatus = status;
}

if (finalStatus !== 'granted') {
handleRegistrationError('Permission not granted to get push token for push notification!');
return;
}

const projectId = Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;

if (!projectId) {
handleRegistrationError('Project ID not found');
}

try {
const pushTokenString =
// https://github.com/expo/expo/tree/main/ ... ations#api
// getExpoPushTokenAsync -- resolves with an Expo push token
(
await getExpoPushTokenAsync({
projectId,
})
).data;

console.log(`${Platform.OS} Got Expo push token ${pushTokenString}`);

return pushTokenString;
} catch (e: unknown) {
handleRegistrationError(`${e}`);
}
}

function handleRegistrationError(errorMessage: string) {
alert(errorMessage);
throw new Error(errorMessage);
}

export default function App() {
const [expoPushToken, setExpoPushToken] = useState('');
const [channels, setChannels] = useState([]);
const [notification, setNotification] = useState(undefined);
const [response, setResponse] = useState(undefined);
const notificationListener = useRef();
const responseListener = useRef();

useEffect(() => {
console.log(`${Platform.OS} Getting Expo Token with registerForPushNotificationsAsync`);
registerForPushNotificationsAsync()
.then((token) => setExpoPushToken(token ?? ''))
.catch((error: any) => setExpoPushToken(`${error}`));

getNotificationChannelsAsync().then((value) => setChannels(value ?? []));
}, []);

useEffect(() => {
// https://github.com/expo/expo/tree/main/ ... ations#api
// addNotificationReceivedListener -- adds a listener called whenever a new notification is received
// Foreground
console.log(`${Platform.OS} Creating notificationListener`);
notificationListener.current = addNotificationReceivedListener((notification) => {
console.log(
`${
Platform.OS
} Notification received through notificationListener [NotificationReceivedListener] ${JSON.stringify(
notification,
null,
2,
)}`,
);

setNotification(notification);
});

// https://github.com/expo/expo/tree/main/ ... ations#api
// addNotificationResponseReceivedListener -- adds a listener called whenever user interacts with a notification
// Foreground & Background & Killed
console.log(`${Platform.OS} Creating responseListener`);
responseListener.current = addNotificationResponseReceivedListener((response) => {
console.log(
`${
Platform.OS
} Response received through responseListener [NotificationResponseReceivedListener] ${JSON.stringify(
response,
null,
2,
)}`,
);

setResponse(response);
});

console.log(`${Platform.OS} added listeners`);

return () => {
// https://github.com/expo/expo/tree/main/ ... ations#api
// removeNotificationSubscription -- removes the listener registered with addNotificationReceivedListener()
console.log(`${Platform.OS} Removing notificationListener`);
notificationListener.current && removeNotificationSubscription(notificationListener.current);

// https://github.com/expo/expo/tree/main/ ... ations#api
// removeNotificationSubscription -- removes the listener registered with addNotification*Listener()
console.log(`${Platform.OS} Removing responseListener`);
responseListener.current && removeNotificationSubscription(responseListener.current);
};
}, []);

// https://github.com/expo/expo/tree/main/ ... ations#api
// useLastNotificationResponse -- a React hook returning the most recently received notification response
// Foreground & Background
const lastNotificationResponse = useLastNotificationResponse();
useEffect(() => {
if (lastNotificationResponse === undefined || lastNotificationResponse === null) {
console.log(
`${
Platform.OS
} lastNotificationResponse is undefined or null [useLastNotificationResponse] ${JSON.stringify(
lastNotificationResponse,
null,
2,
)}`,
);

return;
}

console.log(
`${
Platform.OS
} Got notification from lastNotificationResponse [useLastNotificationResponse] ${JSON.stringify(
lastNotificationResponse,
null,
2,
)}`,
);
}, [lastNotificationResponse]); //

Подробнее здесь: https://stackoverflow.com/questions/795 ... -or-closed
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»