android - 在 Android 上检测 USB 网络共享

标签 android usb

有什么方法可以(以编程方式)在您的 Activity/应用程序中知道用户已在他的手机上启用 USB 网络共享?

最佳答案

您还可以使用反射来访问用于设置 USB 网络共享的隐藏功能。 这是我的代码。

    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!");

要禁用 USB 网络共享,只需将反射方法名称“getTetherableIfaces”更改为“getTetheredIfaces”,将“tether”更改为“untether”即可。

请检查。

关于android - 在 Android 上检测 USB 网络共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7509924/

相关文章:

python - USB 错误 : [Errno 13] Access denied (insufficient permissions)

linux - 在 Linux 上通过 USB 发送原始数据

c# - 插入时锁定 USB C#

android - 透明 active ,带有淡淡的灰色

java - DialogFragment 在 Android 4.4.2 中顶部有蓝线

java - 如何在 Android 中暂停线程的消息队列?

python - 向 usb GSM 调制解调器发送 'AT' 命令在 Python 中返回空字符串

java - 如何在 Android/Java 中循环显示背景颜色?

android - 根据 ServerValue.TIMESTAMP 查询 Firebase

linux - 使用 --device 标志时,在主机上创建的新设备节点不会反射(reflect)在 Docker 容器中