• 读取其他程序的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

     
  • 相关阅读:
    恭喜你,你毕业了
    用VB.Net2008制作安装程序详细步骤(菜鸟级别,高手勿进)
    交通标志结构计算软件开发进程
    【工作笔记002】在TC中建立应用于出行分布的阻抗矩阵(最短路矩阵)
    VB.Net 2008 引用Excel12
    开博,开播。
    【推荐】万物兴歇——衰老与寿命的演化
    一张交叉口渠划的彩色平面图
    萦绕在头脑中的思路_我的编程梦们 【更新至2010.06.03】
    8月份的回顾
  • 原文地址:https://www.cnblogs.com/jyx140521/p/2855960.html
Copyright © 2020-2023  润新知