共享preferences交叉应用

共享preferences交叉应用

本文介绍了共享preferences交叉应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个应用程序应用程序1( com.mine.app1 ),其中我已经声明了一个共享preference

 共享preferences controlinfo = getShared preferences(销code,MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
共享preferences.Editor编辑= controlinfo.edit();editor.putString(销code,DDDD);
editor.commit();

我有一个应用程序2( com.mine.app2 )中,我试着读出共享preference 从应用程序1。

在这里,我有以下的code(下一个按钮的onclick):

 上下文CON = createPackageContext(com.mine.app1,0);
共享preferences INTERAL preF = getShared preferences(销code,MODE_PRIVATE);应用程序2(这个程序)的//共享preF
共享preferences外部preF = con.getShared preferences(销code,MODE_PRIVATE); //应用1的共享preF
//注意:MODE_PRIVATE无所谓字符串internalPin code = INTERAL pref.getString(销code,无);
字符串externalPin code =外部pref.getString(销code,无);

在这种情况下,我得到 internalPin code externalPin code 无。

然而,当我改变的顺序 getShared preference

 上下文CON = createPackageContext(com.mine.app1,0);
共享preferences外部preF = con.getShared preferences(销code,MODE_PRIVATE); //应用1的共享preF
共享preferences INTERAL preF = getShared preferences(销code,MODE_PRIVATE);应用程序2(这个程序)的//共享preF字符串internalPin code = INTERAL pref.getString(销code,无);
字符串externalPin code =外部pref.getString(销code,无);

我这种情况下,我得到两个 internalPin code externalPin code DDDD (这是在应用程序1中设定的值( com.mine.app1 ))

我希望 internalPin code 将返回none和 externalPin code DDDD 在这两个情况。

为什么不呢?


解决方案

This is not a great idea. The user can get rid of Application 1 whenever they wish, at which point Application 2 can no longer get at this data.

Instead, use a synchronization model. Have Application 1 send out a broadcast Intent when preferences change, with an attached signature-level permission so only Application 2 (or any others that you write) can receive it. Application 2 can then update its own local data store (e.g., its own SharedPreferences). Application 2 can do the same, allowing the user to modify its copy of the preference data and sending out the broadcasts to let the other application(s) know. That way, if any one application is removed, the other application(s) do not lose their preference data, yet everything can remain in sync.

这篇关于共享preferences交叉应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:15