如何在Android 4.0设备上以编程方式启用USB Tethering?

Gau*_*pta 14 usb android tethering

我想在我的Android 4.0设备上启用我的应用程序的USB Tethering?以下代码适用于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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

Dav*_*ser 1

我有与此类似的代码,它适用于 Android 4.0(但仅适用于某些设备)。不幸的是,对网络共享的访问是特定于供应商的。我注意到的一件事是,您没有使您尝试调用的方法变得可访问。如果在您使用的设备上该方法已设为私有,则此方法将不起作用。尝试添加:

method.setAccessible(true);
Run Code Online (Sandbox Code Playgroud)

在你打电话之前

Integer code = (Integer) method.invoke(cm, "usb0");
Run Code Online (Sandbox Code Playgroud)

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