📜  如何将传感器数据写入文件 android studio - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:43.093000             🧑  作者: Mango

代码示例1
public class Main extends Activity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
private FileWriter writer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activiy_main);
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}

public void onStartClick(View view) {
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}

public void onStopClick(View view) {
    mSensorManager.unregisterListener(this);
}
protected void onResume() {
    super.onResume();
    writer = new FileWriter("myfile.txt",true);
}

protected void onPause() {
    super.onPause();

    if(writer != null) {
       writer.close();
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

@Override
public void onSensorChanged(SensorEvent event) {

    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];
    writer.write(x+","+y+","+z+"\n");

 }
}