Home » Android » android – Opening WebView in background

android – Opening WebView in background

Posted by: admin June 15, 2020 Leave a comment

Questions:

This is the first time I ask something, so if there is something wrong just tell me and I´ll try to fix it ASAP.

We have a customer that wants us to login in their servers with a native Android app, but without giving us a custom way to do this. They want us to use the current website they have to log and, after authentication takes place, retrieve within the browser a XML which contains the data we need. After that, use the data in the native app. All of this with the user not knowing/seeing that a browser is being used. A total mess IMHO.

Of course, I have never tried this approach in the past and my first tests make me feel like this is impossible (or extremely difficult) to achieve. Whenever I try to load the URL in a hidden WebView the default browser pops up showing the website.

My main question is, is it possible to load a webview and work with it (invoke javascript, etc…) in the background?

Thank you.

How to&Answers:

You could set the WebView to hidden by default with the attribute android:visibility=”gone”, interact with it at runtime then when you need to show it to the user after you’ve loaded data, just call setVisibility(View.VISIBLE)

Hope this helps!

Answer:

Ofc, you must to use a Thread :

protected void getPage(){
    Thread th = new Thread(){

        public void run(){

            //Download and make things



            mActivity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    //print int the activity

                }
            });
        }
    };

    th.start();

Remember, and thats is VERY important, you CANT draw from thread to the main activity. The only who can draw in the screen is the main activity. You can draw with 2 methods:

One , with the method _mActivity.runOnUiThread(new Runnable() {_ like the example i put.
Two, use a Handler to send messages from thread to main activity with the information that you want to draw.

*Main activity is the activity that its in the screen in that moment, not the first activity of the app