SharedPreferences 共享数据
在做项目的时候,不想把项目做的很复杂,而又要把功能实现,
例如:A应用提供设置接口,及实现。 数据很自然的保存到 A 应用里面了。
而这个数据又要提供给另外的应用 B 用,为把把程序写的尽量简单,所以
用SharedPreferences 来保存数据了。
A 这边的写法跟一般的写法一样。
public static final String CALL_RECORD_SHARE = "record_share";
SharedPreferences sharedPreferences = context.getSharedPreferences(CALL_RECORD_SHARE, Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("record","no");
editor.apply();
editor.commit();
B应用访问A应用中的 SharedPreferences 数据 设置A 应用的包名为:com.android.phone
Context otherAppContext = null;
SharedPreferences sharedPreferences = null;
try{
otherAppContext = mContext.createPackageContext("com.android.phone", Context.CONTEXT_IGNORE_SECURITY);
sharedPreferences = otherAppContext.getSharedPreferences("record_share", Context.MODE_WORLD_READABLE | Context.MODE_MULTI_PROCESS);
}catch(Exception e){
e.printStackTrace();
}
// 下面是功能实现
if(null != sharedPreferences){
if("yes".equalsIgnoreCase(sharedPreferences.getString("record", "no"))){
CallCommandClient.getInstance().startVoiceRecording();
}
Log.d(this, "dxy_ sharedPreferences " + sharedPreferences.getString("record", "noss"));
}else{
Log.d(this, "dxy_ sharedPreferences have value");
}
当然还有一种更为简单的方法 是 ShareID 不过 ,这里就不写了。希望对有需要的人有所帮助!