Giter Club home page Giter Club logo

cordova-plugin-shake's Introduction

Shake Gesture Detection for Cordova npm version

Apache Cordova / PhoneGap Plugin to detect when a physical device performs a shake gesture.

For iOS, the plugin uses the native shake detection. Fo all other platforms, it is based on a standalone JavaScript implementation I wrote last year (gist).

Install

Requires Cordova v5.0.0 or above.

Latest published version on npm

cordova plugin add cordova-plugin-shake

Latest version from GitHub

cordova plugin add https://github.com/leecrossley/cordova-plugin-shake.git

Usage

You do not need to reference any JavaScript, the Cordova plugin architecture will add a shake object to your root automatically when you build.

NB: For non-iOS platforms, there is no native component to this plugin but it depends on the device motion plugin (added when this plugin is added).

Example

var onShake = function () {
  // Fired when a shake is detected
};

var onError = function () {
  // Fired when there is an accelerometer error (optional)
};

// Start watching for shake gestures and call "onShake"
// with a shake sensitivity of 40 (optional, default 30)
shake.startWatch(onShake, 40 /*, onError */);

// Stop watching for shake gestures
shake.stopWatch();

License

MIT License

cordova-plugin-shake's People

Contributors

chatgris avatar leecrossley avatar ludufre avatar luissilvaos avatar patrickfuerst avatar ritzlgrmft avatar vincentpuget 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  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-shake's Issues

onShake() not firing on iOS

I have used this code for my University classes for the past few years. This weekend, I have recompiled and tested Android 5.1.1 on Samsung Galaxy and iOS 10.3.3 (iPhone 6) and iOS 11.1.2 on an iPad Air.

onShake doesn't fire on either iOS device. Works fine on Android.
Using build.phonegap.com with the following key items from index.xml:

`   <plugin name="cordova-plugin-shake"                         spec="0.6.0" />
    <plugin name="cordova-plugin-device-motion"                 spec="2.0.0" />
    <plugin name="cordova-plugin-statusbar"                     spec="2.3.0" />
    <plugin name="cordova-plugin-whitelist"                     spec="1.2.2" />

    <preference name = "phonegap-version"                value = "cli-6.5.0" />`

I have also tested with
cli-6.4.0
cli-6.3.1
and I observe no change (works on android, not iOS)

The index.js code is:

`"use strict;"

/*===========================*/
/* put global variables here */
/*===========================*/

var bodyNode;		// body node in the DOM tree to set the background color
var buttonNode;		// listen for clicks (web) and touches (mobile)
var shakeNode;		// if mobiel, show user shaking is an option
var labelNode;		// the element in the DOM we will set to "rgb(10,23,45);"

/* wait until all phonegap/cordova is loaded then call onDeviceReady*/
document.addEventListener("deviceready", onDeviceReady, false);

/*====================*/
/* put functions here */
/*====================*/

function onDeviceReady(){

	bodyNode 			= document.getElementById('bodyElement');
	buttonNode			= document.getElementById('buttonElement');
	shakeNode			= document.getElementById('shakeElement');
	rgbNode 			= document.getElementById('rgbElement');

	buttonNode.onclick 	= changeColor; // for browser mouse clicks

	// on webapp, shake will be undefined, but it will be on mobile...
	// https://github.com/leecrossley/cordova-plugin-shake
	// place <plugin name="cordova-plugin-shake"/> in config.xml

	if (typeof shake !== 'undefined') {
		// watch for device shaking, if we hit the unit threshold, call onShake
		shakeNode.innerHTML = "or you can shake me!"
		shake.startWatch(onShake, 30, onShakeError);
	}

	changeColor();	

}

var onShake = function() {
	alert("onShake event");
	changeColor();
}

var onShakeError = function() {
	alert("onShakeError occurred");
}

function changeColor() {
	var r = randomColorComponent();
	var g = randomColorComponent();
	var b = randomColorComponent();

	var rgbString = "rgb(" + r + "," + g + "," + b + ")";

	rgbNode.innerHTML = rgbString;
	bodyNode.style.backgroundColor = rgbString;
}

function randomColorComponent() {
	return Math.floor(Math.random() * 256); //make a random int from 0 - 255
}
`

onDeviceReady() is being called as this line is functioning
shakeNode.innerHTML = "or you can shake me!"
Developer debugging via safari and USB cable shows:

  • No console warnings or errors
  • No CSP warnings or errors.
  • shake is defined
  • calling onShake() works in the debugger console (alert is called, color changes).

clicking the "press me" button calls changeColor() and color changes
See below

image

Questions

  1. What am I missing? This is working on my Android device.
  2. Is there some debugging tips I can try?
  3. Do I need the cordova-plugin-device-motion ?

(oh, and the phonegap build logs are clean too)

cordova-plugin-shake working on Android, but not iOS

1. What is the context?

I have built an Ionic 5/Capacitor/React app where I have added the cordova-plugin-shake through capacitor by following the Ionic Docs.

2. What does the code look like?

import React from "react";
import { Subscription } from "rxjs";
import { Shake } from "@ionic-native/shake";

// other stuff...

class MagicEightBall extends React.Component {

  shakeSubscription: Subscription = new Subscription();

  ionViewWillEnter() {
    console.log("Magic8Ball ionViewWillEnter()");
    this.shakeSubscription = Shake.startWatch().subscribe(() => this.onShake());
  }

  onShake() {
    // process shake
  }

}

3. What is the problem?

This works perfectly on Android, but it does not work on iOS. I have made sure the Cordova dependencies have been installed through pod install and that seems to have gone fine. Have been looking for an answer for quite some time now, but I cannot seem to fix it. It has been tested on an iPhone 6S with the latest iOS version as well as on an iPad. The Android version has been run on a Xiaomi Mi 9 and it has worked since the start. Just cannot get it running on iOS.

Any ideas?

iOS shake detection doesn't work

We recently updated to the latest cordova for iOS 6.2.0.

This plugin injects the motionEnded function in to the MainViewController.m file but it looks like nothing from the MainViewController.mfile is called.

Does someone experience the same behaviour?

shake event not firing state change after state change shake is working in ionic can you please help me

this is my code:

if(!$window.localStorage.Shakecount){
$window.localStorage.setItem('Shakecount', 1);
}
if(!$window.localStorage.themecolor){
$window.localStorage.setItem('themecolor', "awesome_blue");
}

$scope.themecolor = $window.localStorage.getItem("themecolor");
var indexcount = $window.localStorage.getItem("Shakecount");



var onShake =  function() {
    alert("afterloadedok");
    switch(indexcount){
        case "1":
            var index = parseInt(indexcount) + 1;
            $scope.themecolor = "royal_pink";
            alert(index);
            alert($scope.themecolor);
            $window.localStorage.setItem('Shakecount', index);
            $window.localStorage.setItem('themecolor', $scope.themecolor);
            shake.stopWatch();
            $window.location.reload();
            break;
        case "2":
            var index = 1;
            $scope.themecolor = "awesome_blue";
            alert(index);
            alert($scope.themecolor);
            $window.localStorage.setItem('Shakecount', index);
            $window.localStorage.setItem('themecolor', $scope.themecolor);
            shake.stopWatch();
            $window.location.reload();
            break;

        default:
            index = 1;
            $scope.themecolor = "awesome_blue";
            alert(indexcount);
            alert($scope.themecolor);
            $window.localStorage.setItem('Shakecount', index);
            $window.localStorage.setItem('themecolor', $scope.themecolor);
            shake.stopWatch();
            $window.location.reload();
            break;
    }
}

if(window.shake) shake.startWatch(onShake,40);

Doesn't work in iOs simulator

Coffescript:

Meteor.startup ->
  if Meteor.isCordova
    alert('here')
    shake.startWatch( ->
      alert('shake')
    )

In the simulator I see "here" and simulate a shake gesture and but never see "shake".

Thanks!

Uncaught TypeError...

D/CordovaLog(16667): file:///android_asset/www/plugins/uk.co.ilee.shake/www/shake.js: Line 15 : Uncaught TypeError: Cannot call method 'watchAcceleration' of undefined

Phonegap 3.4.0
Android 4.4.2
Nexus 5

Address the comments on the gist?

Hi Lee,

I know you may not monitor your gists, but the gist for Shake.js has a lot of comments, some of which seem to bring up relevant issues:

  • calling Math.abs with two parameters
  • callback stops triggering after first shake
  • "the math is just plain wrong" and the fork was mentioned on StackOverflow. Issues it claims to fix:
    • The maths was a bit weird. It did not actually measure the difference in acceleration. (Math.abs() only takes one argument.)
    • It was not very configurable per usage
    • Error handling did nothing.
    • The function called on the shake event received no information about the gesture.
    • The same function only fired once since it was cleared after a shake event occurred.
    • You could only do one thing upon a shake. (This version allows multiple instances, but you'll probably only want to have one watching for shakes at any given time.)

Can't find variable: shake

Hi,

I'm using PhoneGap (Cordova 5.0.0) with Ionic 1.0.0, a mobile development framework based on Angular.

Your docs say a 'shake' object is added to the root. However, as soon as I try to read that object my JS bugs out saying:

Can't find variable: shake

I have added your plugin though cordova plugin add cordova-plugin-shake and rebuilt my project.

This is my full plug-in list:

com.ionic.keyboard 1.0.4 "Keyboard"
com.phonegap.plugins.PushPlugin 2.4.0 "PushPlugin"
cordova-plugin-shake 0.5.1 "Shake Gesture Detection"
org.apache.cordova.console 0.2.13 "Console"
org.apache.cordova.device 0.3.0 "Device"
org.apache.cordova.device-motion 0.2.11 "Device Motion"

FWIW, one warning npm gave me when installing your plug-in was:

WARNING: org.apache.cordova.device-motion has been renamed to cordova-plugin-device-motion. You may not be getting the latest version! We suggest you `cordova plugin rm org.apache.cordova.device-motion` and `cordova plugin add cordova-plugin-device-motion`.

Plugin not Working Cordova 3.4

Hello,
The plugin is not working on my android device(Galaxy S4).

I used the Code provided in the readme file of the Plugin,but the shake event never gets fired.What are my doing wrong?.Thanks

onShake() not working on Android 12

Tested my code on Nexus 6P running on Android 8.x.x, and shake triggers perfectly. On my Google Pixel 3XL running on Android 12, onShake event is not triggered. Shake functionality is verified to be working on the Pixel (tested through another app).

`var shakeNode;

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
shakeNode = document.getElementById('shakeId');
if (typeof shake !== 'undefined') {
shakeNode.innerHTML = "ready!"
shake.startWatch(onShake, 30, onShakeError);
}
}

var onShake = function() {
alert("Shake triggered.");
}

var onShakeError = function () {
alert("ShakeError occurred.")
}`

Background mode not working

Hi there,

Can someone help me with the background mode of the shake option enabled? any example code would be helpful,

Scenario 1: Works fine: Foreground
Launch App
Shake the mobile
Shake is triggered

Scenario 2: Does not work: Background when the app is minimized

   Launch App
   Shake the mobile
   Shake is not triggered

Scenario 3: Does not work: Background when the app is minimized and phone locked

    Launch App
    Shake the mobile
    Shake is not triggered

Please advise me, Thanks in advance.

Shake event is fired twice every time it fires

Shake event is fired twice every time it fires. Even increasing the sensitivity I was not able to reduce the number of times the shake method is called.

Whenever I shake my iPhone 5 iOS 7.2.2 the callback is called twice.

shake finished

is there a call back for when the shake has finished?

winphone have a strange behavior

hi @leecrossley
awesome plugin
Android and iOS are all work done
but in winphone when I use

shake.startWatch(onShake, 40 , onError );

it will trigger the onError function and have a wrong message "No Result"

On shake end

Hi

I wanted to ask is t possible to detect when a shake has ended ver when one has started?

Class not found

Hello,

Could you please help me?
The line bellow returns the error "Class not found":
What could be?

shake.startWatch(
  function () {
    logger.error('device is being shaken');
  }, 40, function (err) {
    logger.error('device on error: ' + JSON.stringify(err));
  });

Angular Animation not Working

Hello,

I have a problem using this plugin in my Ionic Application for an iOS App.

I want a transform-animation ( transform: 'rotateY(180deg)' ) to start when device is shaken.
The animation works perfectly when triggering it by a click or by itself after waiting like 2 seconds.

I have a method, which changes the variable to trigger the animation:

@Component({
...
animations: [
    trigger('state', [
      state('active', style({
        transform: 'rotateY(180deg)'
      })),
      transition('* => active', animate('400ms ease'))
    ])
  ],
...
})
export class MyComponent {

  constructor( private shake: Shake, private platform: Platform ){
    if( this.platform.ready() === 'cordova' ){
      this.shake.startWatch(40).subscribe( () => this.toggleState() );
    }
  }

  toggleState() {
    this.state = this.state === 'inactive' ? 'active' : 'inactive';
  }

}

So by shaking my iPhone I get correct outputs in the Xcode debug console and the state-variable changes from inactive to active, but the rotateY-animation will not be shown.
By clicking a button with (click)="toggleState()" property, everything works perfectly.

Can anybody help me?

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.