Android 当加速度计中3axis的值发生变化时,如何触发警报?
我有以下代码:Android 当加速度计中3axis的值发生变化时,如何触发警报?,android,accelerometer,Android,Accelerometer,我有以下代码: import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.TextView;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
TextView xCoor; // declare X axis object
TextView yCoor; // declare Y axis object
TextView zCoor; // declare Z axis object
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
xCoor=(TextView)findViewById(R.id.xcoor); // create X axis object
yCoor=(TextView)findViewById(R.id.ycoor); // create Y axis object
zCoor=(TextView)findViewById(R.id.zcoor); // create Z axis object
// add listener. The listener will be HelloAndroid (this) class
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
/* More sensor speeds (taken from api docs)
SENSOR_DELAY_FASTEST get sensor data as fast as possible
SENSOR_DELAY_GAME rate suitable for games
SENSOR_DELAY_NORMAL rate (default) suitable for screen orientation changes
*/
}
public void onAccuracyChanged(Sensor sensor,int accuracy){
}
public void onSensorChanged(SensorEvent event){
// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
// assign directions
float x=event.values[0];
float y=event.values[1];
float z=event.values[2];
// to display the
xCoor.setText("Accelerometer X: "+ x);
yCoor.setText("Accelerometer Y: "+ y);
zCoor.setText("Accelerometer Z: "+ z);
}
}
我需要在其中一个轴改变其值时触发警报。。。。如果发生事故,我的x轴发生变化,将触发视频上传事件。。。。有谁知道并愿意指导我吗?你需要这样的东西(请注意,这更多的是一个示例,而不是功能性的Android特定代码): 这在实践中很可能不起作用,因为传感器会非常快地为您提供新值,并且差值不太可能高于阈值。相反,您需要对其进行编辑,以便在短时间内存储来自传感器的最大值和最小值,并根据阈值检查它们之间的差异。例如,记录3秒钟内的最大值和最小值,并进行比较。如果它们之间的差异大于阈值(您应该根据一些事故测试数据预先计算),那么您可以上传视频或您想做的任何事情
float foo = 100f;//Some default value
public void compareX(float x) { //Call this from your onSensorChanged and pass it the X value
float diff = x - foo;
if(diff>threshold) //threshold is the baseline value for your sudden change
{
uploadVideo();
}
else{
foo = x;
}