Android:如何保存附加了 addJavascriptInterface 的 WebView 的状态?

发布于 2024-10-12 14:45:06 字数 1252 浏览 6 评论 0原文

我有一个 android WebView,它有一个使用 addJavajavascriptInterface() 添加的 JavaScript 接口。

是否可以保存WebView的状态(网页状态,html,css,javascript),然后在onCreate上恢复它?如果是,怎么办?

到目前为止我的代码一直崩溃:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        final WebBackForwardList list = mWebView.restoreState(savedInstanceState);
        if (savedInstanceState.containsKey("currentPicture")) {
            final File f = new File(savedInstanceState.getString("currentPicture"));
            mWebView.restorePicture(savedInstanceState, f);
            f.delete();
        }
    } else {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidApp");
        mWebView.loadUrl(url);
    }
}

public void onSaveInstanceState(Bundle outState) {
    final WebBackForwardList list = mWebView.saveState(outState);
    File mThumbnailDir = getDir("my-thumbnails", 0);
    if (list != null) {
        final File f = new File(mThumbnailDir, mWebView.hashCode() + "_pic.save");
        if (mWebView.savePicture(outState, f))
        outState.putString("currentPicture", f.getPath());
    }
}

I have an android WebView that has a JavaScript interface added with addJavajavascriptInterface().

Is it possible to save the state of the WebView (webpage state, html, css, javascript) and then restore it on onCreate? If yes, how?

The code I have so far keeps crashing:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        final WebBackForwardList list = mWebView.restoreState(savedInstanceState);
        if (savedInstanceState.containsKey("currentPicture")) {
            final File f = new File(savedInstanceState.getString("currentPicture"));
            mWebView.restorePicture(savedInstanceState, f);
            f.delete();
        }
    } else {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidApp");
        mWebView.loadUrl(url);
    }
}

public void onSaveInstanceState(Bundle outState) {
    final WebBackForwardList list = mWebView.saveState(outState);
    File mThumbnailDir = getDir("my-thumbnails", 0);
    if (list != null) {
        final File f = new File(mThumbnailDir, mWebView.hashCode() + "_pic.save");
        if (mWebView.savePicture(outState, f))
        outState.putString("currentPicture", f.getPath());
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文