如何保存 Android 应用的运行状态呢?

pythoners 发布于 2011/09/30 09:52
阅读 969
收藏 2
编写了一个简单的应用,如下所示,想在应用启动的时候恢复之前保存的状态,我该怎么做呢?
package com.android.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTextView = new TextView(this);

        if (savedInstanceState == null) {
            mTextView.setText("Welcome to HelloAndroid!");
        } else {
            mTextView.setText("Welcome back.");
        }

        setContentView(mTextView);
    }

    private TextView mTextView = null;
}

加载中
0
鉴客
鉴客
你需要重载方法 onSaveInstanceState(Bundle savedInstanceState) 用来保存配置:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putBoolean("MyBoolean", true);
  savedInstanceState.putDouble("myDouble", 1.9);
  savedInstanceState.putInt("MyInt", 1);
  savedInstanceState.putString("MyString", "Welcome back to Android");
  // etc.
  super.onSaveInstanceState(savedInstanceState);
}

另外在读取配置的时候可以在 onCreate 或者是 onRestoreInstanceState 实现,代码如下:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
  double myDouble = savedInstanceState.getDouble("myDouble");
  int myInt = savedInstanceState.getInt("MyInt");
  String myString = savedInstanceState.getString("MyString");
}
0
sasuke38
sasuke38
明显是直接复制咱贴 来的 要是我是正常退出呢 怎么保存?那个方法只有不正常退出才会执行
0
sasuke38
sasuke38
public void save(){
		SharedPreferences sp = getSharedPreferences("XR", MODE_PRIVATE); 
		Editor editor = sp.edit(); 
		editor.putInt("fontSize", fontSize);
		editor.putInt("fontColor", fontColor);
		editor.putInt("backgroudColor", backgroudColor);
		editor.commit();
	}
	public void Init(){
		SharedPreferences sp = getSharedPreferences("XR", MODE_PRIVATE);
		Log.d("ff", sp.getInt("fontColor", 3333)+"");
		this.fontColor=sp.getInt("fontColor", Color.WHITE);
		this.fontSize=sp.getInt("fontSize", 18);
		this.backgroudColor=sp.getInt("backgroudColor", Color.BLACK);
		et.setTextColor(fontColor);
		et.setTextSize(fontSize);
		et.setBackgroundColor(backgroudColor);
	}

返回顶部
顶部