android 如何在应用程序进入react-native后台1分钟后执行函数

vcirk6k6  于 2023-08-01  发布在  Android
关注(0)|答案(1)|浏览(118)

我想执行一个功能,并沿着导航变化的状态变化时,应用程序去后台后1分钟,它在React Native,我用我的代码,但它不工作。

useEffect(() => {
        let timeoutId;
        const handleAppStateChange = (nextAppState) => {
            // nextAppState can be 'active', 'background', or 'inactive'
            if (nextAppState === 'background') {
                // Your app is transitioning to the background
                console.log('App is in the background');
                isBackgndRef.current = true
       
                timeoutId = setTimeout(() => {
                    checkCondition();
                }, 20000);
                // You can perform any background-related tasks here
            } else if (nextAppState === 'active') {
                // Your app is transitioning to the foreground
                console.log('App is in the foreground');
                // You can perform any foreground-related tasks here
                if (isBackgndRef.current == true) {console.log("checking");
                    clearTimeout(timeoutId);
                    isBackgndRef.current = false;
                }
            }
        }
        // Add the event listener when the component mounts
        AppState.addEventListener('change', handleAppStateChange);

        // Clean up the event listener when the component unmounts
        return () => {
            AppState.removeEventListener('change', handleAppStateChange);
            clearTimeout(timeoutId); console.log("return called");
        };
    }, []);

字符串

vmdwslir

vmdwslir1#

后台应用状态请使用react-native-background-timer插件中的setTimeout(),而不是react-native setTimout()。
使用以下链接查找react-native-background-timer插件:https://www.npmjs.com/package/react-native-background-timer

相关问题