保存在 SharedPreferences 中从 JavascriptInterface 在 webview 中返回的值

Save in SharedPreferences value returned from JavascriptInterface in webview

我认为这是一个 Context 问题,但我想不通。

我正在使用 JavascriptInterface 界面从 webview 检索用户 ID。我正在使用 WebAppInterface class 检索值并将其保存在 sharedprefs 中。我可以测试 returned 值,没问题。当我从 WebAppInterface 中拉出它时,它保存在 SharedPreferences 中,但是当我尝试在另一个 activity 中检索它时,检索到的值是默认值。

网络视图activity:

public class Login extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
        myWebView.loadUrl("mydomain.com/retrieveid"); //here I use the real url
    }
 ...
}

WebAppInterfaceClass

public class WebAppInterface {
    Context mContext;
    SharedPreferences mPrefs;
    WebAppInterface(Context c) {
        mContext = c;
        mPrefs = c.getSharedPreferences("My_Prefs", 0);
    }

    @JavascriptInterface
    public void returnUserID(String uid) {
        Editor editor = mPrefs.edit();
        editor.putInt("uid", Integer.valueOf(uid));
        editor.commit();
        Integer uid2 = mPrefs.getInt("uid", 0);
        Log.i("uid after update", String.valueOf(uid2)); //this value is correct
        Intent intent = new Intent(mContext, MainActivity.class);
        mContext.startActivity(intent);
   }
}

然后在 MainActivity.class 我尝试用 getSharedPreferences("My_Prefs", 0).getInt("uid",0); 检索这个值,它总是 return 0.

[已更新]

场景 1 - 2 个活动在不同的应用程序中

当调用 getSharedPreferences(String name, int mode) 时,mode 参数确定存储的值是私有的,还是全局可读的 and/or 可写的。

MODE_PRIVATE(其值为 0)可能是您在最初存储数据的应用程序中使用的。这意味着没有其他应用程序可以访问该数据。

您应该知道,自 API 级别 17 以来,其他模式已被弃用,因为它们会打开安全漏洞。

您应该考虑让第一个应用实现 ContentProvider or Service 来提供共享数据。

场景 2 - 2 个活动在同一个应用程序中,但在不同的进程中

参考 this question and its accepted answer. Please note, though, that MODE_MULTI_PROCESS 在 API 级别 23 中被弃用,因为它在某些版本的 Android 中不能可靠地工作,并且不会尝试协调跨进程的并发修改。

您应该考虑实施 ContentProvider 或 Service 来提供共享数据。对于非常简单的数据,FileProvider(文件的 ContentProvider)可能就足够了。

  1. 基本上不要在 SharedPreferences 中的活动之间传递值,这就是 Intent Extras 的用途。

粗略的思路是:

Intent intent = new Intent(mContext, MainActivity.class);
intent.putExtra("uid", uid);
mContext.startActivity(intent);

然后在 MainActivity

getIntent().getIntExtra("uid", -1);

将return你的价值或-1

  1. 您从应用程序内部使用 Intent 触发 MainActivity 有点奇怪,这让我觉得您实际上应该使用 startActivityForResult 启动当前 activity:http://developer.android.com/training/basics/intents/result.html