读取其他程序的sharedpreference

I:访问本程序的(FirstApp)SharedPreferences中的数据代码如下:

 

Java代码
SharedPreferences sharedPreferences = getSharedPreferences("first_app_perferences", Context.MODE_PRIVATE);  
String name = sharedPreferences.getString("name""");  //getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值 
int age = sharedPreferences.getInt("age"1);  

 

II:访问其他应用中的Preference(在SecondApp中访问FirstApp的数据),前提条件是:FirstApp的preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。

如:在<package name>为com.first.app的应用使用下面语句创建了preference("first_app_perferences")。

Java代码
getSharedPreferences("first_app_perferences", Context.MODE_WORLD_READABLE);  

 

在SecondApp中要访问FirstApp应用中的preference,首先需要创建FirstApp应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :

Java代码
Context firstAppContext = createPackageContext("com.first.app", Context.CONTEXT_IGNORE_SECURITY);   
SharedPreferences sharedPreferences = firstAppContext.getSharedPreferences("first_app_perferences",  Context.MODE_WORLD_READABLE);   
String name = sharedPreferences.getString("name""");  
int age = sharedPreferences.getInt("age"0);  

 

如果不通过创建Context访问FirstApp应用的preference,可以以读取xml文件方式直接访问FirstApp应用的preference对应的xml文件,

如: 
File xmlFile = new File(“/data/data/<package name>/shared_prefs/first_app_perferences.xml”);//<package name>应替换成应用的包名: com.first.app

 
原文地址:https://www.cnblogs.com/jyx140521/p/2855960.html