在多个安卓应用之间共享数据

3
我正在为Android编写一个SDK,将被许多不同的应用程序使用。每个应用程序都需要知道是否有另一个使用该SDK的应用程序的先前安装;第一个应用程序将创建一个随机id(一个cookie)并存储它,所有后来的应用程序都必须读取它并重复使用它。请注意,每个设备都会重新创建cookie。
我已经搜索了很长时间才找到答案;在回答之前请仔细阅读,因为我已经阅读了许多不同的StackOverflow答案,并且搜索了互联网上的随机博客;我尝试了很多方法,但没有一种方法有效(我将为您保存链接)。
  • A ContentProvider is definitely overkill. Also it needs to intrude an app's AndroidManifest.xml, something I am trying to avoid.
  • Likewise for a service: needs to be defined in the AndroidManifest.xml, which I do not control and do not want to require changes to.
  • Using external storage would perhaps be an option, but I don't want to require additional permissions.
  • Using SharedPreferences directly with getSharedPreferences() does not work because apps can only access their own preferences.
  • I can get a common preferences object using createPackageContext(package, MODE).getSharedPreferences(). This would work beautifully if I had a main package and many clients of the data, but in fact I don't know the package of the app that will be installed first -- it can be any of them. I don't even have a list of package names to search. Passing a package name which has not been installed fails.
  • Following the approach above, I have tried to piggyback on some standard Android app which I can count on, and store my preferences there -- say:

    createPackageContext(
        "com.android.browser",
        Context.CONTEXT_RESTRICTED)
        .getSharedPreferences(
            "GLOBAL_PREFS",
            Context.MODE_WORLD_READABLE);
    

    but it does not work: the error reads

    Couldn't create directory for SharedPreferences file
      /data/data/com.android.browser/shared_prefs/GLOBAL_PREFS.xml
    
因此,简而言之:我需要将一段数据(一个简短的字符串)存储在某个标准位置,以便任何其他应用程序可以在那里读取它(如果有),并且最好不要在AndroidManifest.xml中进行任何魔法或请求任何权限。可能没有完美的答案,所以也许最好的解决方案是写入外部存储器;这样做可以让事情更具上下文性,显然,在iOS上使用钥匙链存储安全数据是微不足道的。

我只想为其他可能遇到这个问题的人提供帮助,调用另一个包的上下文中的getSharedPreferences(...)是非常糟糕的想法。Android使用SharedPreferences对象的缓存,仅由首选项文件名键入,并且不考虑包。换句话说,除非您从未使用任何上下文而仅使用自己的上下文,否则绝对不能保证您获得的SharedPreferences实际上对应于您正在调用的包上下文。 - j__m
1个回答

2
很遗憾,我不知道有什么很好的答案。您已经提出了自己的选择方案并且使用外部存储可能是最好的方法。
为了提供一些可能的解决方案,您可以使用一个具有固定名称和全局可读(可能是可写)权限的平面文件。然后,您需要遍历所有应用程序目录并检查每个文件夹中是否存在这个已知命名的文件,并尝试打开它。
虽然这在理论上可能有效,但请考虑包含“cookie”的应用被卸载的情况。然后您将没有cookie。因此,您可能需要在每个应用程序中创建cookie,并将先前cookie的值复制到新cookie中。
我实际上还没有尝试过这个方法,但我想它应该可以工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接