美文网首页
根据加速度感应器判断手机方向

根据加速度感应器判断手机方向

作者: 43d60efa37c7 | 来源:发表于2017-03-02 10:34 被阅读116次
    //手机顶部朝上
    public static final int UP = 0;
    //手机底部朝上
    public static final int DOWN = 1;
    //手机左边朝上
    public static final int LEFT = 2;
    //手机右边朝上
    public static final int RIGHT = 3;
    public int orientation = 0;
    
    @Override
    public void onResume() {
        SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor_gravity=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
         sensorManager.registerListener(new SensorEventListener() {
                
                @Override
                public void onSensorChanged(SensorEvent event) {
                    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                        float x = event.values[0];
                        float y = event.values[1];
                        //y的绝对值大于x时,顶部或者底部朝上
                        if (Math.abs(y) > Math.abs(x)) {
                            if (y > 0) {
                                orientation = UP;
                            }else{
                                orientation = DOWN;
                            }
                        }else{
                            if (x > 0) {
                                orientation = LEFT;
                            }else{
                                orientation = RIGHT;
                            }
                        }
                    }
                }
                
                @Override
                public void onAccuracyChanged(Sensor arg0, int arg1) {
                    // TODO Auto-generated method stub
                    
                }
            }, sensor_gravity, SensorManager.SENSOR_DELAY_UI);
            super.onResume();
    

    相关文章

      网友评论

          本文标题:根据加速度感应器判断手机方向

          本文链接:https://www.haomeiwen.com/subject/skshgttx.html