首页 » Android » android USB Accessory

android USB Accessory

2017-05-21 12:21:54阅读(833)

AOA插上,系统广播接收不到Intent(包含ACCESSORY_ATTACHED Action),但是activity能够收到系统发送的Intent(包含ACCESSORY_ATTACHED Action)
1 在AOA插上,activity能够收到系统发送的Intent(包含ACCESSORY_ATTACHED Action)

    <intent-filter>
        <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
    </intent-filter>
    <meta-data
        android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
        android:resource="@xml/accessory_filter" />

2 如果APP已经启动,此时插拔AOA,可通过onNewIntent,//APP正在运行,插拔AOA,获取到系统发送的Intent(包含ACCESSORY_ATTACHED信息)

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(intent.getAction())) {
            addDebugText("ACTION_USB_ACCESSORY_ATTACHED");
            final UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                if (accessory != null) {
                    addDebugText("usb EXTRA_PERMISSION_GRANTED");
                }
            } else {
                addDebugText("usb EXTRA_PERMISSION_GRANTED null!!!");
                // set permision
                synchronized (this) {
                    mUsbManager.requestPermission(accessory, mPermissionIntent);
                }
            }
        }
    }

3 AOA已经插上,(启动了其他APP或者杀死了自己的APP进程)再启动APP,要主动去判断AOA是否连接上,连接上则获取USB权限

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usb_accessory);
        //手动启动APP后,判断AOA是否连接上,连接上的则弹框请求USB权限,
        if(mUsbManager.getAccessoryList() != null && mUsbManager.getAccessoryList().length>0){
            Intent intent = getIntent();
            //final UsbAccessory accessory = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);  //unusefull 手动启动APP,Intent里面没有设置EXTRA_ACCESSORY
            final UsbAccessory accessory = mUsbManager.getAccessoryList()[0];
            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                if (accessory != null) {
                    addDebugText("usb EXTRA_PERMISSION_GRANTED");
                }
            } else {
                addDebugText("usb EXTRA_PERMISSION_GRANTED null!!!");
                // set permision
                synchronized (this) {
                    mUsbManager.requestPermission(accessory, mPermissionIntent);
                }
            }
        }
    }

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹