Android:如何检查用户是否"Turn On"或"Turn Off"移动数据连接



我试图解决这个问题,几乎成功了,但三星双核(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
}

请帮助我在三星Duos中解决此问题。

谢谢

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

 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);
     }
  }
}

最新更新