Is there a way to get values from a sensor while the main thred is paused?
GOAL: I need to register the light sensor, the main thread must wait 10 seconds and then i must get an average value after these 10 seconds.
PROBLEM: I must wait in the main thread, so if i do a while or a sleep, the sensor doesn't get any value
WHAT I TRIED: I tried to register the sensor in another thread or asynctask, but nothing happened if i pause the main thread for 10 seconds (i tried with a sleep, with an handler, with a while and with a join). A user suggested me to use a Handler and the onPause/onResume. My actual code is this, but i still don't get anything while the main thread is waiting:
public class MyActivity
{
private Lux light; //Lux implements SensorEventListener
private SensorManager mSensorManager;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.listeners);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
light=new Lux();
onPause();
}
@Override
protected void onResume()
{
mSensorManager.unregisterListener(light, mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT));
light.getAverage();
super.onResume();
}
@Override
protected void onPause()
{
super.onPause();
mSensorManager.registerListener(light, mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),SensorManager.SENSOR_DELAY_FASTEST);
Handler h=new Handler();
h.postDelayed(myTask, 10000);
}
private Runnable myTask = new Runnable()
{
public void run()
{
onResume();
}
};
}
Please, help me.
I resolved this way. it was simpler that i thought.
SensorManager mSensorMgr = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
HandlerThread mHandlerThread = new HandlerThread("sensorThread");
mHandlerThread.start();
Handler handler = new Handler(mHandlerThread.getLooper());
mSensorMgr.registerListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST, handler);