在不旋转应用程序的情况下捕获设备旋转

时间:2019-03-20 20:18:51

标签: android android-layout android-activity rotation screen-rotation

Tenho umaaplicaçãocom Android Webview,用户活动配置portrait

<activity
        android:name=".activity.MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateUnspecified|adjustResize"></activity>

但是我想进行以下事件:用户旋转设备,并且应用程序屏幕继续纵向显示,但是我需要进行此事件,以仅使Web视图中的一个视频产生动画,并且旋转。有人针对这种情况有解决方案吗?

2 个答案:

答案 0 :(得分:1)

如果您要轮换活动,则应删除 android:screenOrientation =“纵向” 并添加 android:configChanges =“ orientation | keyboardHidden”

<activity
    android:name=".activity.MainActivity"
    android:configChanges="orientation|keyboardHidden"
    android:windowSoftInputMode="stateUnspecified|adjustResize"></activity>

然后在您的活动中覆盖 onConfigurationChanged()方法以在应用程序旋转时获取回调

class MainActivity extends AppCompatActivity {
    ...

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // App is rotated to landscape
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            // App is rotated to portrait
        }
    }
}

在这种情况下,将不会重新创建活动,您应该自己处理UI组件的更新。 看看original documentation可获得更多详细信息;)

已更新:

如果您想将“活动”保持为纵向模式并仅检测到旋转,请查看:

答案 1 :(得分:0)

解决:

    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("SensorLog", "Landscape");
                }
                orientation = 1;
            }
            else
            {
                if (orientation != 0)
                {
                    Log.d("SensorLog", "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);