在安卓系统中,如何通过程序启用/禁用数据连接

48

我想通过编程方式启用/禁用数据连接。 我已经使用了以下代码:

void enableInternet(boolean yes)
{
    ConnectivityManager iMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Method iMthd = null;
    try {
        iMthd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
        } catch (Exception e) {
               } 
    iMthd.setAccessible(false);

    if(yes)
     {

                try {
                    iMthd.invoke(iMgr, true);
                    Toast.makeText(getApplicationContext(), "Data connection Enabled", Toast.LENGTH_SHORT).show();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                     dataButton.setChecked(false);
                     Toast.makeText(getApplicationContext(), "IllegalArgumentException", Toast.LENGTH_SHORT).show();

                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "IllegalAccessException", Toast.LENGTH_SHORT).show();

                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                     dataButton.setChecked(false);
                     Toast.makeText(getApplicationContext(), "InvocationTargetException", Toast.LENGTH_SHORT).show();

                }

     }
    else
     {
        try {
            iMthd.invoke(iMgr, true);
            Toast.makeText(getApplicationContext(), "Data connection Disabled", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                   dataButton.setChecked(true);
                Toast.makeText(getApplicationContext(), "Error Disabling Data connection", Toast.LENGTH_SHORT).show();
                                    }
     }
}

在模拟器中没有任何错误,但是当我尝试在真实设备上运行时,出现了“InvocationTargetException”错误。

我正在使用API级别8构建应用程序。


InvocationTargetExceptione.getMessage() 方法返回什么结果?内部异常呢? - Greyson
你正在使用哪个设备?该设备安装的 Android 操作系统版本是多少? - David Wasser
我正在三星Galaxy S上运行它,Android操作系统是2.2。 - JiTHiN
2个回答

90

这段代码示例适用于运行 Android 2.3(姜饼)及以上版本的手机:

private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    final ConnectivityManager conman = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
    connectivityManagerField.setAccessible(true);
    final Object connectivityManager = connectivityManagerField.get(conman);
    final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}
不要忘记将这行代码添加到你的清单文件中。
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

1
运行这段代码后,我遇到了java.lang.reflect.InvocationTargetException错误。 - mcacorner
9
对于 Android 版本低于 2.3 的设备,我们可以使用 Java 反射方法来启用/禁用数据连接。参考 https://dev59.com/zmbWa4cB1Zd3GeqPX4xr。 - JiTHiN
+1,你的方法对我非常有效。谢谢,我能否像上面一样以编程方式将GPS设置为开/关? - Vigbyor
@TobiasMoeThorstensen 我尝试将此代码添加到AppWidgetProvider OnReceive方法中,但是我收到了 W/ActivityManager(444): Killing ProcessRecord{a6bdce00 1809:com.rajaraman.quicksettings/u0a10064}: background ANR 的错误提示。我需要在线程中运行它以避免ANR吗? - Rajaraman Subramanian
在AsyncTask中运行此代码不会引发后台ANR。 - Rajaraman Subramanian
显示剩余12条评论

1

@riHaN JiTHiN,你的程序在2.3及以上版本中运行良好,但是'else'语句需要做出小改变:

else
     {
        try {
            iMthd.invoke(iMgr, true);

“true”应更改为“false”

iMthd.invoke(iMgr, false);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接