【问题标题】:How can I Toggle off the Mobile Network Data by programming如何通过编程关闭移动网络数据
【发布时间】:2014-09-20 06:48:09
【问题描述】:

我想通过编程关闭网络数据。我已经尝试过下面的代码,但只是关闭了网络数据,而不是在设置中的移动数据中进行了切换。

try {
    final ConnectivityManager conman = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final java.lang.reflect.Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);
    // (true) to enable 3G; (false) to disable it.
    setMobileDataEnabledMethod.invoke(iConnectivityManager, false);
} catch (Exception e) {
    e.printStackTrace();
}

【问题讨论】:

    标签: android networking mobile 3g


    【解决方案1】:

    使用此代码关闭移动网络:

    public boolean getMobileDataEnabled() throws Exception {
        ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        Class ownerClass = mcm.getClass();
        Method method = ownerClass.getMethod("getMobileDataEnabled");
        return (Boolean)method.invoke(mcm);
    }
    
    public void setMobileDataEnabled(boolean enabled) throws Exception {
        ConnectivityManager mcm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        Class ownerClass = mcm.getClass();
        ownerClass.getMethod("setMobileDataEnabled",boolean.class).invoke(mcm, enabled);
    }
    
    try {
        boolean isMobileDataEnable = getMobileDataEnabled();
        if (isMobileDataEnabled) {
            setMobileDataEnabled(!isMobileDataEnable);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    AndroidManifest.xml添加

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 2019-10-29
      • 2012-04-27
      • 1970-01-01
      • 2023-03-27
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多