即使在关闭应用程序Android时,如何保留活动的任务



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

@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();
}

最新更新