简体   繁体   中英

Kill Background Job on Active App State React Native

I am having problems stopping a background action running in my android app. Basically, the way I am using it in this way: 1- I use an appState hook that lets me know when the app is in foreground or background . 2- When the appState Turns to 'background' I start a background job using BackgroundJob.start() from 'react-native-background-action' . 3-When the appState turns to 'active' (comes back to foreground). I use BackgroundJob.stop()

The problem happens when I kill the app, cause when I kill the app and I lose the reference from the background job I started before, so every time kill the app I add another job to the background making the app work bad, so my question basically is: Did you face the same problem? If you did how did you solve it? If not, do you have another way to solve the problem?

I use the background job cause my app has a speech recognition functionality that gets triggered by a wake word, and it needs to listen when the app is in the background.

useEffect(() => {
    const startBackgroundListening = async () => {
      await BackgroundJob.start(backgroundListening, backgroundOptions);
    };
    const stopPorcupine = async () => {
        await porcupineRef.current?.stop();
        porcupineRef.current?.delete();
    };
    if (currentAppState === 'background') {
      if (isLoggedIn) {
        if (isNotificationShowed === false) {
          handleNotification(
            i18n.t('closingWarning'),
            i18n.t('closingWarningText'),
          );
          uiStore.updateIsNotificationShowed(true);
        }
        if ((isRecord || isCall || isSms || isAlarm) && isBackgroundListeningRunning.current === false) {
          //start background listenning
          startBackgroundListening();
          isBackgroundListeningRunning.current = true;
        }
      }
    } else if (currentAppState === 'active') {
      //stop and delete background listenning in case there is one
        stopPorcupine();
        BackgroundJob.stop();
        isBackgroundListeningRunning.current = false;
    }
  }, [currentAppState]);

The react-native-background-action documentation ( https://www.npmjs.com/package/react-native-background-actions ) states that "If you call stop() on background no new tasks will be able to be started! Don't call .start() twice, as it will stop performing previous background tasks and start a new one. If .start() is called on the background, it will not have any effect." If your concern was that multiple Background tasks would run simultaneously and cause bad app performance, the documentation shows calling .start() stops any previous background tasks, so you should be fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM