簡體   English   中英

當手機在縱向-橫向模式之間旋轉時,如何阻止加速度計檢測向上/向下運動

[英]How do I stop accelerometer from detecting upward/downward motion when the phone is rotated between portrait-landscape modes

當我down up 2 個布爾值。 手機默認position為豎屏。

當我將手機旋轉到橫向時,即使我沒有向下移動手機, down變量也會變為真。 然后,當我旋轉回縱向時,即使手機沒有向上移動, up值也會變為真。

我該如何阻止這種情況發生? 我想要這樣,如果手機處於updown模式,無論手機的方向如何,它都會保持該模式。

上下代碼:

                if (ty > 3.0f) { // go down
                    getWindow().getDecorView().setBackgroundColor(Color.GREEN);
                    down = true;
                    up = false;
                }
                else if (ty < -3.0f) { // go up
                    getWindow().getDecorView().setBackgroundColor(Color.YELLOW);
                    up = true;
                    down = false;
                }

                upVal.setText("Up: " + up);
                downVal.setText("Down: " + down);

(我也不知道為什么當我向下移動它時它會變成綠色,即使ty值為正,反之亦然。)

旋轉代碼:

            if( (orientation < 35 || orientation > 325) && rotation!= ROTATION_O){ // PORTRAIT
                rotation = ROTATION_O;
            }
            else if( orientation > 145 && orientation < 215 && rotation!=ROTATION_180){ // REVERSE PORTRAIT
                rotation = ROTATION_180;
            }
            else if(orientation > 55 && orientation < 125 && rotation!=ROTATION_270){ // REVERSE LANDSCAPE
                rotation = ROTATION_270;
            }
            else if(orientation > 235 && orientation < 305 && rotation!=ROTATION_90){ //LANDSCAPE
                rotation = ROTATION_90;
            }

事實證明,我需要做的就是分別在手機旋轉和停止時注銷和重新注冊加速度計。

  1. 這里添加一個陀螺儀 class
  2. 在 MainActivity 中,添加以下內容:
        gyroscope.setListener(new Gyroscope.Listener() {
            // on rotation method of gyroscope
            @Override
            public void onRotation(float rx, float ry, float rz) {
                if (rz > 1.0f) {
                    //phone is moving, unregister the accelerometer
                    accelerometer.unregister();

                } else if (rz < -1.0f) {
                    // phone is moving, unregister the accelerometer
                    accelerometer.unregister();

                } else {
                    //phone stops moving, re-register the accelerometer
                    accelerometer.register();
                }
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM