能否给一个SOCKET通转USB通信的安卓程序代码

编程爱好者一枚。我想把SOCKET通信接收到的数据通过USB发出,同时程序还具有两种通信的收和发功能。我尝试了自己将网上的两种通信的代码整合协作,但是失败了。求专家给个程序。

你要的应该是电脑城10块钱1块的usb有线网卡。不需要你做任何编程,就当网络操作就可以了。

下面是一个基于 Socket 和 USB 的数据收发的 Android 应用程序的代码,不知道还能不能用。

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    // Socket 相关变量
    private Socket mSocket;
    private BufferedReader mBufferedReader;
    private PrintWriter mPrintWriter;

    // USB 相关变量
    private UsbManager mUsbManager;
    private UsbDevice mUsbDevice;
    private UsbDeviceConnection mUsbDeviceConnection;
    private UsbInterface mUsbInterface;
    private UsbEndpoint mUsbEndpointIn;
    private UsbEndpoint mUsbEndpointOut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化 Socket 相关变量
        try {
            mSocket = new Socket("服务器 IP 地址", 8080);
            mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
            mPrintWriter = new PrintWriter(mSocket.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 初始化 USB 相关变量
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        UsbDevice usbDevice = null;
        for (UsbDevice device : mUsbManager.getDeviceList().values()) {
            if (device.getVendorId() == YOUR_VENDOR_ID && device.getProductId() == YOUR_PRODUCT_ID) {
                usbDevice = device;
                break;
            }
        }
        if (usbDevice != null) {
            mUsbDevice = usbDevice;
            mUsbDeviceConnection = mUsbManager.openDevice(mUsbDevice);
            mUsbInterface = mUsbDevice.getInterface(0);
            mUsbEndpointIn = mUsbInterface.getEndpoint(0);
            mUsbEndpointOut = mUsbInterface.getEndpoint(1);
            mUsbDeviceConnection.claimInterface(mUsbInterface, true);
        } else {
            Log.e(TAG, "USB 设备未连接");
        }

        // 开启 Socket 数据接收线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        String data = mBufferedReader.readLine();
                        Log.d(TAG, "接收到数据:" + data);
                        // 将接收到的数据通过 USB 发送出去
                        sendUsbData(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 关闭 Socket 相关变量
        try {
            mBufferedReader.close();
            mPrintWriter.close();
            mSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭 USB 相关变量
        mUsbDeviceConnection.releaseInterface(mUsbInterface);
        mUsbDeviceConnection.close();
    }

    // 发送数据到 Socket
    private void sendSocketData(String data) {
        mPrintWriter.println(data);
        mPrintWriter.flush();
    }

    // 发送数据到 USB
    private void sendUsbData(String data) {
        byte[] bytes = data.getBytes();
        int result = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, bytes, bytes.length, 1000);
        if (result < 0) {
            Log.e(TAG, "发送数据到 USB 失败");
        }
    }

    // 从 USB 接收数据
    private void receiveUsbData() {
        byte[] buffer = new byte[1024];
        int result = mUsbDeviceConnection.bulkTransfer(mUsbEndpointIn, buffer, buffer.length, 1000);
        if (result > 0) {
            String data = new String(buffer, 0, result);
            Log.d(TAG, "接收到数据:" + data);
            // 将接收到的数据通过 Socket 发送出去
            sendSocketData(data);
        } else {
            Log.e(TAG, "从 USB 接收数据失败");
        }
    }
}

记得把 YOUR_VENDOR_ID 和 YOUR_PRODUCT_ID 需要替换成自己的 USB 设备的 Vendor ID 和 Product ID。

另外,由于 USB 相关的操作需要使用到 Android 的 USB Host API,因此需要在 AndroidManifest.xml 文件中添加以下权限和特性:


<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />

同时,还需要在 Activity 中添加以下代码来处理 USB 设备的权限请求:

private static final String ACTION_USB_PERMISSION = "com.example.usbhost.USB_PERMISSION";

private final BroadcastReceiver mUsbPermissionReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (usbDevice != null) {
                        // 已获取 USB 设备的权限,可以进行相关操作
                    }
                } else {
                    Log.e(TAG, "未获取 USB 设备的权限");
                }
            }
        }
    }
};

private void requestUsbPermission() {
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    mUsbManager.requestPermission(mUsbDevice, pendingIntent);
}

在请求权限之后,系统会弹出一个对话框让用户确认是否授权,如果用户授权,则会收到一个 USB_PERMISSION 的广播,然后就可以在 BroadcastReceiver 中处理相关操作。

Android开发之socket搭配usb通信实现手机下发给其他设备指令

Android开发中USB串口通信开发主要涉及到以下几个类及相应的方法:
1 ,UsbManager:负责管理USB设备的类,你可以在相应代码中通过以下方法获得

//获取UsbManager实例方法
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
该类提供的主要方法有:
1) getDeviceList()
获得设备列表,返回的是一个HashMap.;
2) hasPermission(UsbDevice device)
判断你的应用程序是否有接入此USB设备的权限,如果有则返回真,否则返回false.
3) openDevice(UsbDevice device)
打开USB设备,以便向此USB设备发送和接受数据,返回一个关于此USB设备的连接。
4) requestPermission(UsbDevice device, PendingIntent pi)
向USB设备请求临时的接入权限。

2,UsbDevice:一个USB设备对象,每个设备一般包括一个接口,也可能有多个,每个接口又包含节点用来与此设备传输数据。主要方法有:
1) getDeviceClass()
返回此USB设备的类别,用一个整型来表示。
2) getDeviceId()
返回唯一标识此设备的ID号,也用一个整型来表示。
3) getDeviceName()
返回此设备的名称,用一个字符串来表示。
4) getDeviceProtocol()
返回此设备的协议类别,用一个整型来表示。
5) getDeviceSubclass()
返回此设备的子类别,用一个整型来表示。
6) getVendorId()
返回生产商ID
7) getProductId()
返回产品ID
8) getInterfaceCount()
返回此设备的接口数量
9) getInterface(int index)
得到此设备的一个接口,返回一个UsbInterface。

3,UsbInterface:代表USB设备的一个接口(物理接口),UsbInterface本身是一个类,此类的主要方法有以下:
1) getId()
得到给接口的id号。
2) getInterfaceClass()
得到该接口的类别。
3) getInterfaceSubclass()
得到该接口的子类。
4) getInterfaceProtocol()
得到该接口的协议类别。
5) getEndpointCount()
获得关于此接口的节点数量。
6) getEndpoint(int index)
对于指定的index获得此接口的一个节点,返回一个UsbEndpoint.
4, UsbEndpoint:代表一个接口的某个节点的类。该类主要方法:
1) getAddress()
获得此节点的地址
2) getAttributes()
获得此节点的属性
3) getDirection()
获得此节点的数据传输方向
5 ,UsbDeviceConnection:代表USB连接的一个类。用此连接可以想USB设备发送和接收数据,主要方法有:
1)bulkTransfer(UsbEndpoint endpoint, byte[] buffer, int length, int timeout)
通过给定的endpoint来进行大量的数据传输,传输的方向取决于该节点的方向,buffer是要发送或接收的字节数组,length是该字节数组的长度。传输成功则返回所传输的字节数组的长度,失败则返回负数。
2)controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)
该方法通过0节点向此设备传输数据,传输的方向取决于请求的类别,如果requestType为USB_DIR_OUT则为写数据,USB_DIR_IN, 则为读数据

获取到通讯对象之后,就可以通过udp或者tcp以流的形式进行数据的传递


不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/7441740
  • 除此之外, 这篇博客: 安卓手机通过USB连接路由器有线上网中的 安卓手机通过USB,连接到带USB口的定制路由器,在手机上进行设置后可实现有线上网。 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    这个与普通的”USB网络共享”使用网络的方法是相反的,普通的是电脑共享使用手机的移动网络上网;这个是手机使用路由器接入的宽带网络上网,和WIFI连接路由器上网一样的效果,只是这是通过USB线上网。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

看看下面的示例代码

public class SocketToUsbService extends Service {
    private ServerSocket serverSocket;
    private Socket socket;
    private UsbManager usbManager;
    private UsbDevice usbDevice;
    private UsbDeviceConnection usbDeviceConnection;
    private UsbInterface usbInterface;
    private UsbEndpoint usbInEndpoint;
    private UsbEndpoint usbOutEndpoint;
    private UsbDeviceReceiver usbDeviceReceiver;

    public SocketToUsbService() {
        usbDeviceReceiver = new UsbDeviceReceiver();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化Socket服务
        try {
            serverSocket = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 初始化USB连接
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        registerReceiver(usbDeviceReceiver, filter);

        // 查找USB设备并请求权限
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            UsbDevice device = deviceIterator.next();
            if (device.getVendorId() == VENDOR_ID && device.getProductId() == PRODUCT_ID) {
                usbDevice = device;
                usbManager.requestPermission(usbDevice, permissionIntent);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(usbDeviceReceiver);
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (usbDeviceConnection != null) {
            usbDeviceConnection.close();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        socket = serverSocket.accept();
                        // 接收到Socket数据
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String receiveData = in.readLine();

                        // 发送USB数据
                        if (usbDeviceConnection != null) {
                            usbDeviceConnection.bulkTransfer(usbOutEndpoint, receiveData.getBytes(), receiveData.getBytes().length, 0);
                        }

                        // 接收USB数据
                        byte[] buffer = new byte[1024];
                        int count = usbDeviceConnection.bulkTransfer(usbInEndpoint, buffer, buffer.length, 3000);
                        if (count > 0) {
                            String usbData = new String(buffer);
                            Log.i(TAG, "Receive USB data: " + usbData);
                        }

                        // 发送Socket数据
                        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                        out.println(usbData);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        return super.onStartCommand(intent, flags, startId);
    }

    private class UsbDeviceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null && device.getVendorId() == VENDOR_ID && device.getProductId() == PRODUCT_ID) {
                            usbDevice = device;
                            usbDeviceConnection = usbManager.openDevice(usbDevice);
                            if (usbDeviceConnection != null) {
                                usbInterface = usbDevice.getInterface(0);
                                usbDeviceConnection.claimInterface(usbInterface, true);
                                usbInEndpoint = usbInterface.getEndpoint(0);
                                usbOutEndpoint = usbInterface.getEndpoint(1);
                            }
                        }
                    }
                }
            }
        }
    }
}

onCreate方法用于初始化Socket服务和USB连接,onDestroy方法用于关闭Socket连接和释放USB资源,onStartCommand方法