2013-11-22 70 views
2

我有一個PhoneGap應用程序,我使用HTML5 LocalStorage,因此保存用戶數據(如用戶令牌,用戶名等)。從PhoneGap升級到本機

事情是,最近我們決定從PhoneGap轉移到原生Android應用程序。但有一件事我需要解決:

是否有可能使用java代碼從HTML5 LocalStorage獲取數據?我們不希望用戶在更新後註銷,所以我需要一種方法從LocalStorage中獲取用戶令牌並將其保存在SharedPreferences中。

在此先感謝!

回答

0

普拉卡什向我指出正確的方向,但也有一些東西丟失:

public class MyJavaScriptInterface { //the class and the callbacks must be public 
    @JavascriptInterface //this is needed for android 4.2 and above 
    public void someCallback(String jsResult) { 
     // this will be passed the local storage name variable 
    } 
} 

有一些設置來配置web視圖:

public void importPhoneGapUser() { 
    String databasePath = getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 
    String pathToCache = getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 

    WebView mAuthWebView = new WebView(this); 
    WebSettings webSettings = mAuthWebView.getSettings(); 

    webSettings.setDatabasePath(databasePath); 
    webSettings.setAppCachePath(pathToCache); 
    webSettings.setGeolocationDatabasePath(databasePath); 

    webSettings.setAppCacheMaxSize(5 * 1048576); 

    webSettings.setAppCacheEnabled(true); 
    webSettings.setDatabaseEnabled(true); 
    webSettings.setJavaScriptEnabled(true); 
    webSettings.setDomStorageEnabled(true); 

    mAuthWebView.addJavascriptInterface(new MyJavaScriptInterface(), "JsInterface"); 

    //i wasn't able to run JS through 'javascript:' protocol, so i had to use a HTML file 
    mAuthWebView.loadUrl("file:///android_asset/import_auth.html"); 
} 

希望這會幫助別人一天

1

這是可能的。爲了執行JavaScript,並得到響應,你可以做如下:

定義JavaScript回調接口代碼:

class MyJavaScriptInterface { 
public void someCallback(String jsResult) { 
    // this will be passed the local storage name variable 
} 
} 

附加此回調到您的WebView:

MyJavaScriptInterface javaInterface = new MyJavaScriptInterface(); 
webView.addJavascriptInterface(javaInterface, "HTMLOUT"); 

Run your JavaScript calling window.HTMLOUT.someCallback from the script: 

webView.loadUrl("javascript:(function() { var name = window.localStorage['name']; 
window.HTMLOUT.someCallback(name); })()");  

注 - window.localStorage ['name']與window.localStorage.getItem('name')相同

這個帖子在stackoverflow上幫我

您可能需要使用super.webView.addJavascriptInterface或super.addJavascriptInterface來添加接口。您可能需要使用super.webView.loadUrl或super.loadUrl來調用它。這一切都取決於你將從哪裏調用。