Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How could I get the steps data from Headless? #358

Open
wkchoong opened this issue May 4, 2024 · 0 comments
Open

How could I get the steps data from Headless? #358

wkchoong opened this issue May 4, 2024 · 0 comments

Comments

@wkchoong
Copy link

wkchoong commented May 4, 2024

I have try using the react-native-background-fetch and only works from foreground to get the data but when the app has terminated it will not get the data. I was stuck on "Step: 4" from "backgroundTask" function. Let me know how to solve this and thanks.

 export const backgroundTask = async (mode: string) => {
  return new Promise<void>(async (resolve, reject) => {
    try {
      await AsyncStorage.setItem('@type', mode);
      await AsyncStorage.setItem('@lasted-update-time', moment().format('lll'));
      const permission = await check(PERMISSIONS.ANDROID.ACTIVITY_RECOGNITION);
      await AsyncStorage.setItem('@run', 'Step: 1');
      if (permission === 'granted') {
        await AsyncStorage.setItem('@run', 'Step: 2');
        const netInfo = await NetInfo.fetch();
        if (netInfo.isConnected) {
          await AsyncStorage.setItem('@run', 'Step: 3');
          await googleFitRecording();
          await AsyncStorage.setItem('@run', 'Step: 4');
          const todaySteps = await GoogleFit.getDailySteps(new Date());
          await AsyncStorage.setItem('@run', 'Step: 5');
          const currentSteps = _.toNumber(
            _.get(todaySteps, '[2].steps[0].value', 0),
          );
          const jsonItemsFromStorage = await AsyncStorage.getItem('@items');
          if (jsonItemsFromStorage) {
            const formatItems = JSON.parse(jsonItemsFromStorage);
            const newItemsData = [
              ...formatItems,
              {
                label: moment().format('lll'),
                type: 'Background Mode',
                currentSteps,
              },
            ];
            await AsyncStorage.setItem('@items', JSON.stringify(newItemsData));
          } else {
            await AsyncStorage.setItem(
              '@items',
              JSON.stringify([
                {
                  label: moment().format('lll'),
                  type: 'Background Mode',
                  currentSteps,
                },
              ]),
            );
          }
          return resolve();
        } else {
          return resolve();
        }
      } else {
        return resolve();
      }
    } catch (e) {
      await AsyncStorage.setItem('@error', _.get(e, 'message', ''));
      return reject(e);
    }
  });
};
export const googleFitRecording = async () => {
  return new Promise((resolve, _reject) => {
    GoogleFit.startRecording(
      callback => {
        // Process data from Google Fit Recording API (no google fit app needed)
        return resolve(callback);
      },
      ['step', 'activity', 'distance'],
    );
  });
};

  useEffect(() => {
    if (Platform.OS === 'android') {
      initGoogleFit();

      initBackground().finally(() => {
        BackgroundFetch.scheduleTask({
          taskId: 'com.testtrackinghealth.tracksteps',
          stopOnTerminate: false,
          enableHeadless: true,
          startOnBoot: true,
          delay: 60000,
          forceAlarmManager: true,
          periodic: true,
        });
      });
    }
  }, []);

  const initGoogleFit = async () => {
    const options = {
      scopes: [Scopes.FITNESS_ACTIVITY_READ, Scopes.FITNESS_ACTIVITY_WRITE],
    };

    const permissionResult = await request(
      PERMISSIONS.ANDROID.ACTIVITY_RECOGNITION,
    );
    switch (permissionResult) {
      case 'granted':
        const authorizeRes = await GoogleFit.authorize(options);
        if (authorizeRes.success === true) {
          await googleFitRecording();
        }
        break;
      case 'denied':
        break;
      case 'blocked':
        break;
      case 'limited':
        break;
      case 'unavailable':
        break;
      default:
        break;
    }
  };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant