因此,我正在开发用于将传感器值存储在一个文件中的 android 应用程序。我的主要问题是应用程序只是在文件中写入最后一个值。基本上我正在尝试编写将每个传感器值存储到文件的代码。我是编写Android应用程序的初学者...有人可以帮忙吗?这是代码:
package com.example.hello;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView xAxis, yAxis, zAxis;
private SensorManager sm;
private Sensor mSensor;
final File file = new File(Environment.getExternalStorageDirectory(),
"results.txt");
static FileOutputStream fos;
static OutputStreamWriter myOutWriter;
private String writeString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xAxis = (TextView) findViewById(R.id.xAxis);
yAxis = (TextView) findViewById(R.id.yAxis);
zAxis = (TextView) findViewById(R.id.zAxis);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
try {
fos = new FileOutputStream(file);
myOutWriter = new OutputStreamWriter(fos);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SensorEventListener sensor = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
xAxis.setText("xAxis: " + event.values[0]);
yAxis.setText("yAxis: " + event.values[1]);
zAxis.setText("zAxis: " + event.values[2]);
String test = new String(" " + event.values[0] + " "
+ event.values[1] + " " + event.values[2]);
writeData(test);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
sm.registerListener(sensor,
sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_UI);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static void writeData(String test) {
try {
myOutWriter.append(test);
myOutWriter.flush();
myOutWriter.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
}