如何读取其他应用程序的 SharedPreferences(相同用户 ID)? [英] How to read other app's SharedPreferences (same user ID)?

查看:69
本文介绍了如何读取其他应用程序的 SharedPreferences(相同用户 ID)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Android 4.3 上测试.我有两个应用程序,com.my.app.firstcom.my.app.second.在我的活动中,我想从其他应用程序中读取首选项.我选择为我的两个应用使用相同的用户 ID:

Tested on Android 4.3. I have two apps, com.my.app.first and com.my.app.second. In my activity I want to read preferences from the other app. I chose to use the same user ID for both my apps:

android:sharedUserId="com.my.app"

我总是这样加载我的偏好:

I always load my preferences like this:

prefs = getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);

现在,在我的第二个应用中,我执行以下操作:

Now, in my second app I do the following:

try {
    Context context = createPackageContext("com.my.app.first", Context.CONTEXT_IGNORE_SECURITY);
    // context.getPackageName() does indeed return "com.my.app.first"

    // Note: Context.MODE_WORLD_READABLE makes no difference here!
    prefs = context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE);
}

prefs.mFile 错误地指向 /data/data/com.my.app.second/shared_prefs/MyAppPreferences.xml.

显然,调用 getSharedPreferences 返回当前应用的首选项,即使我使用了其他应用的上下文.我究竟做错了什么?请帮忙!

Obviously, the call to getSharedPreferences returns the preferences for the current app even though I used the context of the other app. What am I doing wrong? Please help!

推荐答案

发现问题!这确实看起来像是 getSharedPreferences API 中的一个错误.结果证明,对 getSharedPreferencesprevious 调用导致另一个 context.getSharedPreferences() 调用返回前一个实例 - 当前应用程序的首选项.

Found the problem! This sure looks like a bug in the getSharedPreferences API. It turned out that a previous call to getSharedPreferences caused the other context.getSharedPreferences() call to return the previous instance - the current app's preferences.

解决方案是确保 getSharedPreferences() 在读取其他应用的首选项之前被调用.

The solution was to make sure that getSharedPreferences() was NOT called before reading the preferences of the other app.

这篇关于如何读取其他应用程序的 SharedPreferences(相同用户 ID)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆