Detect USB tethering on android

后端 未结 5 447
Happy的楠姐
Happy的楠姐 2020-12-01 15:01

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

5条回答
  •  一整个雨季
    2020-12-01 15:49

    I have found that if I check for usb0 network interface it only has an ip address once tethering has been set up.

    public static String getIPAddressUsb(final boolean useIPv4) {
        try {
            final List interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (final NetworkInterface intf : interfaces) {
                if (intf.getDisplayName().startsWith("usb")) {
                    final List addrs = Collections.list(intf.getInetAddresses());
                    for (final InetAddress addr : addrs) {
                        final String sAddr = addr.getHostAddress().toUpperCase();
                        final boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        if (useIPv4) {
                            if (isIPv4) { return sAddr; }
                        } else {
                            if (!isIPv4) {
                                final int delim = sAddr.indexOf('%');
                                return delim < 0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (final Exception ex) {
            // for now eat exceptions
        }
        return "";
    }
    
    
    boolean isUsbTethered(){
    String ipAddr = MipnAndroidApplication.getIPAddressUsb(true);
        if (ipAddr.length() == 0) {
            Log.i(LOG_TAG, "tethering not enabled");
        return false;
        } else {
            Log.i(LOG_TAG, "tethering enabled :)");
        return true;
        }
    }
    

提交回复
热议问题