Widget that retrieve data from several html pages

偶尔善良 提交于 2019-12-25 02:44:05

问题


I retrieve some data from html after several step (login, click on link, run javascript, etc.) using webview, like described here: how to get html content from a webview? putting more actions in cascade. I don't use thread, mainly when an action (login for example) is done, it's called onPageFinished and this fire another webview.loadUrl and so on to another onPageFinished till all the actions are executed.

I want to create a widget that show this result, that fire this chain of webview.loadUrl when the widget refresh button is pressed or every day at 12AM. Only after that all the chain is completed, the result can be showed in the widget.

I've read some tutorials, and I saw that there're different approach, TimerTask, Service, Broadcast receiver, ect., but I didn't understand which fit to my project. I don't know if my explaination was clear, but in the onUpdate of the widget, I shoud start the webview.loadUrl sequence, but I can't return anything until the last onPageFinished is called.

This is what I mean for chain action, urlChain is a static string LinkedList with the sequence of URLs (and other stuff).

@SuppressLint("SetJavaScriptEnabled")
private void callChain()
{
    /* WebViewClient must be set BEFORE calling loadUrl! */
    browser.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            /* This call inject JavaScript into the page which just finished loading. */
            if (!urlChain.isEmpty())
            {
                callChain();
            }
        }

    });

    /* load a web page */
    if (!urlChain.isEmpty())
    {
        String currentUrl;
        currentUrl = urlChain.pop();
        browser.loadUrl(currentUrl);
    }
}

回答1:


It is probably a good idea to perform the background work on a Service or some other independent structure, fireing an update to the widget or performing an direct update on all widgets afterwards, which then causes the fresh data to get displayed.


Without knowing anything about your exact project, the cleanest way would probably be a SyncAdapter, peforming the synchronization in the background and updating a ContentProvider which can then get used when updating the widget.

However this may be overkill (you need to register a sync account in the system, etc), depending on your actual needs. You could as well just have a Service the widget may request an update on, which then fires an update using the same technique once it finished loading.

Oh, and if you're bound to exactly 12 AM, have a look at AlarmManager.



来源:https://stackoverflow.com/questions/20826704/widget-that-retrieve-data-from-several-html-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!