Search code examples
javaandroidtoast

Make toast display before internet connection waiting loop


I want to achieve the following behavior in my app:

If there's no internet connectivity, a toast display warning about that, when there is finally connectivity a webview is loaded.

I manage to do all desired behavior except for the toast thing, I've tried these ways:

isOnline();

        if (!online) {
            Thread y=new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    Toast.makeText(getBaseContext(), "No hay conectividad a Internet", Toast.LENGTH_LONG).show();

                }
            });

            y.start();
            try {
                y.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
            Thread t=new Thread(new Runnable() {
                @Override
                public void run() {

                    while (!online)
                    {
                        isOnline();
                    }
                }
            });

            t.start();

            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

And this one:

isOnline();

        if (!online) {
            Toast.makeText(getBaseContext(), "No hay conectividad a Internet", Toast.LENGTH_LONG).show();
        }
            Thread t=new Thread(new Runnable() {
                @Override
                public void run() {

                    while (!online)
                    {
                        isOnline();
                    }
                }
            });

            t.start();

            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

But neither of them get to show the toast at time.

What could I do so the Toast is shown?


Solution

  • Let me suggest you the most simple way - just use this library:

    https://github.com/AggarwalAnkit/InternetAvailabilityChecker

    The usage is very simple, just follow the tutorial - https://medium.com/the-sixt-india-blog/check-active-internet-connection-on-android-device-3138ad81932d

    As a result you will get something like this:

    override fun onInternetConnectivityChanged(isConnected: Boolean) {
        if (isConnected){
        //load webView
      } else {
        //show Toast here
     }
    }