2012-07-09 20 views
0

我有下面這段代碼:如何在加速計中3軸的值發生變化時觸發警報?

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軸改變,也引發關閉視頻上傳活動....有誰知道並願意引導我?

回答

1

你需要像這樣(請注意,這是比功能的Android特定代碼爲例):

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; 
} 

這很可能不會在實踐中該傳感器爲您提供了新的價值相當快的工作並且差異不大可能高於閾值。相反,您需要對其進行編輯以在短時間內存儲傳感器的最大值和最小值,並檢查它們與閾值的差異。例如,記錄3秒鐘內的最大值和最小值,然後進行比較。如果它們的差異大於閾值,那麼您應該從某些事故測試數據中預先計算出該閾值,然後您上傳視頻或您想要執行的任何操作。

相關問題