GithubHelp home page GithubHelp logo

aminoid / react-native-activity-recognition Goto Github PK

View Code? Open in Web Editor NEW
92.0 3.0 80.0 554 KB

React Native wrapper for the Activity Recognition API.

License: GNU General Public License v2.0

Java 61.59% JavaScript 16.23% Objective-C 19.45% Ruby 2.74%
react-native android ios activity-recognition

react-native-activity-recognition's Introduction

react-native-activity-recognition

npm version

React Native wrapper for the Android Activity Recognition API and CMMotionActivity. It attempts to determine the user activity such as driving, walking, running and cycling. Possible detected activities for android are listed here and for iOS are listed here.
Updated January 7th and tested with react-native v0.57.5

Installation

npm i -S react-native-activity-recognition

or with Yarn:

yarn add react-native-activity-recognition

Linking

Automatic

react-native link react-native-activity-recognition

IMPORTANT NOTE: You'll need to follow Step 4 for both iOS and Android of manual-linking

Manual

Make alterations to the following files in your project:

Android

  1. Add following lines to android/settings.gradle
...
include ':react-native-activity-recognition'
project(':react-native-activity-recognition').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-activity-recognition/android')
...
  1. Add the compile line to dependencies in android/app/build.gradle
...
dependencies {
    ...
    compile project(':react-native-activity-recognition')
    ...
}
  1. Add import and link the package in android/app/src/.../MainApplication.java
import com.xebia.activityrecognition.RNActivityRecognitionPackage;  // <--- add import

public class MainApplication extends Application implements ReactApplication {
    // ...
    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            // ...
            new RNActivityRecognitionPackage()                      // <--- add package
        );
    }
  1. Add activityrecognition service in android/app/src/main/AndroidManifest.xml
...
<application ...>
    ...
    <service android:name="com.xebia.activityrecognition.DetectionService"/>
    ...
</application>
...

iOS

  1. In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...>
  2. Go to node_modulesreact-native-activity-recognitionios ➜ select RNActivityRecognition.xcodeproj
  3. Add RNActivityRecognition.a to Build Phases -> Link Binary With Libraries
  4. Add NSMotionUsageDescription key to your Info.plist with strings describing why your app needs this permission

Usage

Class based implementation

import ActivityRecognition from 'react-native-activity-recognition'

...

// Subscribe to updates
this.unsubscribe = ActivityRecognition.subscribe(detectedActivities => {
  const mostProbableActivity = detectedActivities.sorted[0]
})

...

// Start activity detection
const detectionIntervalMillis = 1000
ActivityRecognition.start(detectionIntervalMillis)

...

// Stop activity detection and remove the listener
ActivityRecognition.stop()
this.unsubscribe()

Hooks based implementation

import ActivityRecognition from 'react-native-activity-recognition'

...

// Subscribe to updates on mount

  useEffect(() => {
    ActivityRecognition.subscribe(detectedActivities => {
      const mostProbableActivity = detectedActivities.sorted[0];
      console.log(mostProbableActivity);
    });

// Stop activity detection and remove the listener on unmount

    return ActivityRecognition.stop();
  });

...

// Start activity detection

const detectionIntervalMillis = 1000
ActivityRecognition.start(detectionIntervalMillis)

Android

detectedActivities is an object with keys for each detected activity, each of which have an integer percentage (0-100) indicating the likelihood that the user is performing this activity. For example:

{
  ON_FOOT: 8,
  IN_VEHICLE: 15,
  WALKING: 8,
  STILL: 77
}

Additionally, the detectedActivities.sorted getter is provided which returns an array of activities, ordered by their confidence value:

[
  { type: 'STILL', confidence: 77 },
  { type: 'IN_VEHICLE', confidence: 15 },
  { type: 'ON_FOOT', confidence: 8 },
  { type: 'WALKING', confidence: 8 },
]

Because the activities are sorted by confidence level, the first value will be the one with the highest probability Note that ON_FOOT and WALKING are related but won't always have the same value. I have never seen WALKING with a higher confidence than ON_FOOT, but it may happen that WALKING comes before ON_FOOT in the array if they have the same value.

The following activity types are supported:

  • IN_VEHICLE
  • ON_BICYCLE
  • ON_FOOT
  • RUNNING
  • WALKING
  • STILL
  • TILTING
  • UNKNOWN

iOS

detectedActivities is an object with key to the detected activity with a confidence value for that activity given by CMMotionActivityManager. For example:

{
    WALKING: 2
}

detectedActivities.sorted getter will return it in the form of an array.

[
    {type: "WALKING", confidence: 2}
]

The following activity types are supported:

  • RUNNING
  • WALKING
  • STATIONARY
  • AUTOMOTIVE
  • CYCLING
  • UNKNOWN

Credits / prior art

The following projects were very helpful in developing this library:

react-native-activity-recognition's People

Contributors

aminoid avatar cooperka avatar galziv avatar ghengeveld avatar gp2mv3 avatar markrickert avatar shorsher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-native-activity-recognition's Issues

Build Error on andoird

Hi Below is the error m facing when build on android
Duplicate class com.google.android.gms.measurement.AppMeasurement found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$ConditionalUserProperty found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$Event found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$EventInterceptor found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$OnEventListener found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$Param found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.measurement.AppMeasurement$UserProperty found in modules classes.jar (com.google.android.gms:play-services-measurement-impl:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.android.gms.tagmanager.zzcv found in modules classes.jar (com.google.android.gms:play-services-tagmanager-api:12.0.1) and classes.jar (com.google.android.gms:play-services-tagmanager-v4-impl:17.0.0)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics found in modules classes.jar (com.google.android.gms:play-services-measurement-api:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Event found in modules classes.jar (com.google.android.gms:play-services-measurement-api:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics$Param found in modules classes.jar (com.google.android.gms:play-services-measurement-api:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)
Duplicate class com.google.firebase.analytics.FirebaseAnalytics$UserProperty found in modules classes.jar (com.google.android.gms:play-services-measurement-api:17.2.0) and classes.jar (com.google.firebase:firebase-analytics-impl:12.0.1)

Can some on help me with this

Incompatible Types: Inferred type does not conform to upper bound(s)

Here is the version I'm using -

react: "^16.4.0"
react-native: "^0.52.2"
react-native-activity-recognition: "^3.2.0"

Issue

I kept getting the following error while building -

ActivityRecognizer.java:203 - Error: incompatible types - inferred type does not conform to upper bound(s)
ArrayList<DetectedActivity> updatedActivities = intent.getParcelableArrayListExtra(DetectionService.ACTIVITY_EXTRA);
                                                       ^
Inferred: DetectedActivity
Upper bound(s): Parcelable

Solution

I was able to fix this by changing line 203 to this -

ArrayList<DetectedActivity> updatedActivities = (ArrayList<DetectedActivity>) intent.getParcelableExtra(DetectionService.ACTIVITY_EXTRA);

Just wanted to report it here, so it helps someone.

🍻

GPL Licensing - Major issues

This component got flagged by our legal team stating that this comes under GPL license so technically we will have to make our app source available during distribution.

Is this true? just curious why this component is licensed under GPL and not MIT and other liberal license policy. Also, community should be made aware of this issue because I am sure lot of people use this to build their own mobile app and are not aware of it.

Background mode

Is it possible to make this service listen for activity changes and kick in foreground app on particular activity? Would be great if there wouldn't be any notifications while app is not running.

Something messed up!

I've been found this issue -> null is not an object (evaluating 'ActivityRecognitionNative.ANDROID_STILL'
reactnativeactrecg
)

error when build

Hi, i got error when build

: method does not override or implement a method from a supertype
@OverRide
^
Note: D:\projects\MyAct\node_modules\react-native-activity-recognition\android\s
rc\main\java\com\xebia\activityrecognition\DetectionService.java uses unchecked
or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
:react-native-activity-recognition:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-activity-recognition:compileReleaseJava
    WithJavac'.

Compilation failed; see the compiler error output for details.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug
    option to get more log output.

BUILD FAILED

who know how to solve this problem, thank you.

Is project still active/maintained?

Hi,

commits are pretty old and there are some open issues, is the project still alive?

I tried to use this with Expo, but with no luck, I got a "module not found" error just by running ActivityRecognition.subscribe

Documentation Android about Gradle

In the readme that contains this part using gradle 4 and 5 will have problems.

  1. Add the compile line to dependencies in android/app/build.gradle
...
dependencies {
    ...
    compile project(':react-native-activity-recognition')
    ...
}

On version 4:

WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and
'api'.
It will be removed in version 5.0 of the Android Gradle plugin.

Failure: Build failed

I'm getting this error, after the adding this library
screen shot 2018-08-13 at 13 30 12

If I'm changing in build.gradle compile 'com.google.android.gms:play-services:+' to `compile 'com.google.android.gms:play-services:15.0.1' I'm getting these errors:

screen shot 2018-08-13 at 13 33 13

Issue with ios Pod install

[!] There are multiple dependencies with different sources for RNActivityRecognition in Podfile:

  • RNActivityRecognition (from ../node_modules/react-native-activity-recognition/ios)
  • RNActivityRecognition (from ../node_modules/react-native-activity-recognition)

Add podspec for cocoapod

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

When I install the cocoapods of my project, let me know :

[!] The RNActivityRecognition pod failed to validate due to 1 error:
- ERROR | attributes: Missing required attribute homepage.
- WARN | source: The version should be included in the Git tag.
- WARN | description: The description is equal to the summary.

Indeed, it missing a RNActivityRecognition.podspec in the lib.
Here is the diff that solved my problem:

diff --git a/node_modules/react-native-activity-recognition/RNActivityRecognition.podspec b/node_modules/react-native-activity-recognition/RNActivityRecognition.podspec
new file mode 100644
index 0000000..f9b3123
--- /dev/null
+++ b/node_modules/react-native-activity-recognition/RNActivityRecognition.podspec
@@ -0,0 +1,18 @@
+require 'json'
+
+package = JSON.parse(File.read('./package.json'))
+
+Pod::Spec.new do |s|
+  s.name                = 'RNActivityRecognition'
+  s.version             = package['version']
+  s.summary             = package['description']
+  s.description         = package['description']
+  s.homepage            = package['homepage']
+  s.license             = package['license']
+  s.author              = package['author']
+  s.source              = { :git => "https://github.com/XebiaStudio/react-native-activity-recognition.git" }
+  s.platform            = :ios, "7.0"
+  s.source_files        = "ios/*.{h,m}"
+  s.preserve_paths      = "*.js"
+  s.dependency 'React-Core'
+end

This issue body was partially generated by patch-package.

Calling this.unsubscribe() twice

Should there be a guard in place where calling this.unsubscribe() when there are no active listeners on the object? Calling it twice generates an error and it would be nice if the module remembered the state and didn't call it if it wasn't necessary.

Having this guard in place would eliminate a lot of code in my project that's checking this.

Is there a way to get an initial activity?

Hi, great plugin thank you! i have a question. When you run it the plugin does not return anything unless there is a change which is fine, but then is it possible to know in which state I currently am before the change. as if the phone is stationary we would never get an activity. Thanks

Not able to detect an Activity

Hello @Aminoid!
I am currently struggling to get the activity recognition to work.
Starting the ActivityRecognition seems to work. I can see the native logs in adb logcat. But the subscribe callback is never called. Also the native logs in the ActivityDetectionBroadcastReceiver.onReceive method are never triggered. It looks like there is never an activity event fired.

I tried it in the Android Emulator as well as on a real device (Oneplus 5t).
Any ideas what the issue could be

My code looks like this:

function getUserActivity() {
  return new Promise((resolve, reject) => {
    const unsubscribe = ActivityRecognition.subscribe(detectedActivities => {
      const mostProbableActivity = detectedActivities.sorted[0];

      if (mostProbableActivity.confidence < CONFIDENCE_THRESHOLD) {
        reject(`getUserActivity: Confidence too low (${mostProbableActivity.confidence})`);
      } else {
        resolve(mapUserActivity(mostProbableActivity.type));
      }
    });

    // Start activity detection
    ActivityRecognition.start(DETECTION_INTERVAL).then(result => {
      console.log('ActivityRecognition started!');
    }).catch(error => {
      console.log('ActivityRecognition failed!', error);
    });

    ...
}

Setup:

  • "react-native": "0.59.5"
  • "react-native-activity-recognition": "^3.2.0"

I had version conflicts so I had to set the following in app/build.gradle

implementation(project(':react-native-activity-recognition')) {
    exclude group: "com.google.android.gms", module: 'play-services-places'
}

Do you have any idea what could cause these issues? Help is very welcome since I desperately need this functionality :)
Thanks!

Linking problems

Hello, after doing the automatic or manual linking and having done step 4, android studio gives me several errors before not present, while in xcode tells me data motion in missing.
At the moment my app takes gps coordinates using react-native-mauron85-background-geolocation and I wanted to use react-native-activity-recognition to know the activity performed.
Thanks in advance
schermata 2018-02-06 alle 16 58 29

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.