在Android上仅允许纵向时检测方向更改

ove*_*t13 4 android android-orientation

我必须解决以下几个:我有一个Activity它的android:screenOrientation="portrait".即使当设备在Activity可见时旋转到横向时,我必须启动另一个设备,并且当设备旋转回纵向时,我必须进行finish()横向活动.我尝试用a执行此操作BroadcastReceiver,但是这个特殊活动因为没有收到任何广播android:screenOrientation="portrait".任何帮助都非常感谢.

谢谢.

小智 7

Philipp的解决方案是获取手机定位,但将屏幕方向固定为肖像作品对我来说非常完美:

您可以使用SensorManager类来获取Android设备的方向,即使在Manifest中通过android禁用自动方向切换:screenOrientation ="portrait"

看到这段代码(由Philipp,见上面的链接):

SensorManager sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
    sensorManager.registerListener(new SensorEventListener() {
        int orientation=-1;;

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.values[1]<6.5 && event.values[1]>-6.5) {
                if (orientation!=1) {
                    Log.d("Sensor", "Landscape");
                }
                orientation=1;
            } else {
                if (orientation!=0) {
                    Log.d("Sensor", "Portrait");
                }
                orientation=0;
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }
    }, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
Run Code Online (Sandbox Code Playgroud)


Cha*_*har 5

当 android:screenOrientation="portrait" 或 "landscape" 在menifest 文件中设置时,如果您想这样做,则仍然不会触发任何侦听器,请尝试以编程方式在您的 onConfigurationChanged() 中处理仅纵向模式,在这里您也可以启动再次活动。

  • 答案是错误的,OrientationEventListener 在这种情况下工作正常 (2认同)