您的位置:首页 > Web前端

读写其他应用程序的sharedpreferences

2016-06-18 09:29 399 查看

正在学习读写其他应用程序的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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android