读写其他应用程序的sharedpreferences

来源:互联网 发布:java 基础 代码 编辑:程序博客网 时间:2024/05/16 11:40

正在学习读写其他应用程序的sharedpreferences,所以把想到的东西在这儿再梳理一下吧。

首先,要读取其他应用的sharedpreferences,前提是创建该sharedpreferences的应用程序指定该访问权限是 MODE_WORLD_READABLE,或者是 MODE_WORLD_WRITABLE.前者是在其他应用程序中只读,后者是在其他应用程序中可读可写。
第二就是,获取其他程序的sharedpreference对应的CONTEXT,代码如下

try {Context mcontext= createPackageContext("com.example.mpreferences",CONTEXT_IGNORE_SECURITY);                } catch (PackageManager.NameNotFoundException e) {                    e.printStackTrace();                }

其中,”com.example.mpreferences”是其他应用程序的包名,包名即是一个应用程序的标识。CONTEXT_IGNORE_SECURITY是一个flag,忽略安全性。
第三,利用Context 的mcontext.getSharedPreferences(“wshuang_preference”,MODE_PRIVATE)来获取对应的sharedpreference。
第四就是正常读取了。

try { Context mcontext = createPackageContext("com.example.mpreferences", CONTEXT_IGNORE_SECURITY); SharedPreferences msharedpreferences = mcontext.getSharedPreferences("wshuang_preference", MODE_PRIVATE); int count = msharedpreferences.getInt("count", 0);      } catch (PackageManager.NameNotFoundException e) {                    e.printStackTrace();                }
1 0
原创粉丝点击