0

I have a BroadcastReceiver to listen to the connection and disconnection of the device via USB. USB_DEVICE_ATTACHED does not work when connecting the scanner (scanner #1) to the device (Android OS 6) via USB. When the scanner is disconnected, USB_DEVICE_ATTACHED is triggered, and then immediately USB_DEVICE_DETACHED. Why doesn't USB_DEVICE_ATTACHED fire when connected? If you connect another scanner, then everything is fine, immediately upon connection, USB_DEVICE_ATTACHED is triggered. In addition, if you connect scanner No. 1 to another device (Android OS 10), then everything also works when connected. What could be the reason? I would be glad for any hint.

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ru.evotor.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".TestReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

TestReceiver

class TestReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d("MyLog", "onReceive")
        intent?.let { intent: Intent ->
            intent.action?.let { action: String ->
                Log.d("MyLog", "action $action")
            }
        }
    }
}
  • Possible duplicate of https://stackoverflow.com/questions/64751962/usb-device-attached-without-a-device-filter-in-android-10 – Robert Jun 09 '22 at 16:00
  • Unfortunately it doesn't suit me. – TOvchinnikova Jun 10 '22 at 04:46
  • Please place the entry within a launcher activity, not a service or a receiver. https://developer.android.com/guide/topics/connectivity/usb/host#manifest-example https://stackoverflow.com/questions/6163856/usb-device-attached-intent-not-firing – ecle Sep 15 '22 at 01:01

1 Answers1

0

Add this in your manifest file:

<service
    android:name=".UsbService"
    android:enabled="true"
    android:exported="true">

    <intent-filter>
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
    </intent-filter>
</service>
SerjantArbuz
  • 982
  • 1
  • 12
  • 16