【发布时间】:2017-06-09 07:02:06
【问题描述】:
我正在尝试将 onSensorChanged( ) 方法的总加速度写入文件。我处理写入文件的代码有问题。 我的文件只显示一个值。我想查看 所有 值,直到我切换按钮停止写入。您能否指出我的代码中的错误在哪里。提前致谢。
ToggleButton OnStore;
private GestureDetectorCompat mDetector;
FileOutputStream fileOutputStream;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnStore = (ToggleButton) findViewById(R.id.onStore);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorText = (TextView) findViewById(R.id.sensor);
accelermeter = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelermeter,
SensorManager.SENSOR_DELAY_NORMAL);
OnStore.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (OnStore.isChecked()){
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File Root = Environment.getExternalStorageDirectory();
File dir = new File(Root.getAbsolutePath()+"/MyApp");
if (!dir.exists()){
dir.mkdir();
}
File file = new File(dir,"Mymessage.txt");
try {
fileOutputStream = new FileOutputStream(file,true);
String space =" ";
byte[] convert = space.getBytes();
fileOutputStream.write(convert);
String finalData;
finalData = String.valueOf(TotalAccelerate);
fileOutputStream.write(finalData.getBytes());
//fileOutputStream.close();
Toast.makeText(getApplicationContext(),"Message saving",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
Toast.makeText(getApplicationContext(),"SDcard not found",Toast.LENGTH_LONG).show();
}
}
if (!OnStore.isChecked()){
try {
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getApplicationContext(),"Message Stopped.",Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
double TotalAccelerate;
ArrayList<Double> list;
@Override
public final void onSensorChanged(SensorEvent event) {
// The light sensor returns a single value.
// Many sensors return 3 values, one for each axis.
double xx = event.values[0];
double yy = event.values[1];
double zz = event.values[2];
TotalAccelerate = Math.round(Math.sqrt(Math.pow(xx, 2)
+ Math.pow(yy, 2)
+ Math.pow(zz, 2)));
// Log.i(DEBUG,"Total "+ TotalAccelerate);
list = new ArrayList<Double>();
list.add(TotalAccelerate);
// findPeaks(list);
sensorText.setText("Total: " + list);
Log.i(DEBUG, "Total " + list);
}
【问题讨论】:
标签: java android android-layout listview android-studio