【问题标题】:webview, using loadData at onResume loses historywebview,在 onResume 使用 loadData 会丢失历史记录
【发布时间】:2015-08-07 21:00:07
【问题描述】:

我有这个应用程序可以在 web 视图中阅读文章。刚启动ArticleActivity的时候,网页的html其实是下载成字符串解析成手机网站的,然后我用wb.loadData(html, "text/html; charset=UTF-8", null);。下载发生在异步任务中,因为我无法在 ui 线程上进行 Internet 活动,但现在,每当单击页面上的链接时,它只是默认为 loadUrl() 根据 webviewclient。我可以在历史上使用goBack(),没问题。

问题在于搜索栏小部件。我调用 SearchResultsActivity,它会打开一个 web 视图并加载一个 url。当用户点击一篇文章时,SearchResultsActivity 通过一个意图将它发送回 ArticleActivity。问题是我想使用loadData() 作为新文章链接,我尝试在onResume() 中这样做,但如果我仍在先前加载的页面上,则不会发生任何事情。日志语句显示来自EXTRA_RETURN_RESULT 的Url 确实成功了,所以我认为意图是好的。我认为这是由于javascript“同源”的事情,所以这就是为什么如果我使用loadDataWithBaseURL(),页面会加载。但是如果我现在尝试返回按钮,之前加载的页面是空白的!加载新页面时如何保存历史记录?

class SearchWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // if it is morning sign out AND is an article, send url to ArticleActivity
        if(Uri.parse(url).getHost().endsWith("morningsignout.com")) {
            Intent intent = new Intent(view.getContext(), ArticleActivity.class);
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, url); // Put url in intent
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // Open w/ old articleActivity if exists
            view.getContext().startActivity(intent);
            return true;
        }

//        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//        view.getContext().startActivity(intent);
        return false;
    }
}

来自文章活动

@Override
protected void onResume() {
    super.onResume();

    // URL from CategoryActivity
    String intentURL = getIntent().getStringExtra(Intent.EXTRA_HTML_TEXT);

    // Set webView to new article
    if (intentURL != null) new URLToMobileArticle(webView).execute(intentURL);
    else {
        // If statement is reached, then intent originated from SearchResultsActivity
        intentURL = getIntent().getStringExtra(Intent.EXTRA_RETURN_RESULT);
        new URLToMobileArticle(webView).execute(intentURL);
        Log.d("ArticleActivity", "Loading: " + intentURL);
    }
}

URLToMobileArticle是什么,getArticles()是下载/解析函数:

public URLToMobileArticle(WebView webview) {
    this.wb = webview;
}

@Override
protected String doInBackground(String... params) {
    return getArticle(params[0]);
}

@Override
protected void onPostExecute(final String html) {
    wb.loadData(html, "text/html; charset=UTF-8", null);
    // wb.loadDataWithBaseURL(link, html, "text/html; charset=UTF-8", null, null);
    Log.d("URLToMobileArticle", "Loaded webpage");
}

【问题讨论】:

    标签: android html webview browser-history


    【解决方案1】:

    答案是我可以使用 shouldInterceptRequest() 来始终以我认为合适的方式加载 html。我只需要确保我可以区分网页 url 和其他请求,如图像或样式表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      相关资源
      最近更新 更多