7

I want my app to check whether "Data network mode" or "Mobile data" is enabled, even if it is not currently active. In other words I need to check whether the app will potentially incur mobile data charges, even if it the phone is currently connected through WiFi.

By googling I have found the following code which checks whether "Mobile data" is "active".

ConnectivityManager cm =
        (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;

The problem with this code is that if WiFi is active the Mobile data is not reported as active even if it is switched to on.

Can the code be modified to determine whether mobile data is "enabled" and therefore potentially active, rather than as with this code whether it is the currently active connection mode?

4

4 回答 4

3

试试这个,它在大多数情况下都有效。

ConnectivityManager cm =
                (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnected();

        if (!isConnected)
        {
            return false;
        }
于 2014-02-19T07:33:06.373 回答
2

尝试这个

   ConnectivityManager cm = (ConnectivityManager) 
            activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null
        // otherwise check if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
于 2012-09-10T13:54:35.333 回答
1

我不确定这是否适用于所有设备,但它确实适用于我尝试过的一些设备:

private boolean isMobileDataEnabled(Context ctx) {
    int mobileData = Settings.Secure.getInt(ctx.getContentResolver(), "mobile_data", 0);
    return mobileData == 1;
}

即使我有一个活动的 WiFi 连接,它似乎也会返回正确的结果。

于 2016-10-06T12:56:28.973 回答
0

请查看此代码:(我在 Play 商店中发布的应用程序之一的代码)

private static boolean isAPNEnabled(Context paramContext) {
    try {
        NetworkInfo networkInfo = ((ConnectivityManager) paramContext.getSystemService("connectivity")).getActiveNetworkInfo();
        return networkInfo.isConnected();
    } catch (Exception e) {
        return false;
    }
}
于 2012-09-10T14:26:46.980 回答