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

时间:2015-09-11 16:46:06

标签: android webview sharedpreferences android-context

我认为这是一个Context问题,但我无法理解。

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

webview活动:

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);检索此值,它总是返回0.

2 个答案:

答案 0 :(得分:1)

[更新]

场景1 - 这2项活动位于不同的应用程序中

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

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

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

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

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

请参阅this question及其接受的答案。但请注意,{23}在API级别23中已弃用,因为它在某些Android版本中无法可靠地运行,并且不会尝试协调跨进程的并发修改。

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

答案 1 :(得分:1)

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

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

    然后在MainActivity中

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

    将返回您的值或-1

    1. 你在应用程序内部使用Intent触发MainActivity有点奇怪,这让我觉得你应该用startActivityForResult开始当前的活动:http://developer.android.com/training/basics/intents/result.html