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

时间:2014-04-22 14:23:56

标签: android

我有一个简单的活动,我根据复选框状态在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

无论如何,或者我应该使用服务绑定模型?请帮忙谢谢

1 个答案:

答案 0 :(得分:2)

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

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

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

在您的情况下,服务仍然可以在您的活动暂停和被带回的时间之间被杀死 - 然后您的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;
    }
}