我需要每秒从我的Android手机中收集传感器数据。我编写的代码为我提供了传感器数据,但仅在传感器值发生变化时才显示。但是我需要收集数据,而无论更改如何。我搜索了,很明显,这就是android sensorManager的工作方式。但有人告诉我有一种解决方法,通过使用计时器功能或使用轮询功能(每秒轮询传感器Listener),可以定期收集数据。 我不是开发人员,并且对Android编程没有太多的了解。有人可以帮我提供代码吗?下面是我当前的代码:
public class MainActivity extends AppCompatActivity implements SensorEventListener{
private static final String TAG = "MainActivity";
private SensorManager sensorManager;
private Sensor mLight, acceleration, mGyro;
TextView soundVal, AccVal, lightVal, GyroVal, RotVal;
Thread runner;
private static double mEMA = 0.0;
static final private double EMA_FILTER = 0.6;
public static final int RequestPermissionCode = 1;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
soundVal = (TextView) findViewById(R.id.soundVal);
lightVal = (TextView) findViewById(R.id.lightVal);
GyroVal = (TextView) findViewById(R.id.GyroVal);
AccVal = (TextView) findViewById(R.id.AccVal);
soundVal = (TextView) findViewById(R.id.soundVal);
Log.d(TAG, "onCreate: Initializing Sensor Services");
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mLight = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
@Override
public void onResume(){
super.onResume();
sensorManager.registerListener(this, mLight,SensorManager.SENSOR_DELAY_GAME);
if (mLight != null) {
sensorManager.registerListener(MainActivity.this, mLight, 1000000000);
Log.d(TAG, "onCreate: Registered Light Listener");
}else{
Log.d(TAG, "onCreate: Light Sensor not supported");
}
}
@Override
public void onPause(){
super.onPause();
sensorManager.unregisterListener(this);
}
//@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor sensor = sensorEvent.sensor;
if (sensor.getType() == Sensor.TYPE_LIGHT) {
Log.d(TAG, "onSensorChanged: \n");
Log.d(TAG, "onSensorChanged: LIGHT: " + sensorEvent.values[0] + "lx");
lightVal.setText("Light: " + sensorEvent.values[0] + " lx");
//SAVING THE LIGHT DATA IN CSV FILE
String FILENAME = "Light_Data.csv";
//To get the system time to be saved along with the Light Data for time synchronisation with second Mobile device data
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSSS");
String entry = format.format(calendar.getTimeInMillis()) + "," + sensorEvent.values[0] + "," + "lx" + "\n";
Log.d(TAG, "onSensorChanged: VALUE" +sensorEvent.values[0] + "lx");
try {
FileOutputStream out = openFileOutput(FILENAME, Context.MODE_APPEND);
out.write(entry.getBytes());
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
//@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}