如何在Android 4.0设备上通过程序启用USB网络共享?

14

我想在我的Android 4.0设备上从我的应用程序启用USB网络共享功能。以下代码适用于Android 2.2,但在4.0上不起作用。 有人能帮忙吗?

int USBTethering(boolean b) {
        try {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            Log.d(tag, "test enable usb tethering");
            Method[] wmMethods = cm.getClass().getDeclaredMethods();
            String str = "";
            if (b)
                str = "tether";
            else
                str = "untether";
            for (Method method : wmMethods) {
                Log.d("in usb tethering method",method.getName()+"<<nn>>");
                if (method.getName().equals(str)) {
                    Log.d(tag, "gg==" + method.getName());
                    Log.d("in if", " case matches "+method.getName()+"and str is "+str);
                    try {
                        Integer code = (Integer) method.invoke(cm, "usb0");
                    //  code = (Integer) method.invoke(cm, "setting TH");
                        Log.d(tag, "code===" + code);
                        return 1;
                    } catch (IllegalArgumentException e) {
                        Log.d(tag, "eroor== gg " + e.toString());
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        Log.d(tag, "eroor== gg " + e.toString());
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        Log.d(tag, "eroor== gg " + e.toString());
                        e.printStackTrace();
                    }
                }
            }
            return 0;

                       } catch (Exception e) {
            Log.e(tag, "" + e);
            return 0;
        }

    }

@MahajanGuy,你找到解决方案了吗?使用已root或未root的设备? - Naskov
在Android 4.0及以上版本中需要Root权限,如果您拥有Root权限,您需要添加 WRITE_SECURE_SETTINGS 权限(https://dev59.com/v2LVa4cB1Zd3GeqPsxFS#12209096)。 - Mdlc
如果您调用getTetherableIfaces()并将所需的字符串传递到tether(String),会发生什么?https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/ConnectivityManager.java @ 671&705 - Ethan
你尝试过哪些设备? - David Wasser
2个回答

1

我有一段类似的代码,在Android 4.0上运行良好(但只在某些设备上)。不幸的是,访问共享网络功能非常依赖厂商。我注意到的一件事是,您没有使要调用的方法可访问。如果在您使用的设备上,该方法已被设置为私有,则此方法将无法正常工作。尝试添加:

method.setAccessible(true);

在你调用之前

Integer code = (Integer) method.invoke(cm, "usb0");

另一件事是接口名称(在您的情况下为“usb0”)也是特定于供应商的。不同制造商的不同设备上的接口名称不同。确保您已获得要测试的设备的正确接口名称。

0

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