比如在包名为com.teleca应用程序A中有一个名叫com.teleca_prefer的Preferences:
java代码:
final static String preferName="com.teleca_prefer";
final static String KEY_TIP="tip";
prefsWorldRead = getSharedPreferences(preferName, Context.MODE_WORLD_READABLE);
Editor prefsWorldReadEditor = prefsWorldRead.edit();
prefsWorldReadEditor.putString(KEY_TIP, "Are you fine?");
prefsWorldReadEditor.commit();
我们可以在包名为com.teleca.robin应用程序B中这样读取它:
java代码:
private SharedPreferences prefsWorldRead;
final static String preferName="com.teleca_prefer";
final static String KEY_TIP="tip";
if(prefsWorldRead ==null) {
Context otherContext=null;
try {
otherContext =createPackageContext("com.teleca", Context.CONTEXT_IGNORE_SECURITY );
} catch (NameNotFoundException e) {
e.printStackTrace();
}
prefsWorldRead = otherContext.getSharedPreferences(preferName, Context.MODE_WORLD_READABLE);
}
String tip=prefsWorldRead.getString(KEY_TIP, "null2");
createPackageContext为Context的方法,"com.teleca"为A应用程序的包名,"com.teleca_prefer"为你要读取的A应用程序的Preferences名字。
本文介绍了如何在一个应用程序中创建并编辑Preferences,然后在另一个应用程序中读取它,前提是要设置正确的权限。通过使用getSharedPreferences和edit方法,可以实现跨应用的数据共享。

973

被折叠的 条评论
为什么被折叠?



