编辑:
我有一个应用程序可以写入SharedPreferences:
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("AfroKeyboard.com.rob", Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
}
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("PREFS_PRIVATE", Context.MODE_WORLD_READABLE);
Editor prefsPrivateEditor = sharedPreferences.edit();
prefsPrivateEditor.putString("layout02", jString);
prefsPrivateEditor.putString("layout02name", "Russian Layout");
prefsPrivateEditor.commit();
和另一个必须从中读取的应用
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("AfroKeyboard.com.rob", Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
}
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("PREFS_PRIVATE", Context.MODE_WORLD_READABLE);
Log.e( "name2" , "name2: "+sharedPreferences.getString("layout02name", "") );
但它返回空。
您认为可能是什么问题?
谢谢!
答案 0 :(得分:7)
您需要指定应用程序上下文。例如:
Context otherAppsContext = null;
try
{
otherAppsContext = createPackageContext("<YOUR_PACKAGE_NAME>", Context.MODE_WORLD_READABLE);
}
catch (NameNotFoundException e)
{
}
SharedPreferences prefs = otherAppsContext.getSharedPreferences("PREFS_FILE", Context.MODE_WORLD_READABLE);
String result = prefs.getString("PREFERENCE_TAG_NAME", "DEFAULT_VALUE");
通过这种方式,您可以阅读保存在文件中的共享偏好设置“PREFERENCE_TAG_NAME”的内容
/data/data/YOUR_PACKAGE_NAME/shared_prefs/<PREFS_FILE>.xml
您可以在不同的应用中执行此操作,但为此,“YOUR_PACKAGE_NAME”必须相同。
如果要更改任何应用中的值,则需要更改getSharedPreferences的模式 从:
Context.MODE_WORLD_READABLE
为:
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE"
答案 1 :(得分:2)
由于您要从其他软件包访问SharedPreferences,因此您需要使用Context.createPackageContext().getSharedPreferences()
代替this.getSharedPreferences()
答案 2 :(得分:1)
试试这个:
将SharedPreferences写为:
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("AfroKeyboard.com.rob", Context.CONTEXT_IGNORE_SECURITY);
}
catch (NameNotFoundException e) {
}
myPrefs = otherAppsContext.getSharedPreferences("NAME_OF_SHARED_PREFERENCES", Context.MODE_WORLD_READABLE);
Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("layout02", jString);
prefsEditor.putString("layout02name", "Russian Layout");
prefsEditor.commit();
将SharedPreferences读取为:
myPrefs = otherAppsContext.getSharedPreferences("NAME_OF_SHARED_PREFERENCES", Context.MODE_WORLD_READABLE);
String s = myPrefs.getString("layout02name", "") );
答案 3 :(得分:0)
到目前为止,这是我设法使这项工作的方式。
String packageName ="com.yourpackage.yourname"
Context otherAppsContext = null;
try
{
otherAppsContext = createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "will crash", 3).show();
}
SharedPreferences prefsother = otherAppsContext.getSharedPreferences(keyPackageName, Context.MODE_WORLD_READABLE);
String key = prefsother.getString("key", "defValue");//use prefs normally here