如何检查android中剩余的互联网数据(手机数据)?

时间:2015-12-07 07:44:33

标签: android internet-connection

我们经常使用以下代码来检查互联网......

/**
 * Checks if the device has Internet connection.
 * @return <code>true</code> if the phone is connected to the Internet.
 */
public static boolean hasConnection() {
    ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
            Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        return true;
    }

    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
        return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        return true;
    }
    return false;
}

或类似的东西......

/**
 * Method is using Connectivity Services to get Connectivity manager. that will find network informations
 * If we found connected state of any network that means we are connected to a network
 * @return true if we are connected otherwise false
 */
public Boolean isConnected() {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager != null) {
        NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
        if(info != null) {
            for (NetworkInfo i : info) {
                if (i.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

好的,现在的问题是,即使我们没有足够的移动/蜂窝数据(互联网平衡)或零余额,这两种方法都会返回。这不是一个很好的条件来执行任何与互联网相关的任务,如调用API等。所以问题是如何精确这些方法?我可以通过编程方式检查数据平衡吗?

0 个答案:

没有答案