1

是否可以在方法内获取 Android 加速度计值onCreate?我想要它,以便在阅读后进行一些初始化。到目前为止,我已经注册了一个传感器侦听器,以便在它们通过onSensorChanged 回调更改时获取这些值。我有 3 个浮点属性(lastxlastylastz)初始化为 -1,以便在更改时将加速度计值存储在那里。在onCreate方法中,注册我的传感器侦听器后,我试图检查这些值,但它们总是等于-1。有没有办法在方法中获取这些值onCreate

这是我的代码:

public class MainActivity extends Activity implements SensorEventListener {
    private SensorManager sensorManager;

    TextView textView;
    StringBuilder builder = new StringBuilder();
    float lastx = -1;
    float lasty = -1;
    float lastz = -1;

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        textView = new TextView(this);

        SensorManager manager = (SensorManager) 
                     getSystemService(Context.SENSOR_SERVICE);

        Sensor accelerometer = manager.getDefaultSensor(
                                     Sensor.TYPE_ACCELEROMETER);

        if(!manager.registerListener(this, accelerometer,
                                     SensorManager.SENSOR_DELAY_GAME)){
        Log.d("ERROR: ", "NO accelerometer found!");
        }

        setContentView(textView);
        builder.setLength(0);

        builder.append(
           "X " + this.lastx + "\nY " + this.lasty + "\nZ " + this.lasty);
        textView.setText(builder.toString());

         Log.d(" * accelerometer values:",
            "X: " + this.lastx+", Y: " + this.lasty + ", Z: " + this.lastz);

    }

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

                 this.lastx = x;
                 this.lasty = y;
                 this.lastz = z;

                 // builder.setLength(0);
                 // builder.append("X " + x + "\nY " + y + "\nZ " + z);
                 // textView.setText(builder.toString());
      }
  }
}
4

2 回答 2

2

onCreate我认为主用户界面线程同时用于onSensorChanged. 所以在完成onSensorChanged之前不能运行onCreate。无论您需要做什么初始化,我建议您安排在第一次调用时完成onSensorChanged,例如,如果值为 -1,则进行初始化。

于 2013-06-11T11:48:15.193 回答
0

先初始化一些变量。

int value , count = 0 , newVal;

内部 onSensorChanged

if(count == 0){

            value = (int) event.values[0];

            count++;

        }

        newVal = (int) event.values[0] - value ;
于 2019-12-11T09:50:19.823 回答