Having trouble implementing UsageStats module into my React Native app

276 Views Asked by At

I have a react native app that needs to retrieve the amount of time the user has spent on social medai related apps. In this case it'll be facebook, instagram, tiktok, etc.

I'm not very familiar with java/kotlin syntax wise and really struggling to figure out how to implement this. I'm pretty sure that it will just be one function that should be called in the react native code to retrieve a list of the time spent on each app.

Here is what I have so far. One of the issues I am struggling with, for example, is that I don't get what Context is. How would this apply in React Native?

public static HashMap<String, Double> getUsageMap(Context context, long start, long end) {
    UsageStatsManager manager = (UsageStatsManager) context.getSystemService("usagestats");
    Map<String, UsageStats> usageStatsMap = manager.queryAndAggregateUsageStats(start, end);
    HashMap<String, Double> usageMap = new HashMap<>();

    for (String packageName : usageStatsMap.keySet()) {
        UsageStats us = usageStatsMap.get(packageName);
        try {
            long timeMs = us.getTotalTimeInForeground();
            Double timeSeconds = new Double(timeMs / 1000);
            usageMap.put(packageName, timeSeconds);
        } catch (Exception e) {
            Log.d(TAG, "Getting timeInForeground resulted in an exception");
        }
    }
    return usageMap;
}

And here is the react native component I wanna call it in:

import React from "react";
import { View, Text, StyleSheet, NativeModules } from "react-native";
import { Button } from "react-native-paper";

const Symptom4 = ({navigation}) => {
  const {UsageStats} = ReactNative.NativeModules;
  //const listOfVals = UsageStats.getUsageMap()
  //console.log(listOfVals)
  return (
    <View style={styles.container}>
      <Text>{/*listOfVals*/}</Text>
      <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: 'white' }, 
});

export default Symptom4;

Any idea? Help would be much appreciated

0

There are 0 best solutions below