I am saving data from Accelerometer Sensor to Database, but I want to do it in a separate thread. I tried to search it on Internet but most of them uses the same thread.
Things I have tried:
SenSorEventListener sel;
Thread A=new Thread(){
public void run()
{
sel=new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
double Acceleration,x,y,z;
x=event.values[0];
y=event.values[2];
z=event.values[2];
Acceleration=Math.sqrt(x*x+y*y+z*z);
db.addAccel(Acceleration);
Log.d("MESSAGE","SAVED");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
}
};
A.start();
try {
A.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sm.registerListener(sel,s,1000000);
}
I took a SensorEventListener, initialized it in a new Thread and then registering it with register listener.
Another approach: I implemented Accelerometer class using Runnable interface, initialized everything in Constructor, so my run() method is blank, but this approach doesn't create a new Thread.
Accelerometer(Context con,Database d)
{
sm=(SensorManager)con.getSystemService(Context.SENSOR_SERVICE);
s=sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this,s,1000000);
db=d;
}
void run()
{}
I would be happy to try another approach, or to hear I am doing something wrong in the above approaches.
First you need to use registerListener(SensorEventListener listener, Sensor sensor, int rate, Handler handler) and supply a Handler that is running on a background thread.
Create a HandlerThread, get its Looper, create a Handler supplying the looper.
This will let you receive the callbacks on the background thread. When finished ensure you remove the listener and then call Looper.quit(), to exit the thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With