Search code examples
androidandroid-activityusbintentfilter

Android do not launch activity when app is running (on IntentFilter match)


I am working on USB device connection. Here my Android phone will work on HOST mode.

I Have specified Intent filter in manifest like:

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

so whenever my device will connect it will show the popup for USB permission and Launch the TestActivity.

But if My app is running and i am in other activity then also it is launching test activity.

Here I want to avoid launch activity again if my app is already running. Is it possible?

Thanks


Solution

  • Here I have the workaround for this. here Intent is registered to the activity so activity will launch definitely on hardware connection ( ie: on receive of this action <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />)

    1. Create activity without setting layout and add finish on create.if you want to get device detail then you can get from here.
    onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UsbDevice device = (UsbDevice)getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);
        finish();
    }
    
    1. Manifest file add set theme for your activity (here TestActivity)

    android:theme="@android:style/Theme.NoDisplay"