gpt4 book ai didi

Android 在最小化和重新启动期间保留变量状态

转载 作者:行者123 更新时间:2023-11-29 21:10:06 28 4
gpt4 key购买 nike

我有一个简单的 Activity ,我根据复选框状态在 onCreate 中启动服务。

@Override
protected void onCreate(Bundle savedInstanceState) {
if(savedInstanceState == null)
Log.e(TAG,"savedInstanceState is null");
if(savedInstanceState != null){
Log.e(TAG,"savedInstanceState is not null");
}
super.onCreate(savedInstanceState);

在复选框状态下选中启动服务并设置serviceStarted

toggleButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {



@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){

Log.e(TAG,"starting service");
serviceStarted = true;
startService(new Intent(getApplicationContext(), MyService.class));

}else{

serviceStarted = false;
stopService(new Intent(getApplicationContext(), MyService.class));


}

}
});

我已经覆盖了以下功能

@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
Log.e(TAG,"onSaveInstanceState called");
super.onSaveInstanceState(outState);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e(TAG,"onResume called : serviceStarted = "+String.valueOf(serviceStarted));
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.e(TAG,"onPause called : serviceStarted = "+String.valueOf(serviceStarted));
}

现在在我的 logcat 中,在启动服务后最小化并重新启动应用程序时,我在下面看到

04-22 12:34:42.150: E/MainActivity(19720): onPause called : serviceStarted = true
04-22 12:34:44.700: E/MainActivity(19720): onResume called : serviceStarted = false

现在我的需求是

我想保留 serviceStarted 的状态不使用 sharedpreferences

无论如何,还是我应该使用服务绑定(bind)模型?请帮忙谢谢

最佳答案

好吧,只需使用整个保存实例状态的东西,这就是它的用途:

protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("serviceStarted", mServiceStarted);
}

protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
mServiceStarted = state.getBoolean("serviceStarted", false);
}

但实际上,如果您的 Activity 被真正销毁(通过后退按钮或操作系统),您仍然会丢失状态,因此更可靠的选择是使用 SharedPreferences

但是在您的情况下,服务仍然可以在您的 Activity 暂停和恢复之间被终止——然后您的 serviceStarted 将过时。所以只需使用静态成员来了解状态:

public MyService extends Service {
private static volatile boolean mIsRunning = false;
public void onCreate() {
MyService.mIsRunning = true;
}
public void onDestroy() {
MyService.mIsRunning = false;
}
public static boolean isRunning() {
return mIsRunning;
}
}

关于Android 在最小化和重新启动期间保留变量状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23222331/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com