How to load url in webview in background while splashscreen is showing?

12,025

Solution 1

You can do it without AsyncTask and you can hide the splash screen when the page loaded without a timer.

WebViewClient class has a method onPageFinished() which will be called once the page has been loaded. You can make use of it.

In you project folder, place your splash screen images with name 'splash_screen.png' (or whatever name you want. If you want to use a different name then change this line webView.setBackgroundResource(R.drawable.splash_screen); to map to your splash screen image file) under res/drawable-xxx with corresponding resolutions.

For Eg: I followed these resolutions for my app's splash screen.

hdpi - 400x800
ldpi - 240x320
mdpi - 320x480
xdpi - 640x960

And try this code:

public class MainActivity extends Activity {
    final Activity activity = this;

    private WebView webView;

    private boolean isSplashOn = false;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView);

        webView.setBackgroundColor(0);
        webView.setBackgroundResource(R.drawable.splash_screen);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.getSettings().setAppCacheEnabled(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setPluginsEnabled(true);
        webView.getSettings().setPluginState(PluginState.ON);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);

        webView.setWebViewClient(new MyWebClient());

        webView.loadUrl("http://www.google.com");
    }

    public class MyWebClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);

            if(url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);

                return true;
            }

            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if(!isSplashOn) {               
                webView.setBackgroundDrawable(null);
                webView.setBackgroundColor(0);

                isSplashOn = true;
            }

            super.onPageFinished(view, url);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(webView.canGoBack()) {
                webView.goBack();

                return true;
            }else {
                activity.finish();
            }
        }

        return super.onKeyDown(keyCode, event);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY" />

</LinearLayout>

EDIT:

By the way i found the issue with your code. You are trying to set the splash screen to the webview before instantiating it.

Change your code from this:

webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);

webview = (WebView)findViewById(R.id.output);

to this:

webview = (WebView)findViewById(R.id.output);

webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);

Solution 2

You can use the simple trick - I was showing a loading spinner till the page was being loaded in background. Thus I had used two web views. In your case, you can use ImageView or any other view.

XML file will like this -

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

//Actual webview
    <WebView
        android:id="@+id/actual_webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

//Any view you want to show while webpage is loading
    <WebView
        android:id="@+id/spinner_webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
...
</RelativeLayout>

Now, in your JAVA file-

//initially, make actual_webview invisible
        actual_webview.setVisibility(View.INVISIBLE);

Also, in

     @Override
        public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);

// make spinner_webview invisible
    spinner_webview.setVisibility(View.INVISIBLE);

// make actual_webview visible
    actual_webview.setVisibility(View.VISIBLE);
    }

Also,

shouldOverrideUrlLoading(...)
onPageStarted(...)
onPageFinished(...)

In all these methods, you get the URL and can check which URL is being loaded or finished loading. According to the URL you can decide whether to show / hide the splash screen.

Solution 3

Why does the splash has to be an activity?

You can make it a full screen ImageView in the bottom of your layout and hide it using a handler:

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (isDestroyed())
                return;
            mSplashView.setVisibility(View.GONE);
        }
    },2000);    
Share:
12,025
Krishna
Author by

Krishna

Always a very enthusiastic student who want to learn everything in short time. Self analyzer, short tempered. I accept changes in life and can take everything as a challenge. Very ambitious

Updated on June 04, 2022

Comments

  • Krishna
    Krishna almost 2 years

    This is my splashscreen activity.

    public class Splash extends Activity {
      private static int SPLASH_TIME_OUT=10000;
      protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        Timer r=new Timer();
        new Handler().postDelayed(r,SPLASH_TIME_OUT);
      }
    
      class Timer implements Runnable{
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Intent i=new Intent(Splash.this,MainActivity.class);
            startActivity(i);
            finish();
        }
    
      }
    }
    

    This is my MainActivity. This activity Should be performed in background while splashscreen is on the front. Is it advisable to use AsyncTask. How to do that?

    If not AsyncActivity, What can I use?

    public class MainActivity extends Activity {
      private WebView webview;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_main);
    
        webview = (WebView)findViewById(R.id.output);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setLoadsImagesAutomatically(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setAppCacheEnabled(false);
    
        webview.setWebViewClient(new WebViewClient(){
    
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                if(url.startsWith("tel:")) { 
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url)); 
                    startActivity(intent); 
                    return true;
                }
                return false;
    
            }
        }
                );
        webview.loadUrl("http://www.example.com");
      }
        //this is to go back to previous pages if exists
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_DOWN){
                switch(keyCode)
                {
                case KeyEvent.KEYCODE_BACK:
                    if(webview.canGoBack()){
                        webview.goBack();
                    }else{
                        finish();
                    }
                    return true;
                }
    
            }
            return super.onKeyDown(keyCode, event);
        }
    }
    

    If possible can I set the time for the splashscreen to view as long as the url is loaded without giving time?

    The second attempt

    public class MainActivity extends Activity {
    WebView webview;
    private boolean isSplashOn = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_main);
    
        webview.setBackgroundColor(0);
        webview.setBackgroundResource(R.drawable.activity_splash);
    
        webview = (WebView)findViewById(R.id.output);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setLoadsImagesAutomatically(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setAppCacheEnabled(false);
        webview.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
    
                if(url.startsWith("tel:")) { 
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                    startActivity(intent); 
                    return true;
                }
                return false;
    
            }
    
            public void onPageFinished(WebView view, String url) {
                if(isSplashOn) { 
                    webview.setBackgroundDrawable(null);             
                    webview.setBackgroundColor(0);
    
                    isSplashOn = false;
                }
    
                super.onPageFinished(view, url);
            }
        }
                );
        webview.loadUrl("http://www.example.com");
    }
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_DOWN){
                switch(keyCode)
                {
                case KeyEvent.KEYCODE_BACK:
                    if(webview.canGoBack()){
                        webview.goBack();
                    }else{
                        finish();
                    }
                    return true;
                }
    
            }
            return super.onKeyDown(keyCode, event);
        }
    
    
    }
    

    Guys. Still the problem is't solved. Need some help