0

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

Parth
  • 1,908
  • 1
  • 19
  • 37

2 Answers2

0

Use BroadcastReceiver for USB_DEVICE_ATTACHED

and in onReceive() Use this

Bhavesh Desai
  • 753
  • 4
  • 20
  • if I insert USB hardware again then it should not ask user permission to use this hardware. Android will remember hardware. – Parth Jan 17 '18 at 06:30
0

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"

Parth
  • 1,908
  • 1
  • 19
  • 37