我想创建一个Android应用程序来找到我的micro-usb(智能卡读卡器设备),所以我在智能卡中接收数据有问题(我通过方法usbDeviceConnection.bulkTransfer向智能卡发送了一个APDU,即0x ...但我不知道如何接收数据或回复的东西(它必须在发送命令后回复卡中的数据)。当它回答时我怎样才能编码或将十六进制转换为字符串?< / p>
我想,(参考代码)我有一个2端点所以我对endpointIn和endpointOut有疑问。这些参数是什么?如何使用它在设备和应用程序之间发送和接收数据?我认为对不对?什么是BroadcastReceiver呢?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textview);
//register the broadcast receiver
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
registerReceiver(mUsbDeviceReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
registerReceiver(mUsbDeviceReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
connectUsb();
}
这是connectUSB方法。
private void connectUsb() {
Toast.makeText(MainActivity.this,
"connectUsb()",
Toast.LENGTH_LONG).show();
searchEndPoint();
if (usbInterfaceFound != null) {
setupUsbComm();
threadUsbTx = new ThreadUsbTx(usbDeviceConnection, endpointOut);
threadUsbTx.start();
//bytes are APDU to send for get data from card.
threadUsbTx.insertCmd(
new byte[]{(byte) 0xA0, (byte) 0xA4, 0x00, 0x00, 0x02, 0x3F, 0x00});
threadUsbTx.insertCmd(
new byte[]{(byte)0x80, (byte)0xb0, 0x00, 0x04, 0x02, 0x00, 0x0d});
threadUsbTx.insertCmd(
new byte[]{0x00, (byte)0xc0, 0x00, 0x00, 0x0d});
}
}
这是ThreadUsbTx类..
class ThreadUsbTx extends Thread {
boolean running;
UsbDeviceConnection txConnection;
UsbEndpoint txEndpoint;
Queue<byte[]> cmdQueue;
byte[] cmdToSent;
ThreadUsbTx(UsbDeviceConnection conn, UsbEndpoint endpoint) {
txConnection = conn;
txEndpoint = endpoint;
cmdQueue = new LinkedList<byte[]>();
cmdToSent = null;
running = true;
}
public void setRunning(boolean r) {
running = r;
}
public void insertCmd(byte[] cmd) {
synchronized (cmdQueue) {
cmdQueue.add(cmd);
}
}
@Override
public void run() {
while (running) {
synchronized (cmdQueue) {
if (cmdQueue.size() > 0) {
cmdToSent = cmdQueue.remove();
}
}
if (cmdToSent != null) {
final int usbResult = usbDeviceConnection.bulkTransfer(
txEndpoint,
cmdToSent,
cmdToSent.length,
0);
final String s = new String(cmdToSent);
String result = null;
try {
result = new String(cmdToSent,"TIS620"); // To Thai language
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final String finalResult = result;
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,
finalResult+" "+String.format("%040x",cmdToSent),
Toast.LENGTH_LONG).show();
}
});
cmdToSent = null;
}
}
}
}
答案 0 :(得分:0)
与USB读卡器通信的最佳方式是使用符合CCID标准的手机以及支持OTG的手机。看一下App&#34; CCID Reader Application Demo&#34;在Playstore中。同样有用the library可用here。否则,您必须在代码中实现或多或少的CCID行为