我想构建一个能够连接到USB设备中几个不同接口的应用程序。我试图使用AsyncTasks和Executor来实现这一点,但是当我实例化一个新的AsyncTask时,它给了我错误:“无法执行任务:任务已经在运行。”为什么会这样?我在doInBackground方法上有一个无限循环,但我认为这个过程与那个过程并行。有人能帮助我吗?
代码:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void addInterface (UsbInterface intf, UsbEndpoint ep){
if (selectedDevice != null && intf != null && ep != null) {
if (mConnection != null && mConnection.claimInterface(intf, true)) {
listOfSelectedUsbInterface.add(intf);
listOfSelectedUsbEndpoint.add(ep);
bufferList.add(ByteBuffer.allocate(ep.getMaxPacketSize())) ;
requestList.add(new UsbRequest());
requestList.get(requestList.size()-1).initialize(mConnection, listOfSelectedUsbEndpoint.get(listOfSelectedUsbEndpoint.size() - 1));
int index= listOfSelectedUsbEndpoint.size()-1;
AsyncTask taskToAdd = new USB_asyncTask().execute(new Integer(index));
taskToAdd.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Log.d(TAG, "Number o endpoints: " + listOfSelectedUsbEndpoint.size());
}
else {
Log.d(TAG, "Device open FAIL");
mConnection = null;
}
}
}
private class USB_asyncTask extends AsyncTask <Integer,Void,String> {
@Override
protected String doInBackground( Integer... idx) {
int index = idx[0].intValue();
while(true) {
requestList.get(index).queue(bufferList.get(index), listOfSelectedUsbEndpoint.get(index).getMaxPacketSize());
Log.d(TAG, "Interrupt in " + index );
// wait for status event
if (mConnection.requestWait() == requestList.get(index)) {
String str = "Interface Id (" + listOfSelectedUsbInterface.get(index).getId() + "): " + String.format("%02X", bufferList.get(index).get(0));
for (int i = 1; i < listOfSelectedUsbEndpoint.get(index).getMaxPacketSize(); i++) {
str += String.format(":%02X", bufferList.get(index).get(i));
}
final String stringtodisplay=str;
runOnUiThread(new Runnable() {
@Override
public void run() {
textInfo.setText(stringtodisplay);
}
});
}
}
}