我正在尝试在第一个APP上使用SharedPreferences保存一些键,然后在初始化第二个APP时加载它们。 它适用于模拟器,但不适用于设备(Android 4.0.3)
这是我在第一个APP上的代码:
private SharedPreferences gameSaved;
private SharedPreferences.Editor editor;
gameSaved = getApplicationContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
int value = 10;
editor = gameSaved.edit();
editor.putInt("value_0", value);
editor.commit();
然后在第二个APP上我得到了这样的键值:
try{
con = getApplicationContext().createPackageContext("com.example.firstapp", 0);
} catch (NameNotFoundException e) {
}
SharedPreferences pref = con.getSharedPreferences(PREFS_NAME, Context.CONTEXT_IGNORE_SECURITY);
int value = pref.getInt("value_0", -1);
在清单上,两个APP共享此行:
android:sharedUserId="com.example.shared"
我检查了SharedPreferences文件是否已正确创建和定位。 最奇怪的是它在模拟器上运行得很好。 请帮忙,我的想法已经用完了。
答案 0 :(得分:0)
我终于可以解决它,但我没有任何技术解释。
以前我在两个APP上都有相同的文件名:
SharedPreferences pref = con.getSharedPreferences(FILE_NAME, Context.CONTEXT_IGNORE_SECURITY);
它没有多大意义,因为这些文件存储/保存在不同的APP数据文件夹中,但如果它们共享相同的SharedPreferences文件名,那么它就不会起作用(至少对于我)。