Android Question Capturing USB_ATTACHED event

yo3ggx

Active Member
Licensed User
Longtime User
I have an application using USB/Serial and USB audio devices. In the manifest.xml file I have the following section, used to make the app start when a specific USB serial device is connected:
B4X:
AddActivityText(main, <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" />)

Then the resource file is created from manifest.xml too:

B4X:
CreateResource(xml, device_filter.xml,
<resources>
    <!-- 0x0403 / 0x6015: FTDI FT230XS UART -->
    <usb-device vendor-id="1027" product-id="24597" />
    
</resources>
)

In the main code, I'm using BroadcastReceiver library to capture the following events:
B4X:
        Broadcast.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED")
        Broadcast.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED")

I need this to handle the situations when USB devices are connected/disconnected when the application is running. UNfortunately because USB_DEVICE_ATTACHED event is captured through the manifest file, the BroadcastReceiver even is no more triggered inside the app for the same event, only for USB_DEVICE_DETACHED

What can I do to capture this event from the app code?

Thank you.
Dan
 

yo3ggx

Active Member
Licensed User
Longtime User
If I don't add the filter in the manifest file, the event is triggered in BroadcastReceiver even without the java code.
If I keep the USB_DEVICE_ATTACHED filter in manifest file, this event is no more captured in BroadcastReceiver, only the
USB_DEVICE_DETACHED is.
If I remove the event from manifest, then I'm asked to approve USB device each time I connect it, even if I choose to accept it always by default.
 
Upvote 0

yo3ggx

Active Member
Licensed User
Longtime User
There is any other way to capture the event when audio goes from local speaker to the USB audio? This can solve my problem too, as I don't need to capture in my app when USB Serial device is connected, only when USB audio device is.
 
Upvote 0

yo3ggx

Active Member
Licensed User
Longtime User
I've commented the following lines in manifest:
B4X:
'AddActivityText(main, <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" />)

Then I've added the java code you provided, but nothing is logged when connecting or disconnecting USB device. I'm not yet familiar with inline java code. I have to put it in a specific place? I have to comment BroadcastReceiver too?
 
Upvote 0
Top