类似iOS的NSUserDefaults,采用key-value(键值对)形式,主要用于轻量级的数据存储
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
//存 SharedPreferences.Editor editor = getSharedPreferences("personInfo",MODE_PRIVATE).edit(); editor.putString("name","zhangsan"); editor.putInt("age",18); editor.putBoolean("married",false); editor.apply();
//读 SharedPreferences preferences = getSharedPreferences("personInfo",MODE_PRIVATE); String name = preferences.getString("name",""); int age = preferences.getInt("age",0); boolean married = preferences.getBoolean("married",false); Log.d(TAG, "onCreate: " + name); Log.d(TAG, "onCreate: " + age); Log.d(TAG, "onCreate: " + married);
} } |