android应用可以在后台运行时检测方向变化吗?

时间:2019-06-19 16:50:53

标签: android android-activity orientation

我有一个类似该主题的小问题。在后台运行的android应用能否检测到方向屏幕变化?我有此代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

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

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
            System.out.println("landscape");
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
            System.out.println("portrait");
        }
    }

}

来自android docs,但是当有人单击“主页”按钮时,它不起作用。

1 个答案:

答案 0 :(得分:0)

创建一个android服务,注册一个广播接收器以进行配置更改并处理内部的方向更改。 https://developer.android.com/training/run-background-service/create-service

val filter = IntentFilter().apply {
addAction(android.intent.action.CONFIGURATION_CHANGED)
} 
this.registerReceiver(broadcastReceiver, filter)