Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect coming back from app settings/background with React Native

My app asks permission to use location services.

If a user denies permission, they can click a button to go to the settings page and grant permissions.

On ios, they are given the option to return directly to the app. on Android, I think they can do something similar.

Is there a way to detect arriving back at the app so I can check their permissions again?

I've tried with React Navigation's useFocusEffect hook:

useFocusEffect(
    React.useCallback(() => {
        console.log("navigated")
        return () => getPosition()
    }, [])
)

But unfortunately, that only works when navigating between screens/routes in the app.

Is there a way to detect the app transitioning from background to foreground?

like image 728
Eli Nathan Avatar asked Jul 26 '26 09:07

Eli Nathan


2 Answers

You can track app state with https://reactnative.dev/docs/appstate

in pseudo-code: if previously 'background' and now 'active' then run your effects

like image 198
GR34SE Avatar answered Jul 29 '26 02:07

GR34SE


Use this hook:

// hooks/useAppIsActive.ts

import { useCallback, useEffect, useRef } from "react";
import { AppState } from "react-native";

export default (callback: Function) => {
  const appStateRef = useRef(AppState.currentState);
  const handleAppStateChange = useCallback((nextAppState) => {
    if (
      appStateRef.current.match(/inactive|background/) &&
      nextAppState === "active"
    ) {
      callback();
    }

    appStateRef.current = nextAppState;
  }, []);

  useEffect(() => {
    AppState.addEventListener("change", handleAppStateChange);
    return () => {
      AppState.removeEventListener("change", handleAppStateChange);
    };
  }, []);
};

And from the component you want to detect "the come back", pass by parameter the callback you want to run:

const MyView = () => {
  const requestLocationAccess = useCallback(() => {
    // request permissions...
  }, [])

  useAppIsActive(() => requestLocationAccess());
}
like image 23
user2976753 Avatar answered Jul 29 '26 04:07

user2976753



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!