An open API service indexing awesome lists of open source software.

https://github.com/kingstinct/react-native-motion-activity-tracker


https://github.com/kingstinct/react-native-motion-activity-tracker

Last synced: 11 months ago
JSON representation

Awesome Lists containing this project

README

          

# react-native-motion-activity-tracker

[![Test Status](https://github.com/Kingstinct/react-native-motion-activity-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/Kingstinct/react-native-motion-activity-tracker/actions/workflows/test.yml)
[![Latest version on NPM](https://img.shields.io/npm/v/react-native-motion-activity-tracker)](https://www.npmjs.com/package/react-native-motion-activity-tracker)
[![Discord](https://dcbadge.vercel.app/api/server/5wQGsRfS?style=flat)](https://discord.gg/5wQGsRfS)

A React Native library to access and track motion activity data using Apple's Core Motion API. It supports activities like walking, running, automotive, stationary, and cycling, with real-time updates and historical data fetching.

## Features

- Check motion activity authorization status.
- Start and stop real-time motion tracking.
- Fetch historical activity data.
- Built for iOS with Core Motion API & for android with Activity Recognition API

**Note**: This library requires a custom dev client when using with Expo.

# React Native Motion Activity Tracker

## Managed Expo Workflow

### Installation

1. Install the package:

```bash
npm install react-native-motion-activity-tracker

```
2. Add this to ur app.son

{
"expo": {
"plugins": [
"react-native-motion-activity-tracker"
]
}
}

```
3. If you want to customize the iOS permission description, you can configure it like this:
{
"expo": {
"plugins": [
[
"react-native-motion-activity-tracker",
{
"NSMotionUsageDescription": "This app uses motion data to enhance your experience."
}
]
]
}
}

4. After making these changes, rebuild your app to apply the native changes:

```bash
expo prebuild
```

# Examples

```TypeScript
import * as MotionActivityTracker from "motion-activity-tracker";
import React, { useEffect, useState } from "react";
import { Text, View, Button, StyleSheet } from "react-native";

export default function App() {
const [message, setMessage] = useState("Initializing...");
const [tracking, setTracking] = useState(false);
const [data, setData] = useState<
MotionActivityTracker.HistoricalActivity[] | undefined
>();
const startDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); // One week ago
const endDate = new Date();

// Fetch historical activity data
useEffect(() => {
const setActivityHistoricalData = async () => {
const data = await MotionActivityTracker.getHistoricalData(
startDate,
endDate,
);
if (data) {
console.log(data[0]);
setData(data);
}
};
setActivityHistoricalData();
}, []);

// Subscribe to motion state changes
useEffect(() => {
const subscription = MotionActivityTracker.addMotionStateChangeListener(
(event) => {
console.log("New Motion State:", event.state); // Log the new state
setMessage(`Tracking started: ${event.state}`); // Update the message
},
);

return () => {
subscription.remove(); // Clean up subscription on unmount
};
}, [message]);

const handleStartTracking = async () => {
try {
const result = await MotionActivityTracker.startTracking();
setMessage(`Tracking started: ${result}`);
setTracking(true);
} catch (error) {
setMessage(`Error: ${error}`);
console.error(error);
}
};

const handleStopTracking = () => {
MotionActivityTracker.stopTracking();
setMessage("Tracking stopped");
setTracking(false);
};

return (

{message}

{data && data.length > 0 && (

{/* Display the latest entry */}
{(() => {
const latestActivity = data.reduce((latest, current) =>
current.timestamp > latest.timestamp ? current : latest,
);

return (
<>

Automotive: {latestActivity.automotive ? "Yes" : "No"}


Running: {latestActivity.running ? "Yes" : "No"}


Stationary: {latestActivity.stationary ? "Yes" : "No"}


Timestamp: {new Date(latestActivity.timestamp * 1000).toLocaleString()}


Unknown: {latestActivity.unknown ? "Yes" : "No"}


Walking: {latestActivity.walking ? "Yes" : "No"}


Confidence: {latestActivity.confidence}

>
);
})()}

)}

);
}

```

# Bare React Native Workflow
For bare React Native projects, you must ensure that you have [installed and configured the `expo` package](https://docs.expo.dev/bare/installing-expo-modules/) before continuing.

### Add the package to your npm dependencies

```
npm install react-native-device-activity
```
#### Add permissions for Motion & Fitness tracking in your Info.plist:

```
NSMotionUsageDescription
This app uses motion data to track your activity.
```

### Configure for iOS

Run `npx pod-install` after installing the npm package.

## API Reference

### `startTracking(): Promise`
Starts real-time tracking of motion activity. Returns a promise that resolves to the initial motion state.

### `stopTracking(): Promise`
Stops the real-time motion tracking.

### `addMotionStateChangeListener(listener: (event: EventPayload) => void): Subscription`
Adds a listener to receive updates when the motion state changes.

### `getHistoricalData(startDate: Date, endDate: Date): Promise`
Fetches historical activity data for the given date range.

### `getPermissionStatusAsync(): Promise`
Checks the current motion activity permission status for iOS.

### `requestPermissionsAsyncAndroid(): Promise`
Requests motion activity permissions for Android devices.

### `isGooglePlayServicesAvailable: boolean`
Indicates whether Google Play Services are available on the current Android device.

### `checkMotionActivityAuthStatus(): Promise`
Checks the motion activity authorization status. Returns one of the following statuses:

- `NOT_DETERMINED`
- `RESTRICTED`
- `DENIED`
- `AUTHORIZED`

## License

This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details.

## Contributing

Contributions are welcome!