Detect USB tethering on android

you can also use reflection to access the hidden function for setting usb tethering.
Here is my code.

    ConnectivityManager cm =
        (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Log.d(TAG,"test enable usb tethering");
    String[] available = null;
    int code=-1;
    Method[] wmMethods = cm.getClass().getDeclaredMethods();

    for(Method method: wmMethods){
      if(method.getName().equals("getTetherableIfaces")){
        try {
            available = (String[]) method.invoke(cm);
            break;
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
      }
    }

    for(Method method: wmMethods){
          if(method.getName().equals("tether")){                  
              try {
                code = (Integer) method.invoke(cm, available[0]);


            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return;
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return;
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return;
            }
            break;
          }
    }

    if (code==0) 
        Log.d(TAG,"Enable usb tethering successfully!");
    else
        Log.d(TAG,"Enable usb tethering failed!");

For disabling usb tethering, you just need to change the reflection method name “getTetherableIfaces” to “getTetheredIfaces”, change “tether” to “untether”.

Please check.

Leave a Comment