您好,我是 android 编程新手。我正在为学校编写一个应用程序,我需要将加速度计数据保存到一个 txt 文件中。问题是当我锁定屏幕或打开屏幕保存时,数据记录会停止。你能给我建议吗?
这是我的代码:
package emzet.data2text;
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.os.PowerManager;
import android.view.View;
import android.widget.Button;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private FileWriter writer;
private Button btnStart, btnStop;
String root = Environment.getExternalStorageDirectory().toString();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setEnabled(true);
btnStop.setEnabled(true);
//PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
//PowerManager.WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyWakeLock");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
public void onStartClick(View view) {
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
btnStop.setEnabled(true);
btnStart.setEnabled(false);
}
public void onStopClick(View view) {
sensorManager.unregisterListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
}
protected void onResume() {
super.onResume();
try {
writer = new FileWriter(root + "/acc2txt-file.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPause() {
super.onPause();
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@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];
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss:SSS");
String s = time.format(new java.util.Date());
try {
writer.write(s+"\t"+x+"\t"+y+"\t"+z+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}