Android USB开发麻烦还是比较多的。
第一种:host模式
这种模式比较不错,由Android设备提供电源,然后与外部设备通信。举个例子来说:电脑连接USB设备,都是这个模式,非常常见的模式。
但是有一个万恶的问题,android接外部USB设备的时候,驱动怎么办?又有那款芯片敢说Android系统支持他们家的芯片,又有哪个厂家说不动android系统装上他们家的驱动,他们家的设备就可以在Android上使用,或许这点上Android很难超越windows。
造成想现状:想加外部设备,都要:重新自己做底层驱动程序--->编译系统--->刷机--->编写android程序--->接入硬件实现功能。
整个一套下来饭都吃好几顿了。还是希望以后android发展发展能向window一样支持多设备驱动吧。
第二种:Accessory模式
这个模式比较揪心,外部设备要供给电源,数据间通信:电脑---手机就是这种模式,手机作为Accessory设备,电脑供给它电源,同时进行数据通信。
恰巧我也是用了这种模式:
程序需要做的:
(1)添加Action BoardCast
private static final String ACTION_USB_PERMISSION ="com.ukey.USB_PERMISSION";
/***********USB broadcast receiver*******************************************/ private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbAccessory accessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { Toast.makeText(global_context, "Allow USB Permission", Toast.LENGTH_SHORT).show(); OpenAccessory(accessory); }else{ Toast.makeText(global_context, "Deny USB Permission", Toast.LENGTH_SHORT).show(); } mPermissionRequestPending = false; } } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)){ DestroyAccessory(true); }else{ Log.d("LED", "...."); } } };
android每次使用Accessory的时候都会询问你是否允许设备访问,这会点击是或否的结果又(2)中代码
启动请求。
(4)openAccessory功能
public int OpenAccessory() { // Intent intent = getIntent(); if (inputstream != null && outputstream != null) { return 1; } UsbAccessory[] accessories = usbmanager.getAccessoryList(); if(accessories != null){ Toast.makeText(global_context, "Accessory Attached", Toast.LENGTH_SHORT).show(); }else{ // return 2 for accessory detached case return 2; } UsbAccessory accessory = (accessories == null ? null : accessories[0]); if (accessory != null) { if( -1 == accessory.toString().indexOf(ManufacturerString)){ Toast.makeText(global_context, "Manufacturer is not matched!", Toast.LENGTH_SHORT).show(); return 1; } if( -1 == accessory.toString().indexOf(ModelString1) && -1 == accessory.toString().indexOf(ModelString2)) { Toast.makeText(global_context, "Model is not matched!", Toast.LENGTH_SHORT).show(); return 1; }if( -1 == accessory.toString().indexOf(VersionString)) { Toast.makeText(global_context, "Version is not matched!", Toast.LENGTH_SHORT).show(); return 1; } Toast.makeText(global_context, "Manufacturer, Model & Version are matched!", Toast.LENGTH_SHORT).show(); if (usbmanager.hasPermission(accessory)) { OpenAccessory(accessory); }else{ synchronized (mUsbReceiver) { if (!mPermissionRequestPending) { Toast.makeText(global_context, "Request USB Permission", Toast.LENGTH_SHORT).show(); usbmanager.requestPermission(accessory,mPermissionIntent); mPermissionRequestPending = true; } } } } return 0; }