Q:

Can android app detect orientation change while running in the background?

I have a small question like in the topic. Can android app which is running in the background detect orientation screen change? I have this code 
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");
        }
    }

}

from android docs but it does not work when for example someone clicked home button.

A:

Create an android service, register a broadcast receiver for configuration changes and handle orientation changes inside. 
https://developer.android.com/training/run-background-service/create-service
val filter = IntentFilter().apply {
addAction(android.intent.action.CONFIGURATION_CHANGED)
} 
this.registerReceiver(broadcastReceiver, filter)

