我有一个类似该主题的小问题。在后台运行的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,但是当有人单击“主页”按钮时,它不起作用。
答案 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)