【问题标题】:show toast when there is no internet access android没有互联网访问android时显示吐司
【发布时间】:2015-11-07 16:04:53
【问题描述】:

如何让这段代码永远在后台运行并始终检测是否有互联网访问(不是互联网连接)并在没有互联网访问时显示敬酒?

here is我想要什么(见喵喵的回答),但它是用于检测互联网

// check connectivity (Internet access)
    private boolean checkConnectivity() {
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try {
            Process mIpAddrProcess = runtime
                    .exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue " + mExitValue);
            if (mExitValue == 0) {
                img_c1.setImageResource(R.drawable.index2);
                return true;
            } else {
                img_c2.setImageResource(R.drawable.index2);
                return false;
            }
        } catch (InterruptedException ignore) {
            ignore.printStackTrace();
            System.out.println(" Exception:" + ignore);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(" Exception:" + e);
        }
        return false;
    }

【问题讨论】:

    标签: android android-toast


    【解决方案1】:

    首先,在后台永远运行这段代码是个坏主意。

    改为使用BroadCastReceiver查看网络状态,所以只有在网络状态变化时才会激活,

    您必须注册 BroadcastReceiver 才能参加网络状态更改事件。因此,每当设备上发生网络 android 广播事件的任何更改时,您的 BroadcastReceiver 都会监听该事件并根据该事件显示 Toast。

    好教程:http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

    http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/

    【讨论】:

    • 我想使用广播接收器,但该链接是关于检测互联网连接,你能告诉我如何使用我的代码在这个广播接收器中检测互联网访问(发送 ping)stackoverflow.com/questions/3767591/…
    • 有什么线索吗? @user370305
    • 为什么要 ping 到外部服务器?只是为了检查互联网连接?
    • 如果有互联网连接但没有互联网访问,我想关闭和打开 wifi,如果没有互联网连接或访问,我不能这样做,因为在这种情况下 wifi 已经关闭.我希望这是有道理的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 2017-01-07
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多