Android USB设备过滤器

时间:2014-10-20 19:35:17

标签: java android xml usb

我试图过滤某些设备以显示USB连接对话框,根据我的理解,这可以通过创建设备过滤器,指定要允许的设备,然后在我的活动中处理意图来完成。

我遇到的问题是,无论我连接的设备是什么,它都会提示(它不限制在device_filter.xml中的列表)。

如何将连接提示限制为device_filter.xml中列出的设备?

device_filter.xml

<?xml version="1.0" encoding="utf-8"?> <resources> <usb-device vendor-id="1027" product-id="24597"> <usb-device vendor-id="1659" product-id="8963" > </resources>

此文件包含我希望列入白名单的设备。

来自AndroidManifest.xml的

        <activity
        android:name=".Player"
        android:clearTaskOnLaunch="true"
        android:configChanges="orientation|keyboardHidden"
        android:exported="true"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        </intent-filter>

        <meta-data
            android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
            android:resource="@xml/device_filter" />
    </activity>

在我的活动中

if (intent.getAction() != null){
        if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
            Context context = getApplicationContext();
            try
            {
                PackageManager pm = context.getPackageManager();
                ApplicationInfo ai = pm.getApplicationInfo( "com.package.name", 0 );
                if( ai != null )
                {
                    UsbManager manager = (UsbManager) context.getSystemService( Context.USB_SERVICE );
                    IBinder b = ServiceManager.getService( Context.USB_SERVICE );
                    IUsbManager service = IUsbManager.Stub.asInterface( b );

                    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();

                    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
                    while( deviceIterator.hasNext() )
                    {
                        UsbDevice device = deviceIterator.next();
                        Log.d ("DERP", "The Vendor ID is: "+device.getVendorId());
                        Log.d ("DERP", "The interface is: "+device.getInterfaceCount());

                        //service.grantDevicePermission( device, ai.uid );
                        //service.setDevicePackage( device, "com.package.name");
                    }
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

A little bit late, but your filter is not well formed:

<usb-device vendor-id="1027" product-id="24597" />

You're missing a slash (/) to close the tag.