0

I used dynamic broadcast can receive UsbManager.ACTION_USB_DEVICE_ATTACHED and UsbManager.ACTION_USB_DEVICE_DETACHED event.

But when my app is not run,the usb device have been plugged,the dynamic broadcast is not receive it. So I want to when my app is first run, i can check it.

I used static broadcast can receive the event,but i don't want to use the method,is it have other method?

ADM
  • 20,406
  • 11
  • 52
  • 83
pengwang
  • 19,536
  • 34
  • 119
  • 168

2 Answers2

1

You can use UsbManager class and get list of connected device, Try using below method and call it in onCreate

private void findSerialPortDevice() {
    // This snippet will try to open the first encountered usb device connected, excluding usb root hubs
    UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();

    if (!usbDevices.isEmpty()) {
        boolean keep = true;
        for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
            device = entry.getValue();
            int deviceVID = device.getVendorId();
            int devicePID = device.getProductId();
            intf = device.getInterface(0);
            if(device != null && !device.equals(""))
                Utils.writeIntoFile(getBaseContext(),"device =============>"+device+"\n"+"getInterface Count =============>"+device.getInterfaceCount());
                // There is a device connected to our Android device. Try to open it as a Serial Port.
            } else {
                    connection = null;
                    device = null;
                }
            }

            if (!keep)
                break;
        }
        if (!keep) {
            // There is no USB devices connected.

        }
    } else {
        // There is no USB devices connected.
    }
}
karan
  • 8,637
  • 3
  • 41
  • 78
1

If you want to get your app started when a device is attached, you have to register the VID/PID of the USB devices in your manifest

<activity
    android:name="..."
    ...>
    <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>

and device_filter.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 0x0403 / 0x6001: FTDI FT232R UART -->
    <usb-device vendor-id="1027" product-id="24577" />
...

e.g. as mentioned here

kai-morich
  • 427
  • 2
  • 7