如何在关闭应用程序时保留 activity 的任务 Android

How to retain the task of the activity even when closing the app Android

我的 android 应用程序中有一个切换按钮,我打算将其打开,但在我通过在后台任务中删除它退出应用程序后,当我再次打开该应用程序时,它恢复正常并切换再次回到关闭状态。 i=我想保留或保存我留下的activity。我将如何保留我的 activity 基本上是片段本身的任务?我要使用暂停吗?

@Override
public void onPause() {
    super.onPause();

}

您可以使用共享首选项来完成此操作。例如,在 onCreate 中,从共享首选项加载开关状态(第一次使用默认值)

SharedPreferences prefs = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE);
switchState = prefs.getBoolean("MyBoolean", false); // switchState being a boolean class member
// then set the switch to switchState

当用户更新开关时,更改 switchState 的存储值并在 onPause 中将更新状态保存到共享首选项中

@Override
public void onPause() {
    super.onPause();
    SharedPreferences.Editor ed = getSharedPreferences("MyUniquePrefsName", Context.MODE_PRIVATE).edit();
    ed.putBoolean("MyBoolean", switchState);
    ed.apply();
}