我正在制作一个记录加速度计读数的应用程序。当我输入TYPE_ACCELEROMETER时,它可以完美记录原始加速度计数据。但是,当我输入TYPE_LINEAR_ACCELERATION时,它无法返回任何值。该应用程序没有给我错误或退出。我认为我必须使用的设备不支持TYPE_LINEAR_ACCELERATION,或者我的清单中没有所有必要的权限。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
currentX = (TextView) findViewById(R.id.currentX);
currentY = (TextView) findViewById(R.id.currentY);
currentZ = (TextView) findViewById(R.id.currentZ);
}
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
currentX.setText(Float.toString(x));
currentY.setText(Float.toString(y));
currentZ.setText(Float.toString(z));
try {
writer.write(x + "," + y + "," + z + "\n");
} catch (IOException e) {
Log.e(LOG_TAG2, "failed");
}
}
};
public void Recordbutton(View view) {
if (recordbuttonstatus) {
playBtn.setEnabled(true);
recordbuttonstatus = false;
startBtn.setText(getString(R.string.stoprecording));
sensorManager.registerListener(accelListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(accelListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
Thread accelerometerrecord = new Thread(new Runnable() {
@Override
public void run(){
File accoutputFile = new File(Environment.getExternalStorageDirectory(), "accelerometervals.txt");
try {
accoutputFile.createNewFile();
} catch (IOException e){
e.printStackTrace();
}
try {
writer = new FileWriter(accoutputFile, false); /*When false, the file is overwritten, when true, the file is appended.*/
} catch (IOException e) {
Log.e(LOG_TAG2, "failed");
}
}
});
accelerometerrecord.start();
} else {
startBtn.setText(getString(R.string.newrecording));
recordbuttonstatus = true;
sensorManager.unregisterListener(accelListener);
}
}
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(accelListener);
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
Log.e(LOG_TAG2, "failed");
}
}
}
public void onStop() {
super.onStop();
sensorManager.unregisterListener(accelListener);
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
Log.e(LOG_TAG2, "failed");
}
}
}
最佳答案
感谢大家。原来,我的手机没有线性加速度传感器。