Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

Detect USB tethering on android

Is there any way to know (pro grammatically) in your Activity/Application that the user has enabled USB tethering on his phone?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...