Acclerometer Sensor in Separate Thread

我的未来我决定 提交于 2019-11-26 16:38:30

问题


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. Please help. Things i have Tried: 1)

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()
   {}

Please suggest me any another approach or if i am doing something wrong in the above approaches.


回答1:


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.



来源:https://stackoverflow.com/questions/17513352/acclerometer-sensor-in-separate-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!