检查互联网连接而不是网络状态

时间:2018-10-27 06:25:17

标签: android internet-connection network-state

我的应用程序也可以在脱机模式下使用,并且在可以连接互联网时也可以正常使用。我正在使用以下代码检查互联网连接。

ConnectivityManagercm = (ConnectivityManager) ConnectivityClass.getInstance().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();

问题是,如果我们连接的WiFi网络不包括互联网访问权限或需要基于浏览器的身份验证,则它仍会返回true。如果无法使用互联网,则应返回false。我需要检查互联网连接,而不是移动网络连接状态。

  

minSdkVersion 15

3 个答案:

答案 0 :(得分:1)

您可以ping URL。然后您就可以知道互联网完全可用。

public Boolean isInternetAvailable() {
    try {
        Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");

        boolean avaiablility = (p1.waitFor()==0);
        return avaiablility;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

答案 1 :(得分:0)

希望使用此代码,您可以检查网络连接

public class InternetCheckerTask extends AsyncTask<Void, Void, Void> {

private OnInternetCheckListener listener;
private int authStatus;
private boolean running;

public InternetCheckerTask(OnInternetCheckListener listener) {
    this.listener = listener;
}

@Override
protected Void doInBackground(Void... voids) {
    running = true;
    if(isInternetReallyAvailable()) {
        authStatus = AuthConstants.CONNECTED;
    } else {
        authStatus = AuthConstants.NOT_CONNECTED;
    }
    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    if(listener != null) {
        listener.onResponse(authStatus);
    }
    running = false;
}

// should not be called from ui thread, can be called only from background service
private boolean isInternetReallyAvailable() {
    ConnectivityManager cm = (ConnectivityManager) App.getInstance().getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    if(activeNetwork == null || !activeNetwork.isAvailable() || !activeNetwork.isConnected()) {
        return false;
    } else {
        // TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
        try {
            int timeoutMs = 1500;
            Socket sock = new Socket();
            SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

            sock.connect(sockaddr, timeoutMs);
            sock.close();

            return true;
        } catch (IOException e) {
            return false;
        }
    }
}

public boolean isRunning() {
    return running;
}

public interface OnInternetCheckListener {
    void onResponse(int status);
}

}

创建一个类并定义以下常量值

public class AuthConstants {
    public static final int CONNECTED = 1;
    public static final int NOT_CONNECTED = 2;
}

这就是您应该在需要的地方使用此功能的方式

new InternetCheckerTask(new InternetCheckerTask.OnInternetCheckListener() {
        @Override
        public void onResponse(int status) {
            switch (status) {
                case AuthConstants.CONNECTED:
                    // connection is available
                    break;
                default:
                    // no connection
                    break;
            }
        }
    }).execute();

答案 2 :(得分:0)

public static boolean isOnline(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm != null
            ? cm.getActiveNetworkInfo()
            : null;
    return netInfo != null && netInfo.isConnectedOrConnecting();
}
  • 选中my answer 以处理wifi和移动数据之间的网络更改。