我如何检查android设备是否已连接到互联网? [英] How I can check android device is connected to the Internet?

查看:154
本文介绍了我如何检查android设备是否已连接到互联网?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法找出android设备是否已连接到Internet。我使用此功能:

Is there any way to find out that android device is connected to the Internet or not. I use this function:

    public boolean isDeviceOnline() {     
        ConnectivityManager cm =
        (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();     
        return netInfo != null && netInfo.isConnectedOrConnecting(); 
    }

,但如果设备连接到未连接WiFi网络的设备,则此函数返回true包括互联网访问权限或需要基于浏览器的身份验证,在这种情况下我想返回false。

but this function return true if device connected to a WiFi network that doesn't include internet access or requires browser-based authentication and I want return false in this situation.

推荐答案

尝试一下

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context) {
    this._context = context;
}

public boolean isInternetAvailble() {
    return isConnectingToInternet() || isConnectingToWifi();
}

private boolean isConnectingToInternet() {
    ConnectivityManager connectivity = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

    }
    return false;
}

private boolean isConnectingToWifi() {
    ConnectivityManager connManager = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (mWifi != null) {
        if (mWifi.getState() == NetworkInfo.State.CONNECTED)
            return true;
    }
    return false;
} }

这样声明

ConnectionDetector ConnectionDetector = new ConnectionDetector(
            context.getApplicationContext());

按原样使用

ConnectionDetector.isInternetAvailble()

这篇关于我如何检查android设备是否已连接到互联网?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆