我希望传感器监听器在按钮点击时开始从传感器获取信息。但是,只要我的活动开始,传感器事件监听器就会开始调用传感器。简而言之,我想控制传感器事件监听器何时开始调用传感器以及何时应该停止从按钮传感器进行监听。我怎么能这样做?
我的代码如下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
final Button posture=(Button)findViewById(R.id.posture_test);
final Button uploaded=(Button)findViewById(R.id.upload);
final Timer start_rec = new Timer();
final android.os.Handler han=new android.os.Handler();
final TextView timer= (TextView)findViewById(R.id.timertxt);
startService(new Intent(this,GPS_Location.class)); //starting the service to get location of user every 1 minute
posture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
posture.setEnabled(false);
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Time Left: " + millisUntilFinished / 1000+" Sec");
}
public void onFinish() {
timer.setText("Test Completed");
}
}.start();
han.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("STOPPED","...");
posture.setText("STOP");
uploaded.setVisibility(View.VISIBLE);
posture.setVisibility(View.GONE);
sensorManager.unregisterListener(gyroListener);
//obj.getLocation();
}
},60000);
}
});
uploaded.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Uri uri=Uri.parse("http://192.168.43.125:8080");
//Intent server=new Intent(Intent.ACTION_VIEW,uri);
//startActivity(server);
Intent posture=new Intent(MainActivity.this,Tapping_Test.class);
startActivity(posture);
}
});
sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
txtX=(TextView)findViewById(R.id.textX);
txtY=(TextView)findViewById(R.id.textY);
txtZ=(TextView)findViewById(R.id.textZ);
}
public void onResume(){
super.onResume();
sensorManager.registerListener(gyroListener,sensor,sensorManager.SENSOR_DELAY_FASTEST);
}
public void onStop(){
super.onStop();
sensorManager.unregisterListener(gyroListener);
}
@Override
public void onBackPressed()
{
finish();
}
public SensorEventListener gyroListener=new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
float x =event.values[0];
float y =event.values[1];
float z =event.values[2];
txtX.setText("X: "+(int)x+" m/s2");
txtY.setText("Y: "+(int)y+" m/s2");
txtZ.setText("Z: "+(int)z+" m/s2");
//Log.d("writing"," to csv"+event.values[0]);
//writing to a csv file...
try {
writeToCsv(Float.toString(event.values[0]),Float.toString(event.values[1]),Float.toString(event.values[2]));
//Log.d("writing"," to csv"+event.values[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};