Accelerometer coding not working in all the phones - android

I am in the process of developing an Android music player which will do the the following actions once a shake action is detected. Actions: 1. Do Nothing 2. Play or Pause 3. Next Song 4. Previous Song
I have created a Service class for the shaking action and it is as follows.
public class Shaker extends Service implements SensorEventListener {
SharedPreferences sharedPreferences;
private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
private long mLastShakeTime;
private SensorManager sensorManager;
private static final String SHAKE_ACTION_PREFERENCE = "shake_action_preference";
private static final String SHAKE_THRESHOLD_PREFERENCE = "shake_threshold_preference";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
super.onCreate();
}
public void onDestroy() {
super.onDestroy();
sensorManager.unregisterListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
return START_STICKY;
}
public void onStart(Intent intent, int startId) {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double acceleration = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2) +
Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
Log.d("Acceleration", "Acceleration is " + acceleration + "m/s^2");
String threshold = sharedPreferences.getString(SHAKE_THRESHOLD_PREFERENCE, "medium");
float SHAKE_THRESHOLD;
if(threshold.equals("high"))
SHAKE_THRESHOLD = 40.5f;
else if(threshold.equals("low"))
SHAKE_THRESHOLD = 15.5f;
else
SHAKE_THRESHOLD = 25.5f;
if (acceleration > SHAKE_THRESHOLD) {
mLastShakeTime = curTime;
Log.d("Shake", "Shake, Rattle, and Roll");
String opt = sharedPreferences.getString(SHAKE_ACTION_PREFERENCE, "nothing");
Log.d("SharedPreference", opt);
Log.d("SharedPreference", threshold);
if(opt.equals("play")) {
MusicPlayer.playOrPause();
} else if(opt.equals("next")) {
MusicPlayer.next();
} else if(opt.equals("prev")) {
MusicPlayer.previous(getApplicationContext(), false);
}
}
}
}
}
}
But when I run the apk files in actual devices, the shaking function is working only on certain phones and not working for all the mobiles.
I have tried on different mobiles using same Android OS, but it is working in one and not working in the other.
I couldn't figure out why it is like this. Can anybody suggest a solution for this?

I had this problem. onSensorChanged method is called for any changes but in some devices, it is called more than once.It cause problem in logic of the code.
I solved this problem by adding a private static boolean variable. (It causes this method called once).Once this method executes,this variable becomes true.
#Override
public void onSensorChanged(SensorEvent event) {
if(!variable) {
variable=true;
...
...
variable=false;
}
}

Related

onAccuryChange always has 3 as value

I am trying to Learn How to detect shaking and tried to make App Detect Shaking
but onAccuryChange always on 3
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
switch(i){
case 2:
txt.setText("Shaked");
break;
case 3:
txt.setText("Default");
break;
default:
txt.setText("Nothing");
break;
}
}
always show "Default"
The TextView Already Have Text="No Actions Yet"
The mobile on Table but it shows "Default" once it run
so why it only gives 3 and how can i make it detect shaking ?
this is the Declaration
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=(TextView)findViewById(R.id.txt);
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
Hello Follow with below steps:
Create interface with name "AccelerometerListener":
public interface AccelerometerListener {
public void onAccelerationChanged(float x, float y, float z);
public void onShake(float force);
}
Create Class name as "MainAccelerometer.java", it is main activity:
public class MainAccelerometer extends Activity implements AccelerometerListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accelerometer_example_main);
// Check onResume Method to start accelerometer listener
}
public void onAccelerationChanged(float x, float y, float z) {
// TODO Auto-generated method stub
}
public void onShake(float force) {
// Do your stuff here
// Called when Motion Detected
Toast.makeText(getBaseContext(), "Motion detected",
Toast.LENGTH_SHORT).show();
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getBaseContext(), "onResume Accelerometer Started",
Toast.LENGTH_SHORT).show();
//Check device supported Accelerometer senssor or not
if (AccelerometerManager.isSupported(this)) {
//Start Accelerometer Listening
AccelerometerManager.startListening(this);
}
}
#Override
public void onStop() {
super.onStop();
//Check device supported Accelerometer senssor or not
if (AccelerometerManager.isListening()) {
//Start Accelerometer Listening
AccelerometerManager.stopListening();
Toast.makeText(getBaseContext(), "onStop Accelerometer Stoped",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("Sensor", "Service distroy");
//Check device supported Accelerometer senssor or not
if (AccelerometerManager.isListening()) {
//Start Accelerometer Listening
AccelerometerManager.stopListening();
Toast.makeText(getBaseContext(), "onDestroy Accelerometer Stoped",
Toast.LENGTH_SHORT).show();
}
}
}
Create Class name as "AccelerometerManager.java", which act as manager for managing accelerometer.
public class AccelerometerManager {
private static Context aContext=null;
/** Accuracy configuration */
private static float threshold = 15.0f;
private static int interval = 200;
private static Sensor sensor;
private static SensorManager sensorManager;
// you could use an OrientationListener array instead
// if you plans to use more than one listener
private static AccelerometerListener listener;
/** indicates whether or not Accelerometer Sensor is supported */
private static Boolean supported;
/** indicates whether or not Accelerometer Sensor is running */
private static boolean running = false;
/**
* Returns true if the manager is listening to orientation changes
*/
public static boolean isListening() {
return running;
}
/**
* Unregisters listeners
*/
public static void stopListening() {
running = false;
try {
if (sensorManager != null && sensorEventListener != null) {
sensorManager.unregisterListener(sensorEventListener);
}
} catch (Exception e) {}
}
/**
* Returns true if at least one Accelerometer sensor is available
*/
public static boolean isSupported(Context context) {
aContext = context;
if (supported == null) {
if (aContext != null) {
sensorManager = (SensorManager) aContext.
getSystemService(Context.SENSOR_SERVICE);
// Get all sensors in device
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
supported = new Boolean(sensors.size() > 0);
} else {
supported = Boolean.FALSE;
}
}
return supported;
}
/**
* Configure the listener for shaking
* #param threshold
* minimum acceleration variation for considering shaking
* #param interval
* minimum interval between to shake events
*/
public static void configure(int threshold, int interval) {
AccelerometerManager.threshold = threshold;
AccelerometerManager.interval = interval;
}
/**
* Registers a listener and start listening
* #param accelerometerListener
* callback for accelerometer events
*/
public static void startListening( AccelerometerListener accelerometerListener )
{
sensorManager = (SensorManager) aContext.
getSystemService(Context.SENSOR_SERVICE);
// Take all sensors in device
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
sensor = sensors.get(0);
// Register Accelerometer Listener
running = sensorManager.registerListener(
sensorEventListener, sensor,
SensorManager.SENSOR_DELAY_GAME);
listener = accelerometerListener;
}
}
/**
* Configures threshold and interval
* And registers a listener and start listening
* #param accelerometerListener
* callback for accelerometer events
* #param threshold
* minimum acceleration variation for considering shaking
* #param interval
* minimum interval between to shake events
*/
public static void startListening(
AccelerometerListener accelerometerListener,
int threshold, int interval) {
configure(threshold, interval);
startListening(accelerometerListener);
}
/**
* The listener that listen to events from the accelerometer listener
*/
private static SensorEventListener sensorEventListener =
new SensorEventListener() {
private long now = 0;
private long timeDiff = 0;
private long lastUpdate = 0;
private long lastShake = 0;
private float x = 0;
private float y = 0;
private float z = 0;
private float lastX = 0;
private float lastY = 0;
private float lastZ = 0;
private float force = 0;
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
// use the event timestamp as reference
// so the manager precision won't depends
// on the AccelerometerListener implementation
// processing time
now = event.timestamp;
x = event.values[0];
y = event.values[1];
z = event.values[2];
// if not interesting in shake events
// just remove the whole if then else block
if (lastUpdate == 0) {
lastUpdate = now;
lastShake = now;
lastX = x;
lastY = y;
lastZ = z;
Toast.makeText(aContext,"No Motion detected",
Toast.LENGTH_SHORT).show();
} else {
timeDiff = now - lastUpdate;
if (timeDiff > 0) {
/*force = Math.abs(x + y + z - lastX - lastY - lastZ)
/ timeDiff;*/
force = Math.abs(x + y + z - lastX - lastY - lastZ);
if (Float.compare(force, threshold) >0 ) {
//Toast.makeText(Accelerometer.getContext(),
//(now-lastShake)+" >= "+interval, 1000).show();
if (now - lastShake >= interval) {
// trigger shake event
listener.onShake(force);
}
else
{
Toast.makeText(aContext,"No Motion detected",
Toast.LENGTH_SHORT).show();
}
lastShake = now;
}
lastX = x;
lastY = y;
lastZ = z;
lastUpdate = now;
}
else
{
Toast.makeText(aContext,"No Motion detected", Toast.LENGTH_SHORT).show();
}
}
// trigger change event
listener.onAccelerationChanged(x, y, z);
}
};
}
In Manifest, do a entry:
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Create layout file name as "accelerometer_example_main.xml":
<RelativeLayout xmlns:android="<a class="vglnk" href="http://schemas.android.com/apk/res/android" rel="nofollow"><span>http</span><span>://</span><span>schemas</span><span>.</span><span>android</span><span>.</span><span>com</span><span>/</span><span>apk</span><span>/</span><span>res</span><span>/</span><span>android</span></a>"
xmlns:tools="<a class="vglnk" href="http://schemas.android.com/tools" rel="nofollow"><span>http</span><span>://</span><span>schemas</span><span>.</span><span>android</span><span>.</span><span>com</span><span>/</span><span>tools</span></a>"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainAccelerometer" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Shake / Tilt Your Phone To Get Accelerometer Motion Alerts" />
</RelativeLayout>
Happy Coding.

Android Sensor Hand Wave Detection

I'm trying to implement a sensor that can detect a hand wave. I found an example that can do hand hover, but not hand wave.
The following code I used is from
How to controlandroid proximity sensor?
public class AndroidProximitySensorActivity extends Activity {
TextView ProximitySensor, ProximityMax, ProximityReading;
SensorManager mySensorManager;
Sensor myProximitySensor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ProximitySensor = (TextView)findViewById(R.id.proximitySensor);
ProximityMax = (TextView)findViewById(R.id.proximityMax);
ProximityReading = (TextView)findViewById(R.id.proximityReading);
mySensorManager = (SensorManager)getSystemService(
Context.SENSOR_SERVICE);
myProximitySensor = mySensorManager.getDefaultSensor(
Sensor.TYPE_PROXIMITY);
if (myProximitySensor == null){
ProximitySensor.setText("No Proximity Sensor!");
}else{
ProximitySensor.setText(myProximitySensor.getName());
ProximityMax.setText("Maximum Range: "
+ String.valueOf(myProximitySensor.getMaximumRange()));
mySensorManager.registerListener(proximitySensorEventListener,
myProximitySensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
SensorEventListener proximitySensorEventListener
= new SensorEventListener(){
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
ProximityReading.setText("Proximity Sensor Reading:"
+ String.valueOf(event.values[0]));
}
}
};
}
In the above code, when the event.values[0] = 0, it means my hand is hover at the sensor. However, I need my sensor to detect a hand wave. How do I do it? Thanks.
Please try this code:
private SensorManager sensorManager;
private Sensor proximitySensor;
private final int WAVE_TIME = 2000;
private final int WAVE_NEEDED_MOVEMENTS = 3;
private long lastWaveTime = 0;
private float lastSensorValue;
private float maxSensorValue;
private float numOfMovements = 0;
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
sensorManager.registerListener(proximitySensorEventListener, proximitySensor,SensorManager.SENSOR_DELAY_NORMAL);
maxSensorValue = proximitySensor.getMaximumRange();
}
#Override
public void onSensorChanged(SensorEvent event) {
if(lastWaveTime + WAVE_TIME > System.currentTimeMillis()) {
System.out.println("Reset timing...");
lastWaveTime = System.currentTimeMillis();
numOfMovements = 0;
lastSensorValue = event.values[0];
} else if((event.values[0] != maxSensorValue && lastSensorValue == maxSensorValue) || (event.values[0] == maxSensorValue && lastSensorValue != maxSensorValue) ){
numOfMovements++;
if(numOfMovements == WAVE_NEEDED_MOVEMENTS) {
System.out.println("WAVE EVENT");
lastWaveTime = System.currentTimeMillis();
numOfMovements = 0;
}
}
}

Android Sensor Shake in the background

I'm trying to follow a tutorial about sensor. It works fine with an activity. However, I want this to work in the background when the phone is locked. What's the best way to do that?
Here's the link to the tutorial
http://jasonmcreynolds.com/?p=388
ShakeDetector class
public class ShakeDetector implements SensorEventListener {
/*
* The gForce that is necessary to register as shake.
* Must be greater than 1G (one earth gravity unit).
* You can install "G-Force", by Blake La Pierre
* from the Google Play Store and run it to see how
* many G's it takes to register a shake
*/
private static final float SHAKE_THRESHOLD_GRAVITY = 2.7F;
private static final int SHAKE_SLOP_TIME_MS = 500;
private static final int SHAKE_COUNT_RESET_TIME_MS = 3000;
private OnShakeListener mListener;
private long mShakeTimestamp;
private int mShakeCount;
public void setOnShakeListener(OnShakeListener listener) {
this.mListener = listener;
}
public interface OnShakeListener {
public void onShake(int count);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// ignore
}
#Override
public void onSensorChanged(SensorEvent event) {
if (mListener != null) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
float gX = x / SensorManager.GRAVITY_EARTH;
float gY = y / SensorManager.GRAVITY_EARTH;
float gZ = z / SensorManager.GRAVITY_EARTH;
// gForce will be close to 1 when there is no movement.
Float f = new Float(gX * gX + gY * gY + gZ * gZ);
Double d = Math.sqrt(f.doubleValue());
float gForce = d.floatValue();
if (gForce > SHAKE_THRESHOLD_GRAVITY) {
final long now = System.currentTimeMillis();
// ignore shake events too close to each other (500ms)
if (mShakeTimestamp + SHAKE_SLOP_TIME_MS > now) {
return;
}
// reset the shake count after 3 seconds of no shakes
if (mShakeTimestamp + SHAKE_COUNT_RESET_TIME_MS < now) {
mShakeCount = 0;
}
mShakeTimestamp = now;
mShakeCount++;
mListener.onShake(mShakeCount);
}
}
}
}
Main Acitivty
public class MainActivity extends AppCompatActivity {
// The following are used for the shake detection
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, ShakeService.class);
startService(intent);
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
#Override
public void onShake(int count) {
Toast.makeText(getApplicationContext(), "shake",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
// Add the following line to register the Session Manager Listener onResume
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onPause() {
// Add the following line to unregister the Sensor Manager onPause
mSensorManager.unregisterListener(mShakeDetector);
super.onPause();
}
}
Shake Service
public class ShakeService extends Service {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
public ShakeService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
#Override
public void onShake(int count) {
Intent i = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
getApplicationContext().startActivity(i);
}
});
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onDestroy() {
mSensorManager.unregisterListener(mShakeDetector);
super.onDestroy();
}
}
You need to use Threads, AsyncTask is the easiest to implement. Take a look at this, if that's what you're looking for: https://developer.android.com/guide/components/processes-and-threads.html
here is a goog example
http://joerichard.net/android/android-shake-detector/
Steps: create a sensor event listener and then get from Activity. Create a service that fires when shake event happen.

SensorEventListener temporarily not working

I've implemented SensorEventListener in my MainActivity, and it works quite well, i'd even say most of the time very well.
But weirdly, sometimes it completely stops working, I need to shake it in every direction for 5-10 seconds and it's magically back on.
It seems to be after the phone as idle/asleep for a long time.
I did implemented the register/unregister on onResume/onPause.
Here is my code, mostly coming from stackoverflow:
SensorManager sensorManager;
private float accel; // acceleration apart from gravity
private float accelCurrent; // current acceleration including gravity
private float accelLast; // last acceleration including gravity
private static final float SHAKE_THRESHOLD = 12.f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initSensor();
}
private void initSensor() {
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
registerSensor();
}
private void registerSensor() {
HandlerThread handlerThread = new HandlerThread(HANDLER_THREAD_NAME_SENSOR);
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL, handler);
accel = 0.00f;
accelCurrent = SensorManager.GRAVITY_EARTH;
accelLast = SensorManager.GRAVITY_EARTH;
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
protected void onResume() {
super.onResume();
registerSensor();
}
#Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
accelLast = accelCurrent;
accelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
float delta = accelCurrent - accelLast;
accel = accel * 0.9f + delta; // perform low-cut filter
//Log.d(TAG, ">>> ALL shake accel = "+ accel);
if (accel > SHAKE_THRESHOLD) {
Log.d(TAG, "shake accel = "+ accel);
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do stuffs in the UI
}
});
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Nothing do to here
}
It was fixed by changing the sensor delay to SensorManager.SENSOR_DELAY_FASTEST;
The registration now looks like :
// Global
private static final String HANDLER_THREAD_NAME_SENSOR = "sensorThread";
// ...Registration
HandlerThread handlerThread = new HandlerThread(HANDLER_THREAD_NAME_SENSOR);
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST,
handler);

How to use get Android's acceleration with specified times?

I am a java newer,
I want to get, for example, 10 different values of my phone's acceleration,
and get an average value from them.
But I can only find answers for continued data, or only one data.
Now I can get one data and display it on my screen.
Can I use for loop to calculate for 10 times?
Thank you.
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
aAngle = event.values[0];
bAngle = event.values[1];
}
private Button.OnClickListener listener = new Button.OnClickListener() {
switch(viewMode){
case VIEW_MODE_1:
title.setText(Double.toString(aAngle) + " " + Double.toString(bAngle));
break;}
I've tried to cast a for loop in the OnSensorChanged method, but it didn't work at all.
I tried to do this, but it seems to have a runtime error.
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0 && sensors.size() <= 10) {
sensorManager.registerListener(this,sensors.get(count),SensorManager.SENSOR_DELAY_NORMAL);
count ++;
}
also, I create two list to save the result every time when my angle is changed.
for(int i = 0; i < aAngleList.size(); i++){
double aAngleTotal = 0;
double bAngleTotal = 0;
aAngleTotal += aAngleList.get(i);
bAngleTotal += bAngleList.get(i);
aAngleAverage = aAngleTotal / aAngleList.size();
bAngleAverage = bAngleTotal / bAngleList.size();
}
public void onSensorChanged(SensorEvent event) {
aAngleList.add(aAngle);
bAngleList.add(bAngle);
}
the for loop is in onResume, right under the if (sensors...)
onSensorChanged is fired everytime your sensor gets a new reading. you can place a counter for ten changes. keep track of values in a list,hashmap and aggregate them.
public class SensorActivity extends Activity, implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
private int count=0;
private List<String> eventX=new ArrayList<String>();
public SensorActivity() {
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
eventX.add(event.getValueMethodwhateverItis());
count++;
if (count=10){
//aggregate from list do anything you want.;
}
}
}

Categories

Resources