Я создал функцию startStask, чтобы запустить мою фоновую задачу с помощью BackgroundFetch из 'react-native-background-fetch', вот так:
Код: Выделить всё
const startStask = async () => {
try {
console.log('try ok');
await BackgroundFetch.configure(
{
minimumFetchInterval: 15,
stopOnTerminate: true,
startOnBoot: true,
},
async taskId => {
console.log('[BackgroundFetch] taskId: ', taskId);
await locationAndNotificationTask();
BackgroundFetch.finish(taskId);
},
error => {
console.log('[BackgroundFetch] failed to start');
},
);
} catch (error) {
console.log('start BG stask err', error);
}
};
Эта функция вызывается с таким действием переключения:
р>
Код: Выделить всё
const toggleSwitch = async () => {
const newValue = !isEnabled;
try {
console.log('okay ! ', newValue)
if (newValue) {
setIsEnabled(newValue); // true
await AsyncStorage.setItem('notifications_status', `${newValue}`);
backgroundTaskIsRunning() ? null : await startStask();
} else {
setIsEnabled(newValue); // false
await AsyncStorage.setItem('notifications_status', `${newValue}`);
await stopStask();
}
} catch (error) {
console.log('menuScreen err', error);
}
};
- React-native 0.73.2
- minSdkVersion = 21
- compileSdkVersion = 34
- targetSdkVersion = 34
- react-native-background-fetch: "^4.2.1",
Подробнее здесь: https://stackoverflow.com/questions/778 ... k-function
Мобильная версия