有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android通过USB通信读取字符串

我对Android中的USB连接没有太多经验,所以我遵循了Android developer page的教程。我试图编写一个代码,例如,当我向USB设备发送命令时

send("M?");

然后,设备会将我的应用程序处理并向我显示的几行字符串发回给我。但不幸的是,我没有得到我想要的。有时我只得到字符串的一部分,有时是一些奇怪的字符,或者什么都没有。你能帮我修一下代码吗?这段代码应该能够读取小字符串(例如20-25个字符),但也可以读取长字符串

我有以下代码:

UsbReadWrite。java

public class UsbReadWrite extends AppCompatActivity {

static UsbDevice device;
private static final String ACTION_USB_PERMISSION = "com.安卓.example.USB_PERMISSION";
static UsbManager mUsbManager;
static PendingIntent mPermissionIntent;
private static byte[] bytes;
private static boolean forceClaim = true;
static int controlTransferResult;
static byte[] readBytes = new byte[4096];
static UsbEndpoint epOut = null, epIn = null;
static UsbDeviceConnection connection;
static int recvBytes;
static String readString = "";
static Thread thread;
static Runnable r;
static UsbInterface intf;
static UsbRequest request;
Handler handler;
static UsbManager manager;
static HashMap<String, UsbDevice> deviceList;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

public UsbReadWrite(Handler handler){

    this.handler = handler;
}
public static boolean connectDevice(Context context){

    manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
    deviceList = manager.getDeviceList();

    if (deviceList.toString().equals("{}")) {

        return false;
    }
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    device = deviceIterator.next();
    mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
    mPermissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    try {
        context.registerReceiver(mUsbReceiver, filter);
    }catch (Exception e){
        e.printStackTrace();
    }

    mUsbManager.requestPermission(device, mPermissionIntent);



    intf = device.getInterface(0);

    // look for our bulk endpoints
    for (int i = 0; i < intf.getEndpointCount(); i++) {
        UsbEndpoint ep = intf.getEndpoint(i);

        if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
            if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                epOut = ep;
            } else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                epIn = ep;
            }
        }
    }
    if (epOut == null || epIn == null) {
        throw new IllegalArgumentException("Not all endpoints found.");
    }
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!mUsbManager.hasPermission(device)){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            connection = mUsbManager.openDevice(device);
            connection.claimInterface(intf, forceClaim);

            connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
            connection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
            connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
            controlTransferResult = connection.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0);
            connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);

            request = new UsbRequest();

            request.initialize(connection, epOut);

        }
    });
    t.start();
    return true;
}

public static final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (device != null) {
                        //call method to set up device communication
                        intf = device.getInterface(0);

                        // look for our bulk endpoints
                        for (int i = 0; i < intf.getEndpointCount(); i++) {
                            UsbEndpoint ep = intf.getEndpoint(i);

                            if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                                if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                                    epOut = ep;
                                } else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                                    epIn = ep;
                                }
                            }
                        }
                        if (epOut == null || epIn == null) {
                            throw new IllegalArgumentException("Not all endpoints found.");
                        }
                        connection = mUsbManager.openDevice(device);
                        connection.claimInterface(intf, forceClaim);
                        connection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
                        connection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
                        connection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
                        controlTransferResult = connection.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0);
                        connection.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);
                        request = new UsbRequest();

                        request.initialize(connection, epOut);
                    }
                } else {
                    Log.d("MyActivity", "permission denied for device " + device);
                }
            }
        }
    }
};

public static void read2(){

    r = new Runnable() {
        @Override
        public void run() {
            synchronized (this) {
                readString="";
                send("M?");
                while (true) {
                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (mUsbManager.hasPermission(device)){


                        recvBytes = connection.bulkTransfer(epIn, readBytes, readBytes.length, 100);
                        Log.e("Database","M?="+readBytes);
                        if (recvBytes != 0) {
                            readString += new String(readBytes);
                            readString = readString.replace("\u0001`","");
                            readString = readString.replace("\u0000","");
                           Log.e("Database","M?="+readString);
                        }
                    }

                }
            }
        }

    };
    thread = new Thread(r);
    thread.start();
}

public static void send(String command){
    String fullCommand = "@" + command + "\r\n"; /*+ "\r\n"*/
    bytes = fullCommand.getBytes();
    while (connection==null){
        continue;
    }
    connection.bulkTransfer(epOut, bytes, bytes.length, 100); //0
}
}

提前谢谢


共 (0) 个答案