show toast when there is no internet access android

谁说我不能喝 提交于 2021-01-28 07:46:59

问题


how do i make this code run in background forever and always detect if there is internet access or not (not internet connection) and show a toast when there is no internet access?

here is what i want (See meow meo's answer), but it is for detecting internet

// 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;
    }

回答1:


First of all, its bad idea to run this code forever in background.

Instead use BroadCastReceiver to check network status, so it will only active at the time of network status change,

You have to register your BroadcastReceiver for Network Status Change event. So whenver any changes happen on device for network android broadcast event and your BroadcastReceiver will listen that event and display Toast based on that.

Good tutorials: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

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



来源:https://stackoverflow.com/questions/33584746/show-toast-when-there-is-no-internet-access-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!