Using the phone accelerometer it is possible to handle shake events.
The problem is of course to decide if the stream of values represents a shake.
The Shake code module finds shake patterns and raises a ShakeEvent when such occurs.
Using the Shake module is simple. Add Shake.bas code module to your project (Project - Add Existing module) and then you should add code similar to:
You should add a reference to the Phone library. This code also uses a SoundPool object to play a sound. So the Audio library is also required here.
Shake module also supports recording the sensors data to a CSV file.
This is useful for understanding the required pattern.
By recording the data and creating the following Excel graph:
I decided to use the change in the X acceleration (derivative line).
The attached program plays a sounds and changes the screen color when you shake the phone. It is not always easy to make a shake event. Playing a sound is a good cue for the user that the shake was "successful".
To prevent repetitive shake events, shakes are disabled for 1.5 seconds after a shake event.
The problem is of course to decide if the stream of values represents a shake.
The Shake code module finds shake patterns and raises a ShakeEvent when such occurs.
Using the Shake module is simple. Add Shake.bas code module to your project (Project - Add Existing module) and then you should add code similar to:
B4X:
Sub Process_Globals
Dim sensor As PhoneSensors
Dim sounds As SoundPool
Dim bounceId As Int
End Sub
Sub Globals
End Sub
Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
sensor.Initialize(sensor.TYPE_ACCELEROMETER)
Shake.CallBackActivity = "Main" 'Set the activity that handles the Shake event
sounds.Initialize(1)
bounceId = sounds.Load(File.DirAssets, "break.mp3")
End If
End Sub
Sub Activity_Resume
sensor.StartListening("sensor")
End Sub
Sub Activity_Pause (UserClosed As Boolean)
sensor.StopListening
End Sub
'Delegate the event handling to the Shake module
Sub sensor_SensorChanged (Values() As Float)
Shake.HandleSensorEvent(Values)
End Sub
'This event is raised when a shake is detected
Sub ShakeEvent
Activity.Color = Colors.RGB(Rnd(0, 255), Rnd(0, 255), Rnd(0, 255))
sounds.Play(bounceId, 1, 1, 1, 0, 1)
End Sub
Shake module also supports recording the sensors data to a CSV file.
This is useful for understanding the required pattern.
By recording the data and creating the following Excel graph:
I decided to use the change in the X acceleration (derivative line).
The attached program plays a sounds and changes the screen color when you shake the phone. It is not always easy to make a shake event. Playing a sound is a good cue for the user that the shake was "successful".
To prevent repetitive shake events, shakes are disabled for 1.5 seconds after a shake event.