Home » Android » android – Running WebView in Background

android – Running WebView in Background

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am developing an application which utilizes a WebView to sign into a website, pull content from it, then notify the user when content is updated. I have gotten the WebView to get the content however I need to know how I can run the WebView as Service in order to get it to run in the background.

As I understand, WebViews must be manipulated from the UI thread which makes things a whole lot harder.

Any suggestions/workarounds as to how I can get the app to notify the user regardless of whether they have the app open or not?

How to&Answers:

While WebViews need to be manipulated on a single thread it doesn’t necessarily need to be the UI thread (unless you want to attach the WebView to the view hierarchy), however it needs to be the same thread for all of the WebViews.

While it’s not something explicitly supported (or heavily tested) there is nothing special that the WebView does to prevent you from running it in a Service. The WebView does call a couple of methods on the Context that don’t normally work in a Service (like getTheme()), so you’d have to work around that with a ContextWrapper. You’ll also need to manually call WebView.layout to trick the WebView into thinking it has a size. There might be more stuff you’d need to do, but nothing else comes to mind.

Answer:

You mean that?

runOnUiThread(new Runnable(){
        public void run() {
            ... something 
        }
    });

Answer:

You cannot inflate or modify any view from background thread. But if you want the content of a web page, you can fetch it in a background thread using HTTP GET. You need to use GET on the url to get its HTML data.

Answer:

It will check if it is possible to have a WebView instance running and control it programmatically to load a page without it having to occupy the screen during page loading. Then when you know you have material loaded I will want to switch to its display in an instant. I will do some testing to see if it can be done on mobile devices.