传感器

MainActivity.java

public class MainActivity extends Activity {
    private SensorManager sm;
    private MyListener listener;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        iv = (ImageView) findViewById(R.id.iv);
        // 速度 方向传感器 光传感器 温度传感器 近距离传感器
        List lists = sm.getSensorList(Sensor.TYPE_ALL);
        for (Sensor s : lists) {
            System.out.println(s.getName());
        }
        listener = new MyListener();
        // 方向传感器
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);

    }

    private class MyListener implements SensorEventListener {
        float lastangle = 0;
        // 当传感器发现数据变化了。
        @Override
        public void onSensorChanged(SensorEvent event) {
            // 0=North, 90=East, 180=South, 270=West
            float angle = event.values[0];
            System.out.println("角度:" + angle);
            RotateAnimation ra = new RotateAnimation(lastangle, -angle,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            ra.setDuration(200);
            
            iv.startAnimation(ra);
            lastangle = -angle;
        }

        // 当传感器的精确度变化的时候
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }

    @Override
    protected void onDestroy() {
        sm.unregisterListener(listener);
        listener = null;
        super.onDestroy();
    }
}
zn.png

activity_main.xml



    


你可能感兴趣的:(传感器)