首页 > 解决方案 > 在互联网连接等待循环之前显示吐司

问题描述

我想在我的应用程序中实现以下行为:

如果没有互联网连接,吐司会显示警告,当最终连接时,会加载 web 视图。

除了吐司之外,我设法做所有想要的行为,我尝试了这些方法:

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();
            }

和这个:

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();
            }

但他们俩都没有时间展示敬酒。

我该怎么做才能显示 Toast?

标签: javaandroidtoast

解决方案


让我建议你最简单的方法 - 只需使用这个库:

https://github.com/AggarwalAnkit/InternetAvailabilityChecker

用法很简单,按照教程操作即可 - https://medium.com/the-sixt-india-blog/check-active-internet-connection-on-android-device-3138ad81932d

结果你会得到这样的东西:

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

推荐阅读