簡體   English   中英

Android:從意圖接收UsbDevice

[英]Android: Receive UsbDevice from intent

我正在搞亂USB主機,並遵循Android開發者網站的指導原則我設法創建了一個Hello World,一旦插入特定的USB設備就會啟動。但是,當我嘗試“...時...從意圖“它返回null”獲取表示附加設備的UsbDevice:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent();
    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);


    // device is always null
    if (device == null){Log.i(TAG,"Null device");}

這是我的清單:

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />
        </activity>
    </application>

我的xml / device_filter.xml(我知道這些是正確的VID和PID,因為我有一個使用Android開發者網站描述的枚舉方法的類似應用程序):

<resources>
    <usb-device vendor-id="1234" product-id="1234"/>
</resources>

當您的應用程序由於USB設備附加事件而(重新)啟動時,設備將在調用onResume時傳遞給intent。 您可以使用getParcelableExtra方法訪問它。 例如:

@Override
protected void onResume() {
    super.onResume();

    Intent intent = getIntent();
    if (intent != null) {
        Log.d("onResume", "intent: " + intent.toString());
        if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
            UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (usbDevice != null) {
                Log.d("onResume", "USB device attached: name: " + usbDevice.getDeviceName());

感謝泰勒亞歷山大,我找到了解決方法(或預期用途?) 基本上,我理解它的方式是觸發打開應用程序的意圖只打開應用程序 之后,您必須根據onResume方法中Android Developers頁面的Enumerating Devices部分搜索並訪問usb設備。

@Override
    public void onResume() {
        super.onResume();

        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

        while(deviceIterator.hasNext()){
            UsbDevice device = deviceIterator.next();
                // Your code here!
        }

我不相信這是做這件事的正確方法,但似乎有效。 如果有人有任何進一步的建議,我會很高興聽。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM