java 如何注册监听器以更改方向?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10361888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:42:12  来源:igfitidea点击:

How to register a listener for orientation change?

javaandroidorientation

提问by Nguyen Minh Binh

My android app will run at background and I need to be notify immediately when orientation change. eg. When user rotate the phone from portrait to landscape (or landscape to portrait), the system should be tell my app that the orientation has changed.

我的 android 应用程序将在后台运行,当方向改变时我需要立即得到通知。例如。当用户将手机从纵向旋转到横向(或横向到纵向)时,系统应该告诉我的应用程序方向已经改变。

Thanks.

谢谢。

回答by Rafiq

This method is called when screen rotated

屏幕旋转时调用此方法

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
        //Do stuff here
}

回答by Arif Nadeem

You do not have to explicitly set the Orientation listener.

您不必显式设置 Orientation 侦听器。

onConfigurationChangedwill be called by the system.

onConfigurationChanged会被系统调用。

@Override
public void onConfigurationChanged(Configuration myConfig) {
    super.onConfigurationChanged(myConfig);
    int orient = getResources().getConfiguration().orientation; 
    switch(orient) {
                case Configuration.ORIENTATION_LANDSCAPE:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
                case Configuration.ORIENTATION_PORTRAIT:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                default:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }
}

回答by Green Tree

But you can implement onConfigurationChanged in daemon. here : Service.

但是您可以在守护进程中实现 onConfigurationChanged。这里:服务