我们目前成立的成员包括:
1)每次处理卡时读取卡并发送唯一代码的硬件设备。包括RFID读卡器,ATMega16微控制器和PL2303 USB-UART,用于与Android设备进行串行通信。
2)每次硬件设备处理卡时都会收到唯一代码(由微控制器发送)的Android应用程序。
我们用于从硬件接收唯一代码的代码:
package com.example.admin.hardware;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
UsbManager manager;
byte[] bytes;
UsbEndpoint end;
UsbInterface inter;
UsbDevice device;
UsbDeviceConnection conn;
TextView data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device == null)
{
Toast.makeText(this, "NO DEVICE CONNECTED!", Toast.LENGTH_LONG).show();
}
else
{
data = (TextView) findViewById(R.id.data);
String name = device.getDeviceName();
//int vendorID = device.getVendorId();
inter = device.getInterface(0);
int i = inter.getEndpointCount();
end = inter.getEndpoint(0);
Toast.makeText(this, "Name Of The "+name, Toast.LENGTH_LONG).show();
//RETURNS 128 if USB_DIR_IN and 0 if USB_DIR_OUT
int direction = end.getDirection();
Toast.makeText(this, "Direction of The EndPoint "+String.valueOf(direction), Toast.LENGTH_LONG).show();
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
conn = manager.openDevice(device);
conn.claimInterface(inter, true);
new Thread(new Runnable(){
@Override
public void run() {
try {
conn.bulkTransfer(end, bytes, 32, 0);
}
catch(Exception e){
data.setText(e.getMessage());
}
}
}).start();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我期待看到的内容:
从硬件设备接收的数据应存储在字节数组中。
实际发生的事情:
程序给出“Buffer start或length out of bounds”错误!
任何帮助将不胜感激!
答案 0 :(得分:1)
您永远不会初始化数组bytes
。
使用byte[] bytes = new byte[32];
。
然后conn.bulkTransfer(end, bytes, bytes.length, 0);
是安全的,以防您需要更改数组的长度。