You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过USB在Android与Windows PC间实现无ADB的命令传输

Hey there! Let’s break down a solid solution for your Android-Windows USB communication needs, since ADB, network, and Bluetooth are off-limits. The Android Open Accessory Protocol (AOAP) is exactly what you’re looking for—here’s a step-by-step guide with actionable code snippets and tips to make it work:

1. Understand AOAP Basics

First, let’s clarify: AOAP lets your Windows PC act as an "accessory" to the Android device. When connected via USB, Android will switch to accessory mode, and your PC can communicate directly with the app over USB without needing ADB. This is fully supported by Android and fits all your constraints.

2. Configure the Android App

Start by setting up your Android app to recognize and communicate with the Windows accessory:

Add Permissions & Features to Manifest

Add these lines to your AndroidManifest.xml to enable accessory support:

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

<application>
    <!-- Broadcast receiver to detect accessory connections -->
    <receiver android:name=".UsbAccessoryReceiver">
        <intent-filter>
            <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
        </intent-filter>
        <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
            android:resource="@xml/accessory_filter" />
    </receiver>
</application>

Create the Accessory Filter XML

Make a res/xml/accessory_filter.xml file to define your PC accessory’s attributes (match these to your Windows app’s configuration):

<resources>
    <usb-accessory manufacturer="YourPCAppManufacturer" model="YourPCAppModel" version="1.0" />
</resources>

Implement USB Communication Logic

Add code to handle accessory connections and send commands from buttons:

import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.ParcelFileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UsbAccessoryReceiver extends BroadcastReceiver {
    private UsbManager mUsbManager;
    private FileInputStream mInputStream;
    private FileOutputStream mOutputStream;

    @Override
    public void onReceive(Context context, Intent intent) {
        mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        String action = intent.getAction();

        if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
            UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
            if (accessory != null) {
                // Request USB permission if needed
                if (!mUsbManager.hasPermission(accessory)) {
                    PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
                    mUsbManager.requestPermission(accessory, permissionIntent);
                } else {
                    openAccessory(accessory, context);
                }
            }
        }
    }

    private void openAccessory(UsbAccessory accessory, Context context) {
        ParcelFileDescriptor fd = mUsbManager.openAccessory(accessory);
        if (fd != null) {
            mInputStream = new FileInputStream(fd.getFileDescriptor());
            mOutputStream = new FileOutputStream(fd.getFileDescriptor());

            // Example: Link a button to send a command
            YourMainActivity activity = (YourMainActivity) context;
            activity.button1.setOnClickListener(v -> sendCommand("COMMAND_BUTTON_1"));
            activity.button2.setOnClickListener(v -> sendCommand("COMMAND_BUTTON_2"));
        }
    }

    private void sendCommand(String command) {
        try {
            mOutputStream.write(command.getBytes());
            mOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
3. Build the Windows Side

For the Windows app, you’ll need to communicate with the Android device in accessory mode. Here’s how to do it with LibUsbDotNet (a .NET wrapper for libusb that works well with AOAP):

Step 1: Install Required Tools

  • Install the Google USB Accessory Driver on Windows (this lets Windows recognize Android in accessory mode).
  • Add the LibUsbDotNet NuGet package to your Windows project.

Step 2: Windows Communication Code

Use this C# snippet to detect the Android accessory and receive commands:

using LibUsbDotNet;
using LibUsbDotNet.Main;
using System.Text;

class UsbAccessoryCommunicator {
    private const int GOOGLE_VID = 0x18D1;
    private const int AOAP_PID = 0x2D00; // Android accessory mode PID

    public void StartListening() {
        UsbDeviceFinder finder = new UsbDeviceFinder(GOOGLE_VID, AOAP_PID);
        UsbDevice usbDevice = UsbDevice.OpenUsbDevice(finder);

        if (usbDevice == null) {
            Console.WriteLine("Android accessory not found.");
            return;
        }

        try {
            usbDevice.SetConfiguration(1);
            UsbInterface usbInterface = usbDevice.OpenUsbInterface(0);
            usbInterface.ClaimInterface();

            // Set up input endpoint to receive commands from Android
            UsbEndpointReader reader = usbInterface.EndpointReader(ReadEndpointID.Ep01);
            byte[] buffer = new byte[256];
            int bytesRead;

            Console.WriteLine("Listening for commands...");
            while (true) {
                ErrorCode error = reader.Read(buffer, 5000, out bytesRead);
                if (error == ErrorCode.None && bytesRead > 0) {
                    String command = Encoding.ASCII.GetString(buffer, 0, bytesRead).Trim();
                    Console.WriteLine("Received command: " + command);
                    
                    // Execute your Windows logic based on the command
                    switch(command) {
                        case "COMMAND_BUTTON_1":
                            RunButton1Action();
                            break;
                        case "COMMAND_BUTTON_2":
                            RunButton2Action();
                            break;
                    }
                }
            }
        } finally {
            usbDevice?.Close();
        }
    }

    private void RunButton1Action() {
        // Replace with your Windows command logic
        Console.WriteLine("Executing Button 1 command...");
    }

    private void RunButton2Action() {
        // Replace with your Windows command logic
        Console.WriteLine("Executing Button 2 command...");
    }
}
4. Troubleshooting Tips
  • Driver Issues: If Windows doesn’t detect the Android accessory, use the Google USB Accessory Driver or the Zadig tool to install a compatible WinUSB driver for the device.
  • Permission Errors: Ensure your Android app requests USB permission correctly—users will see a prompt to allow access when connecting.
  • Device Compatibility: Most modern Android devices support AOAP, but double-check your device’s specs if you run into issues.

内容的提问来源于stack exchange,提问作者Mariana Bittencourt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:01:38