我正在开发一个使用传感器的应用程序。 我将有机会按照给定的顺序在控制台中显示传感器数据。首先,我从加速度计,下一个磁力计数据中查看数据。 目前,数据是随机显示的。一旦加速度计,一旦磁力计。有时他们会出现两次。
这是我的代码:
public class StartFragment extends Fragment implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private Sensor magnetic;
private static final int PERIOD = 10000;
private Handler handler;
boolean flag = false;
private final Runnable processSensors = new Runnable() {
@Override
public void run() {
sensorManager.registerListener(StartFragment.this, accelerometer, SensorManager.SENSOR_DELAY_UI);
sensorManager.registerListener(StartFragment.this, magnetic, SensorManager.SENSOR_DELAY_UI);
flag = true;
handler.postDelayed(this, PERIOD);
}
};
public StartFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_start, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
@Override
public void onResume() {
super.onResume();
handler.post(processSensors);
}
@Override
public void onPause() {
super.onPause();
handler.removeCallbacks(processSensors);
sensorManager.unregisterListener(this, accelerometer);
sensorManager.unregisterListener(this, magnetic);
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[] value = sensorEvent.values;
if (flag) {
Log.d("Current sensor: ", sensorEvent.sensor.getName() + " x: " + Float.toString(value[0]));
Log.d("Current sensor: ", sensorEvent.sensor.getName() + " y: " + Float.toString(value[1]));
Log.d("Current sensor: ", sensorEvent.sensor.getName() + " z: " + Float.toString(value[2]));
flag = false;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {}
答案 0 :(得分:2)
我相信你的方法有问题。传感器以异步方式工作,当他们可以回答时,他们会回答。软件角色是获取答案并在它们到来时使用它们。
在您的情况下,imho的解决方案是,在您获得之前的传感器值后启动并初始化任何传感器,或者更好的是,只是异步工作并保持您的可视化独立(即方式之一的mvp编程基础知识)