android判断连接的wifi是否有网络
高洛峰
高洛峰 2017-04-17 14:40:07
0
4
570

android判断连接的wifi是否有网络。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
巴扎黑

public static int getNetWorkStatus(Context context) {

    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo networkInfo = connectivityManager
                .getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return NETWORK_WIFI_CONNECTION;
            }
            return NETWORK_MOBILE_CONNECTION;
        }
    }
    return NETWORK_DISCONNECTION;
}
洪涛

If you just want to check whether the network is connected, use it directly isNetworkConnected()
If you want to check the network connectivity (whether the network can be accessed), then use isNetworkConnected() in combination with isNetworkOnline()

private boolean isNetworkConnected() {
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected());
}

public boolean isNetworkOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("ping -c 1 114.114.114.114");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return false;
}

Note: 114.114.114.114 can be changed to a website you trust (for example: www.baidu.com)

左手右手慢动作

Personal experience, don’t spray if you don’t like it. . .
I never care whether the user is connected to 3G, 4G or WIFI, and I don’t care whether the WIFI is connected to the Internet, because it doesn’t matter.
The key point is whether the user’s App can connect to the designated server.
So...
Just test the connection to the server directly. If there is no Internet connection, an exception will be thrown quickly.
Try catch and you will know.
Or write a dedicated API for testing connections.

黄舟

Write a method directly and visit http://www.baidu.com. If data is returned, it means there is a network. If no data is returned, or an exception means there is no network. so

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!