我有一个webview的问题,可以通过 HTML5
app访问localStorage . test.html文件通知我浏览器不支持本地存储(即 webview
) . 如果您有任何建议..
package com.test.HelloWebView;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class HelloWebView extends Activity {
WebView webview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new HelloWebViewClient());
webview.loadUrl("file:///android_asset/test.html");
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
webview.setWebChromeClient(new WebChromeClient() {
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(5 * 1024 * 1024);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class HelloWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
6 回答
在API级别19中不推荐使用setDatabasePath()方法 . 我建议您使用这样的存储区域设置:
如果您有多个webview,localstorage无法正常工作 .
两个建议:
使用java数据库代替webview localstorage " @Guillaume Gendre "解释 . (当然它对我不起作用)
本地存储工作就像json一样,所以值存储为"key:value" . 你可以将你的浏览器唯一ID添加到它的密钥并使用普通的android localstorage
如果您的应用使用多个webview,您仍会遇到麻烦:localStorage未在所有网络视图中正确共享 .
如果要在多个Web视图中共享相同的数据,唯一的方法是使用java数据库和javascript接口进行修复 .
This page在github上展示了如何做到这一点 .
希望这个帮助!
缺少以下内容:
重启应用程序后,我也遇到了丢失数据的问题 . 添加这有助于:
适用于我的Android 4.2.2的解决方案,使用构建目标Android 4.4W编译: