Android:如何检查用户是否“打开”或“关闭”移动数据连接

时间:2015-02-03 12:10:25

标签: android networking network-connection

我已经尝试过这个并且几乎成功但未能在三星Duos(GT-S7392)中获得结果。我使用以下代码: -

boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
    Class cmClass = Class.forName(cm.getClass().getName());
    Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
    method.setAccessible(true); // Make the method callable
    // get the setting for "mobile data"
    mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
    // Some problem accessible private API
    // TODO do whatever error handling you want here
}

请帮我解决Samsung Duos中的这个问题。

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码检查连接类型:

 public void checkConnectivity(Context context) {
  ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  if (connectivityManager != null) {
     NetworkInfo ni_act = null;
     try {
        ni_act = connectivityManager.getActiveNetworkInfo();
     }
     catch (Exception e) {
        e.printStackTrace();
     }
     if (ni_act != null) {
        // Only update if WiFi or 3G is connected and not roaming
        int netType = ni_act.getType();
        NetworkInfo.State netState = ni_act.getState();
        int netSubtype = ni_act.getSubtype();

        if (netState == NetworkInfo.State.CONNECTED) {
           postHandlers(NETWORK_CONNECTED);
           if (netType == ConnectivityManager.TYPE_WIFI) {
              postHandlers(NETWORK_CONNECTED_WIFI);
           }

           if (netType == ConnectivityManager.TYPE_MOBILE) {
              // 3G (or better)
              if (netSubtype >= TelephonyManager.NETWORK_TYPE_UMTS) {
                 postHandlers(NETWORK_CONNECTED_UMTS);
              }
              // GPRS (or EDGE)
              if (netSubtype == TelephonyManager.NETWORK_TYPE_GPRS || netSubtype == TelephonyManager.NETWORK_TYPE_EDGE) {
                 postHandlers(NETWORK_CONNECTED_EDGE);
              }
              // UNKNOWN
              if (netSubtype == TelephonyManager.NETWORK_TYPE_UNKNOWN) {
                 postHandlers(NETWORK_CONNECTED_UNKNOWN);
              }
           }

        }
     }
     else {
        NetworkInfo ni_cell = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo ni_wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if ((ni_cell != null && ni_cell.getState() == NetworkInfo.State.DISCONNECTED) || (ni_wifi != null && ni_wifi.getState() == NetworkInfo.State.DISCONNECTED))
           postHandlers(NETWORK_DISCONNECTED);
     }
  }

}
相关问题