结合来自两个传感器android的数据

时间:2015-09-19 10:40:12

标签: android sensor

我有一个加速度计,指向箭头的方式我倾斜手机,当我把手靠近传感器时,我有一个显示不同状态的图像。我想要合并,这样如果我将手机向右倾斜并且将手放在接近传感器上会发生一些事情。

ImageView is;
ImageView iv;
private Sensor mAccelerometer;
private Sensor myProximitySensor;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    iv = (ImageView) findViewById(R.id.imageView1);
    is = (ImageView)findViewById(R.id.imageView);

    final SensorManager manager;
    SensorEventListener listener;

    manager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
    listener = new SensorEventListener() {
        @Override
        public void onAccuracyChanged(Sensor arg0, int arg1) {

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            Sensor sensor = event.sensor;

            if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {


                float x = event.values[0];

                float y = event.values[1];

                float z = event.values[2];

                if (Math.abs(x) > Math.abs(y)) {

                    if (x < 0) {
                        iv.setImageResource(R.drawable.right);



                    }

                    if (x > 0) {

                        iv.setImageResource(R.drawable.left);

                    }

                } else {

                    if (y < 0) {

                        iv.setImageResource(R.drawable.up);

                    }

                    if (y > 0) {

                        iv.setImageResource(R.drawable.down);

                    }

                }

                if (x > (-2) && x < (2) && y > (-2) && y < (2)) {

                    iv.setImageResource(R.drawable.center);

                }
            }
            else if (sensor.getType() == Sensor.TYPE_PROXIMITY) {

                if(event.values[0]==0 ){
                    is.setImageResource(R.drawable.near);



                }else {
                    is.setImageResource(R.drawable.far);

                }


            }


        }
    };
    manager.registerListener(listener, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME);
    manager.registerListener(listener, manager.getDefaultSensor(Sensor.TYPE_PROXIMITY),SensorManager.SENSOR_DELAY_GAME);
}

0 个答案:

没有答案