我一直在玩 Android Open Accessory Development Kit。通过遵循Google 提供的 DemoKit 示例,我可以毫不费力地将解决方案适应我的应用程序。我可以很好地检测、通信和分离附件。
但是,我需要将整个事情作为服务运行。我有一个由 USB_ACCESSORY_ATTACHED 意图(即连接附件时)启动的基本活动,并且工作正常。但是,一旦我启动服务并在其中运行与常规活动中的工作解决方案相同的代码,IOException
每当我尝试与附件通信(监控 arduino 端)时,我都会收到一个(“没有这样的设备”)显示成功的 USB 连接)。即使我在服务中指定了正确的 BroadcastReceiver、在 onStartCommand 回调方法中注册它并使用openAccessory()
. 相关代码如下。
@Override
public void onCreate() {
Log.d(TAG, "ONCREATE");
manager = UsbManager.getInstance(this);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
// Register broadcastreceiver for filtering accessory events
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver,filter);
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "ONSTARTCOMMAND METHOD ACCESSED");
if (mInputStream != null && mOutputStream != null) {
return START_NOT_STICKY;
}
UsbAccessory[] accessories = manager.getAccessoryList();
mAccessory = (accessories == null ? null : accessories[0]);
if (mAccessory != null) {
if (manager.hasPermission(mAccessory)) {
openAccessory();
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
manager.requestPermission(mAccessory,
mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
Log.d(TAG, "mAccessory is null");
}
return START_NOT_STICKY;
}
打开附件方法:
/**
* Open the accessory
*/
private void openAccessory() {
Log.d(TAG, "openAccessory: "+mAccessory);
mFileDescriptor = manager.openAccessory(mAccessory);
if (mFileDescriptor != null) {
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null,this,"AccessoryThread");
thread.start();
}
}
任何可能的解决方案的想法?