Detect if Android device has Internet connection

后端 未结 15 2675
野性不改
野性不改 2020-11-22 08:54

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connect         


        
15条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 09:45

    private static NetworkUtil mInstance;
    private volatile boolean mIsOnline;
    
    private NetworkUtil() {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                boolean reachable = false;
                try {
                    Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
                    int returnVal = process.waitFor();
                    reachable = (returnVal==0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mIsOnline = reachable;
            }
        }, 0, 5, TimeUnit.SECONDS);
    }
    
    public static NetworkUtil getInstance() {
        if (mInstance == null) {
            synchronized (NetworkUtil.class) {
                if (mInstance == null) {
                    mInstance = new NetworkUtil();
                }
            }
        }
        return mInstance;
    }
    
    public boolean isOnline() {
        return mIsOnline;
    }
    

    Hope the above code helps you, also make sure you have internet permission in ur app.

提交回复
热议问题