android 传感器

android  传感器

android  传感器
public class MainActivity extends Activity {
    private ImageView imageView;
    //传感器管理器
    private SensorManager manager;
    //传感器监听器
    private SensorListener listener = new SensorListener();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        imageView = (ImageView) this.findViewById(R.id.imageView);
        imageView.setKeepScreenOn(true);
        //由于传感器是系统提供的服务,所以通过该方法可以获得传感器管理器
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        //在应用在前台时,获取相应的传感器
        Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        //通过传感器管理器为传感器注册监听器,SensorManager.SENSOR_DELAY_GAME采样频率
        manager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //在应用离开前台时,取消注册的监听器
        manager.unregisterListener(listener);
        super.onPause();
    }
    //传感器监听器
    private final class SensorListener implements SensorEventListener{
        //记录先前的值
        private float predegree = 0;
        public void onSensorChanged(SensorEvent event) {
            //获取当前传感器的采样值
            float degree = event.values[0];//存放了方向值 90
            RotateAnimation animation = new RotateAnimation(predegree, -degree, 
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setDuration(200);
            imageView.startAnimation(animation);
            predegree = -degree;
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    }
    
    
}
android  传感器

android 传感器

上一篇:android 动画


下一篇:Android 直连SQL