读取传感器上的数据时出现问题已更改



onSensorChanged上有数据,这些数据在传感器打开时不断出现。

我想:

打开传感器 10 秒
  1. ,每隔 10 秒读取一次数据。
  2. 关闭传感器 20 秒钟。
  3. 连续重复相同的操作(步骤1到2(。

我使用ScheduledExecutorService.scheduleAtFixedRate定期从onSensorChanged读取数据,但它不起作用。解决方案是什么?

public class ProximityService extends Service {
@Override
public void onCreate() {
HandlerThread t = new HandlerThread("ProximityServiceHandler", THREAD_PRIORITY_BACKGROUND);
t.start();
_serviceLooper = t.getLooper();
_serviceHandler = new ProximityServiceHandler(_serviceLooper, this);
}

private final class ProximityServiceHandler extends Handler {
private static final int ON_TIME = 10000;   // 10 seconds
private static final int OFF_TIME = 20000;  // 20 seconds
private void parseSensor(SensorEvent sensorEvent) {
// data processing
}
@Override
public void handleMessage(Message msg) {
_sensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
if (_sensorManager != null) {
_sensor = _sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (_sensor != null) {
_sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent != null) {
// collect data..
// data available in here, but not in _sensorScheduler?
parseSensor(sensorEvent); 
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {       
//
}
};
// why this function doesn't worked ?
_sensorScheduler = Executors.newScheduledThreadPool(1);
_sensorScheduler.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
try {
// turnon sensor
_sensorManager.registerListener(_sensorEventListener, _sensor, SensorManager.SENSOR_DELAY_NORMAL);
// wait to collect data from sensor
Thread.sleep(ON_TIME);
// send data to main thread but data not available in here?
sendData(sensorEvent)
// turn off sensor
_sensorManager.unregisterListener(_sensorEventListener, _sensor);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 0, OFF_TIME, TimeUnit.MILLISECONDS);
}
}
}
}
}

我找到了解决方案,在sendData(sensorEvent(中调用toast,使传感器停止工作。

我修改了toast 以便能够从后台线程调用,如下所示:

public static void showToast(final Context context, final String text, final int duration) {
if (context != null && text != null) {
new Handler(context.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, text, duration).show();
}               
});
}
}

相关内容

  • 没有找到相关文章

最新更新