在Android中,可以使用SharedPreferences来实现数据的共享偏好。以下是一个示例代码:
SharedPreferences sharedPref = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "value");
editor.putInt("key", 123);
editor.putBoolean("key", true);
editor.apply(); // 或者使用editor.commit();
String stringValue = sharedPref.getString("key", "default value");
int intValue = sharedPref.getInt("key", 0);
boolean booleanValue = sharedPref.getBoolean("key", false);
在这个示例中,我们使用名为"MyPref"的SharedPreferences文件进行数据的存储和读取。可以使用不同的文件名来创建多个SharedPreferences文件,以实现不同的数据共享偏好。
需要注意的是,commit()方法会阻塞UI线程,而apply()方法是异步的,不会阻塞UI线程,所以一般推荐使用apply()方法来提交修改。