I have a Flutter app which uses the usb_serial
plugin to connect to serial devices on the USB-port.
In my Android manifest I have
<activity
android:name=".MainActivity"
android:launchMode="singleTask"
and
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
Despite having singleTask
(I have also tried singleInstance
), if the user has the app running, a USB serial-device attached, and reboots their phone/tablet, there will be two “instances” of the app in the recent tasks list after reboot. If they then reboot again, after next boot there will be 3 instances, etc.
Removing the USB_DEVICE_ATTACHED
intent filter stops this from happening, but a side effect of that is that the app will ask for permission to use the USB device every single time it is attached (even if the user checks “Always allow”, which is a well known feature/bug in Android).
One thing to note is that only one of the app instances actually runs on boot, the other one is just sitting there in the recent task list in a non-running state, until the user accidentally switches to it and suddenly has two instances of the same app running.
The problem with this is of course that they end up with weird concurrency issues, and especially the USB serial connection stops working and/or reconnects/disconnects, etc.
So is there a way to avoid ever having two instances of the same app running? As mentioned, singleTask
and singleInstance
have no effect on this issue. So I guess one option would be to somehow, from inside my app, check if the app is already running and if so switch to the running instance and kill the new one. But is there a way to achieve something like this?
The app is a Flutter app, but I guess if there is a way to do it in pure Android it might be achievable using native code via method channels or something.