I'm developing an app which picks up Bluetooth devices using Device Discovery, specifically the function uses Broadcast Receiver
. To speed things up I wanted to thread that function to make it faster and to not lag the UI in Kivy which happens on a MainThread
. I've been stuck on this for a while and I'm running out of patience. I'm not really new to Python but this is my first real big project. I don't understand Java but I can get an idea.
def example(self, *args):
# [...] code
from android.broadcast import BroadcastReceiver
self.broadcast_receiver = BroadcastReceiver(self.bluetooth_devices, actions=[self.BluetoothDevice.ACTION_FOUND])
self.broadcast_receiver.start()
# [...] more code
self.broadcast_receiver.stop()
def bluetooth_devices(self, context, intent):
device = cast(self.BluetoothDevice, intent.getParcelableExtra(self.BluetoothDevice.EXTRA_DEVICE))
# [...] code that finds detected devices
I know for a definite the callback in BroadcastReceiver is not the problem, because it runs fine when function example
is not Threaded. However, minute we put it into a Thread it throws this exception:
JVM exception occurred: Didn't find class
"org.kivy.android.GenericBroadcastReceiver" on path: DexPathList[[directory "."],
nativeLibraryDirectories=[/system/lib64,
/system/lib64]]
java.lang.ClassNotFoundException
From my understanding this must mean that when function consisting of BroadcastReceiver is threaded it potentially loses access to the class it needs to access to start. If so, is there a solution for this?
I'm also aware that BroadcastReceiver
has HandlerThread
.
Problem relied with BroadcastReceiver
as it is done asynchronously, somehow putting it a separate Thread than MainThread
looks for the class in a wrong place.
What I ended up doing was initialising variable responsible for BroadcastReceiver
in the class constructor as class variable then .start()
when you press button Start and .stop()
when you Stop the device scan. Then, as a precaution I defined the BroadcastReceiver
variable to None
and redefined it same way as in the constructor but in the function responsible for stopping the scan.