Java – Accelerometer sensor in a separate thread

Accelerometer sensor in a separate thread… here is a solution to the problem.

Accelerometer sensor in a separate thread

I’m saving data from the accelerometer sensor to the database, but I want to do it in a separate thread. I tried searching for it on the internet, but most use the same thread.

Something I’ve 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 registered it with the register listener.

Another method:
I implemented the Accelerometer class using the Runnable interface to initialize everything in the constructor, so my run() method is blank, but this method 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’d love to try another method or hear what I’m doing wrong in the above method.

Solution

First you need to use registerListener (SensorEventListener listener, Sensor sensor, int rate, Handler handler) and provide a handler to run on a background thread.

Create a HandlerThread, get its looper, and create a Handler to provide a looper.

This will enable you to receive callbacks on a background thread. When you’re done, make sure to remove the listener, and then call Looper.quit() to exit the thread.

Related Problems and Solutions