I am trying to save the obtained accelerometer data to the file on the phone. I get the data every second and I want to save it to the file. Here is my attempt:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.button_start);
stop = (Button)findViewById(R.id.button_stop) ;
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
if (sensors.size() > 0) {
for (Sensor sensor : sensors) {
switch (sensor.getType()) {
case Sensor.TYPE_LINEAR_ACCELERATION:
if (mAccelerometerSensor == null) mAccelerometerSensor = sensor;
break;
default:
break;
}
}
}
context= this;
mXAccValueText = (TextView)findViewById(R.id.value_x);
mYAccValueText = (TextView)findViewById(R.id.value_y);
mZAccValueText = (TextView)findViewById(R.id.value_z);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
writer = new FileWriter("data.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
time = System.currentTimeMillis();
mSensorManager.registerListener(MainActivity.this, mAccelerometerSensor, SensorManager.SENSOR_DELAY_GAME);
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mSensorManager.unregisterListener(MainActivity.this);
}
});
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
long currentTime;
switch (event.sensor.getType()) {
case Sensor.TYPE_LINEAR_ACCELERATION:
currentTime = System.currentTimeMillis();
if (currentTime - accelerometerTime > 1000) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
try {
writer.write(x+","+y+","+z+"\n");
} catch (IOException e) {
e.printStackTrace();
}
accelerometerTime = currentTime;
}
break;
}
}
However, I just keep getting exceptions. I am new to Android, can anyone point me in the right direction, please?
if (currentTime - accelerometerTime > 1000)
Have you set accelerometerTimer before this? In the code given you only set it afterwards?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.