Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@dongminyu/react-native-step-counter

AndrewDongminYoo620MIT0.2.5TypeScript support: included

This library provides an interface for tracking the number of steps taken by the user in a React Native app.

activity-recognition-api, activity-recognition, android, core-motion, ios, motion-sensor-api, motion-sensor, pedometer-api, pedometer, react-native-step-counter, react-native, sensor-manager, step-counter-api, step-counter, step-detection-api, step-detection

readme

React-Native Step Counter Library

FOSSA Status

ko-fi

한국어 사용자는 Korean version.를 참조하십시오.

This library provides an interface for tracking the number of steps taken by the user in a React Native app. This package uses the StepCounter (or Custom accelerometer-based step-counter) Sensor API on Android and the Core Motion framework on iOS to count the steps. It's built using Turbo Module, a new module development architecture for React Native. I made this library compatible with both new and legacy architectures. (Because the turbo module is still in the experimental stage. so it is not widely used.)

Installation

# if you use pure npm (what a classic!),
npm install react-native-step-counter
# or if you prefer to use Yarn (I love it's parallel install feature),
yarn add react-native-step-counter
# or if you use pnpm (it's fast and efficient),
pnpm add react-native-step-counter

Native modules will automatically connect after React Native 0.60 version. So you don't need to link the native modules manually.

👣 if you are using the legacy architecture, you need to follow the guide below. otherwise, you can skip next step.

IF YOU WANT SEE A DEMO IN STANDALONE REACT-NATIVE APPLICATION, SEE WALKING_TRACKER EXAMPLE REPO

Thank you for your interest in my first NPM open source package! I've received a lot of issue reports on various issues, especially the react-native's NEW ARCHITECTURE backwards compatibility, and I've more or less finalized those issues by fixing the code structure across the board. We had generated an example folder from create-react-native-library's template and used it for this project, but due to the structure of that template, we found that the example folder contained a lot of code that was not suitable for reference in a working app, as it was part of the overall development process rather than a standalone application. For this reason, I'm going to independently manage the example application, which we had been developing informally as a sub-repository, as a repository named walking_tracker. I'd really appreciate it if you could take this into consideration.


Setup the New Architecture

  • Applying a new architecture to React Native applications (Common)

    1. React Native released the support for the New Architecture with the release 0.68.0.
    2. This is written with the expectation that you’re using the latest React Native release.
    3. You can find instructions on how to upgrade in the page upgrading to new versions.
    4. write all JS bridges with TypeScript (or Flow.js) because Codegen requires explicitly defined types. As you know, JavaScript is a dynamically typed language, so it is not possible to generate code.
    5. use hermes and flipper debugging tools.
      • Hermes is a new JavaScript engine optimized for running React Native apps on Android and iOS. enabled by default, and you want to use JSC, explicitly disable it.
      • Flipper is a new debugging and profiling tool for React Native.
  • Applying a new architecture to React Native iOS applications

    1_. set platform version to 12.4 or higher. ([minios_version_supported](https://github.com/facebook/react-native/blob/main/scripts/react_native_pods.rb#LL29-L31C4))

    - platform :ios, '11.0'
    + platform :ios, '12.4'
    # ↓ or you can use the variable of (react_native_pods.rb)
    + platform :ios, min_ios_version_supported

    2_. set NODEBINARY to .xcode.env file.

    echo 'export NODE_BINARY=$(command -v node)' > .xcode.env

    3. Fix an API Change in the AppDelegate.m file.

     - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
     {
     #if DEBUG
    -    return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
    +    return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
     #else
         return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
     #endif
     }

    4_. Rename all Objective-C(.m) files to Objective-C++ (.mm) _5. Make your AppDelegate conform to RCTAppDelegate

    • ios/StepCounterExample/AppDelegate.h

      - #import <React/RCTBridgeDelegate.h>
      + #import <RCTAppDelegate.h>
      #import <UIKit/UIKit.h>
      
      - @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate>
      + @interface AppDelegate : RCTAppDelegate
      
      - @property (nonatomic, strong) UIWindow *window;
      @end
    • ios/StepCounterExample/AppDelegate.mm

      #import "AppDelegate.h"
      #import <React/RCTBundleURLProvider.h>
      @implementation AppDelegate
      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
        self.moduleName = @"StepCounterExample";
        self.initialProps = @{};
        return [super application:application didFinishLaunchingWithOptions:launchOptions];
      }
      - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
      {
      #if DEBUG
        return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
      #else
        return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
      #endif
      }
      - (BOOL)concurrentRootEnabled
      {
        return true;
      }
      @end
    • Run pod install

      export RCT_NEW_ARCH_ENABLED=1
      cd ios && pod install
  • Applying a new architecture to React Native Android applications

    1. If your project has React Native later than v0.71.0, you already meet all the prerequisites to use the New Architecture on Android.
    2. You will only need to set newArchEnabled to true in your android/gradle.properties file.

If you prefer to read the official documentation, you can find it here.

ANDROID

3 uses-permission, 3 uses-feature

<!--  android/src/main/AndroidManifest.xml-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stepcounter">
  <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
  <uses-permission android:name="android.permission.BODY_SENSORS_BACKGROUND" />

  <uses-feature
    android:name="android.hardware.sensor.stepcounter"
    android:required="false" />
  <uses-feature
    android:name="android.hardware.sensor.accelerometer"
    android:required="true" />
</manifest>

iOS

set NSMotionUsageDescription

`xml plist <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"> <plist version="1.0"> ... <key>NSMotionUsageDescription</key> <string>We want to access your motion data to count your steps.</string> ... </plist>


## Interface

- `isStepCountingSupported()`: Promise<Record<string, boolean>>: method to check if the device has a feature related step counter or accelerometer.

  - One key for the response object is `granted`, whether the app user has granted this feature permission, and `supported` is whether the device supports this feature.
  - This NativeModule can apply algorithms to a raw accelerometer to extract walking event data without activity sensor privileges, regardless of this response, but it is not recommended. You must write a code that stops tracking sensor events if user denies read-permission - even if you can do that.

- `startStepCounterUpdate(start: Date, callBack: StepCountUpdateCallback)`: EmitterSubscription:

  - If the pedometer sensor is available and supported on the device, register it with the listener in the sensor manager, and return the step count event listener.
  - If the pedometer sensor is not supported by the device or is not available, register the accelerometer sensor with the listener, generate a accel event through an vector algorithm filter and receive it to the app.

- `stopStepCounterUpdate(): void`:

  - unregister registered listener from `sensorManager` and release it.

- `StepCountData`:

  - **Common Interface**

    - `steps`: This is a number property that indicates the number of steps taken by the user during the specified time period.
    - `startDate`: This is a number property that indicates the start date of the data in Unix timestamp format, measured in milliseconds.
    - `endDate`: This is a number property that indicates the end date of the data in Unix timestamp format, measured in milliseconds.
    - `distance`: This is a number property that indicates the distance in meters that the user has walked or run during the specified time period.
    - `counterType`: The name of the sensor used to count the number of steps. In iOS, only the `CMPedometer` is returned, and in Android, the `StepCounter` or `Accelerometer` is returned depending on the device state.

  - **iOS Only**
    - `floorsAscended`: This is a number property that indicates the number of floors the user has ascended during the specified time period. it can be nil if the device does not support this feature.
    - `floorsDescended`: This is a number property that indicates the number of floors the user has descended during the specified time period. it can be nil if the device does not support this feature.
    - `currentPace`: (iOS 9.0+) This is a number property that indicates the current pace of the user in meters per second.
    - `currentCadence`: (iOS 9.0+) This is a number property that indicates the current cadence of the user in steps per second.
    - `averageActivePace`: (iOS 10.0+) This is a number property that indicates the average pace of the user in meters per second.

## Usage

To use the Step Counter Library in your React Native app, follow these steps:

Import the library into your React Native app.

```typescript
import React, { useEffect, useState } from 'react';
import {
  isStepCountingSupported,
  parseStepData,
  startStepCounterUpdate,
  stopStepCounterUpdate,
} from 'react-native-step-counter';

Use the isStepCountingSupported method to check if the device has a step counter or accelerometer sensor.

const [supported, setSupported] = useState(false);
const [granted, setGranted] = useState(false);

async function askPermission() {
  isStepCountingSupported().then((result) => {
    console.debug('🚀 - isStepCountingSupported', result);
    setGranted(result.granted === true);
    setSupported(result.supported === true);
  });
}

Call the startStepCounterUpdate method to start the step counter service.

const [steps, setSteps] = useState(0);

async function startStepCounter() {
  startStepCounterUpdate(new Date(), (data) => {
    console.debug(parseStepData(data));
    setSteps(data.steps);
  });
}

Here's an example of a complete React component that uses the NativeStepCounter.

Link to Example Application: here

Change Log

See the Release Notes for a list of changes.

Contributing

See the Contributing Guide to learn how to contribute to the repository and the development workflow.

License

MIT


Made with create-react-native-library

FOSSA Status

changelog

Changelog

0.2.4 (2024-01-06)

Performance Improvements

  • ⬆️ upgrade cocoapods version (5fd2625)
  • upgrade npm dependencies (17de3ea)

0.2.3 (2023-10-15)

Chore Changes

  • Add Example App Link and Notices (walking_tracker)

0.2.2 (2023-10-14)

Bug Fixes

  • 🚨 RNStepCounter -> StepCounter #29 (279c1f5)
  • android: 🔥 remove unnecessary Gradle scripts (06e6dc9)
  • both: 🔥 remove related to Concurrent React (f7abb92)
  • ios: 🔥 remove dev-staged StepCounterExample (5ae2eec)
  • remove required toolchain java 8 (a24c40a)
  • step counter module backward compatibility (e114df6)

Performance Improvements

  • deps: ⬆️ updated all dependencies (23c6f23)

Documentation

  • doc: 📝 changed contribute, license details (7fbf7b7)

0.2.1 (2023-08-25)

Bug Fixes

  • 🚨 RNStepCounter -> StepCounter (2441e3e)
  • 🚨 RNStepCounter -> StepCounter #29 (df1f904)

0.2.0 (2023-08-20)

Features

  • upgrade react-native-reanimated from 2.17.0 to 3.2.0 (#23) (31aa2c8)

Bug Fixes

  • 🎨 redefine of namespace StepCounter (b8931ea)
  • 🚚 modified Android Code and Some Namespaces (5dcfa6d)
  • 🚨 updated eslint, editorconfig, git, prettier, nvm, watchman, commitlint, ts (a0a2bfb)
  • upgrade react-native from 0.71.6 to 0.71.7 (531f12c)
  • upgrade react-native-gesture-handler from 2.10.2 to 2.11.0 (27b5a5e)
  • upgrade react-native-gesture-handler from 2.9.0 to 2.10.0 (e66302e)
  • upgrade react-native-reanimated from 2.15.0 to 2.16.0 (07283ba)

Performance Improvements

  • ⚡️ updated iOS example application configuration (81561af)

Documentation

  • 📝 reformatted jsdoc generated api-document (4d52438)
  • example: 📝 jsdoc-theme updated (f7196b6)

0.1.16 (2023-04-11)

0.1.15 (2023-04-08)

0.1.14 (2023-04-08)

0.1.13 (2023-04-08)

Documentation

  • react: 📝 all codes are documented now (1ab93b0)

0.1.12 (2023-04-07)

Bug Fixes v0.1.12

  • example: 🔥 remove high vulnerability dependencies (1cfdc7e), closes #2

Performance Improvements v0.1.12

  • example: ➕ install react-native-gesture-handler from peer-dependencies (897547d)
  • example: ⬆️ upgraded all dependencies (react-native,trunk.io,node-version,gem,pods) (cbe50f3)

Documentation v0.1.12

  • example: 📝 updated document build system (d685238)

0.1.11 (2023-03-15)

Bug Fixes v0.1.11

  • ⬇️ iOS platform minimum target reduced, fix some typo of documents (bc1366a)

0.1.10 (2023-03-14)

Performance Improvements v0.1.10

  • iOS: ⬆️ all .m files in StepCounter folder should be renamed to .mm (983be85), closes #1

Documentation v0.1.10

  • react: ✏️ @yusungLEVIT reported typo fixed (09a3056), closes #8
  • react: 📝 wrote a detailed document on importing turbo-module (8d8800a), closes #10

0.1.9 (2023-03-09)

Features v0.1.9

  • android: ⚡️ Stabilize Android functionality (43dc577)

0.1.8 (2023-03-08)

Performance Improvements v0.1.8

  • android: ⚡️ implementation of the Lifecycle Event Listener (dfe9358)

0.1.7 (2023-03-06)

Performance Improvements v0.1.7

  • iOS: ⚡️ issue with the RCTCallableJSModule solved (eecdfd2), closes #2

0.1.6 (2023-03-06)

Bug Fixes

  • example: 🐛 xcode build was trying to locate an "extension point" (6f232f5)
  • iOS: 🚑️ implementation of the sendEvent method (de70534), closes #1

Features

  • iOS: ✨ step detector was also implemented in iOS to increase Step Counter efficiency (625889c)

0.1.5 (2023-03-04)

Bug Fixes v0.1.5

  • android: 🔨 accelerometer permission removed (4105c89)
  • android: 🔨 add some useful npm scripts (a525d69)

Features v0.1.5

  • example: ✨ write example codes and make some test-visible property (6297b95)

0.1.4 (2023-03-04)

Features v0.1.4

  • android: 🔨 move initialize service code for demo app (dfb11cf)

0.1.3 (2023-03-03)

Bug Fixes v0.1.3

  • android: 🏗️ make new-architecture non-require (f5442f5)
  • android: 🔨 gradle project problems solved (16ae7ea)
  • android: 🚑 accelerometer filter hotfix (317a1b9)
  • ios: 🏗️ make new-architecture non-require (c674a9c)
  • iOS: 🐛 iOS implemented codes Fixed (9d5cfb0)

Features v0.1.3

  • iOS: ✨ rewrite implementation iOS specific codes (78de416)
  • iOS: 🐛 event emitter is working now (cd3a1a9)

0.1.2 (2023-03-01)

Performance Improvements v0.1.2

  • 🔖 release new package version v0.1.1 (f56bf11)

0.1.1 (2023-03-01)

Documentation v0.1.1

  • app: 📝 modified README.md for the new interface (94a2434)
  • android: :memo: Completed documentation of Android codes.. (a74a952)
  • all: ✏️ move declaration JSDoc & write README (d9f24f4)
  • app: 📝 updated documents and example codes (7cfe93b)
  • example: 📝 edit typescript example app code (8672b2a)
  • package: 📝 edit README.md for deployment of package (17966ee)

New Feature

  • react: ✨ make main methods for module & configs release (d168036)
  • example: ✨ android implement starting (fd0e7ba)
  • example: ✨ feature interface is changing (d3f0329)
  • example: ⚡️ Users can see how far they've walked all day today. (f903321)
  • example: 🐛 Debug Configuration changed (4a83d28)
  • iOS: ✨ iOS CoreMotion Module Implemented (282ef50)
  • android: ✨ completed step-counter (f7b106f)
  • android: 🏗️ split accelerometer and step_counter (b35b1a3)

Bug Fixes v0.1.1

  • android: 🐛 accelerometer step counting fixing. (3e0c95c)
  • android: 🐛 accelerometer step counting fixing. (b33f27a)
  • android: 🔥 remove useless permission services (before stash) (308371f)
  • android: 🔥 remove useless permission services: resolved (e42089b)
  • android: 🚀 Debug behavior, but not satisfactory (7014b87)
  • android: 🐛 Service does not need to have react context:1 (4c56649)
  • android: 🐛 Service does not need to have react context:2 (f7b673a)
  • android: 🐛 Service does not need to have react context:3 (f1ea15b)
  • android: ⚡️ codes that implemented Service class are removed (541a70e)
  • android: 🐛 there was a time unit problems (ns, ms..). so fixed it (c93b840)
  • android: 🚑 sensor accuracy was too high (dd0193f)
  • android: 🚑️ too much high accuracy issue resolved (3cdda1d)

0.1.0 (2023-02-27)

Other Changes pre-release

  • all: 🎉 initial commit (100b61f)
  • all: 🔧 set configuration file with trunk (ae7c140)
  • all: ➕ update and install dependencies (4e205d3)
  • all: ♻️ simple format w/Trunk (786333f)
  • all: 🚨 disable some linters (342cb80)
  • react: 🍻 drunkenly wrote implementation TS code. (ac6af00)
  • all: 🔧 lint option setting changed (846d6b4)
  • android: 🧱 step-counter-module android frame (0b49162)
  • android: 🍻 step-counter-module android modules (79c7c23)
  • android: 🏗️ convert all .java to .kt (aa970e0)
  • android: 🏗️ finished migration to kotlin (c07575f)
  • android: 🩹 make it better kotlin grammar (5f21468)
  • android: 🚧 building android project architecture (311e6e8)
  • all: ➖ Remove a dependency (f0de273)
  • react: 🤡 implement methods listing (f5cd33e)
  • android: 🧱 android implement methods creating (6ae94ab)
  • all: 🔨 upgrade specific versions (fe73f2e)
  • android: 🚧 WIP: fixed manifest error (d23d2f9)
  • android: 🐛 WIP: android step-counter bug-fixed (cb274d3)
  • android: 🚧 WIP: re-implement permission service (1e32147)
  • all: 🚧 WIP: do not re-invent the wheel (2ee6670)
  • android: 🚧 WIP: PermissionService, StepCounterService fixing (201d65d)
  • android: ⚰️ remove non-safe non-null(!!) syntax (ce925d3)
  • android: 🚧 WIP: permission asking modal doesn't work. (cedac10)
  • android: 🐛 referenced by google-android-simple-pedometer (6fe674f)
  • android: 🐛 some critical error caused (a5c66c2)
  • android: ♻️ permission codes completed & add native-spec (cda5f48)
  • android: 🐛 Fixed android bugs (a893d25)
  • android: ⚰️ Remove dead code (209b83e)
  • react: 🥅 TypeScript Bridge error caught (2fc2506)
  • iOS: 🚸 iOS code implementation (3199acb)
  • android: 🐛 critical bugs resolved. (739cd91)
  • all: 🔧 git workflow and git ignore settings changed (b48debb)
  • iOS: 🐛 update node_modules and pods. (c50765b)
  • android: :wrench: fix some typo (hardware.sensor) (46dab76)
  • all: 🔥 disabled TypeScript beta version's experimental features (e04d261)
  • android: ✨ all logic of android implemented. (f8e7b73)
  • android: ⚡️ step counter delay configured (e639284)
  • android: ⚡️ improve android developing performance (7bd1785)
  • android: 🔥 moved permissions feature to library (35d804c)
  • android: 👷 add gradlePluginPortal repo (47cd8f2)
  • android: 🐛 all time units are changed to milliseconds (9f096cb)
  • app: 🔥 remove native permission codes (512399c)
  • iOS: 🔥 remove unused swift codes (b414ff9)
  • android: 🔧 add google service API (63c0cb1)

Code Refactoring pre-release

  • android: ♻️ deduplicate android codes & added javadoc & JSDoc (31bf912)
  • react: 🥅 TypeScript Bridge source changed (c4a7dbc)
  • android: 🐛 Fixed android native bugs (1a542e4)
  • android: 🐛 change visibility of methods (59a3016)
  • android: ✨ Android Accelerometer Event Convert (d017598)
  • all: 🏗️ configure architecture (ec76a6c)

Revert pre-release

  • android: 🐛 step detector codes revert to previous (c133326)