Skip to content

Instantly share code, notes, and snippets.

@tito
Created November 12, 2013 15:28
Show Gist options
  • Save tito/7432757 to your computer and use it in GitHub Desktop.
Save tito/7432757 to your computer and use it in GitHub Desktop.
Bluetooth example on Android using Python / Pyjnius
'''
Bluetooth/Pyjnius example
=========================
This was used to send some bytes to an arduino via bluetooth.
The app must have BLUETOOTH and BLUETOOTH_ADMIN permissions (well, i didn't
tested without BLUETOOTH_ADMIN, maybe it works.)
Connect your device to your phone, via the bluetooth menu. After the
pairing is done, you'll be able to use it in the app.
'''
from jnius import autoclass
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket')
UUID = autoclass('java.util.UUID')
def get_socket_stream(name):
paired_devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray()
socket = None
for device in paired_devices:
if device.getName() == name:
socket = device.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
recv_stream = socket.getInputStream()
send_stream = socket.getOutputStream()
break
socket.connect()
return recv_stream, send_stream
if __name__ == '__main__':
recv_stream, send_stream = get_socket_stream('linvor')
send_stream.write('hello\n')
send_stream.flush()
# Same as before, with a kivy-based UI
'''
Bluetooth/Pyjnius example
=========================
This was used to send some bytes to an arduino via bluetooth.
The app must have BLUETOOTH and BLUETOOTH_ADMIN permissions (well, i didn't
tested without BLUETOOTH_ADMIN, maybe it works.)
Connect your device to your phone, via the bluetooth menu. After the
pairing is done, you'll be able to use it in the app.
'''
from jnius import autoclass
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket')
UUID = autoclass('java.util.UUID')
def get_socket_stream(name):
paired_devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray()
socket = None
for device in paired_devices:
if device.getName() == name:
socket = device.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
recv_stream = socket.getInputStream()
send_stream = socket.getOutputStream()
break
socket.connect()
return recv_stream, send_stream
if __name__ == '__main__':
kv = '''
BoxLayout:
Button:
text: '0'
on_release: app.reset([b1, b2, b3, b4, b5])
ToggleButton:
id: b1
text: '1'
on_release: app.send(self.text)
ToggleButton:
id: b2
text: '2'
on_release: app.send(self.text)
ToggleButton:
id: b3
text: '3'
on_release: app.send(self.text)
ToggleButton:
id: b4
text: '4'
on_release: app.send(self.text)
ToggleButton:
id: b5
text: '5'
on_release: app.send(self.text)
'''
from kivy.lang import Builder
from kivy.app import App
class Bluetooth(App):
def build(self):
self.recv_stream, self.send_stream = get_socket_stream('linvor')
return Builder.load_string(kv)
def send(self, cmd):
self.send_stream.write('{}\n'.format(cmd))
self.send_stream.flush()
def reset(self, btns):
for btn in btns:
btn.state = 'normal'
self.send('0\n')
Bluetooth().run()
@frankchih
Copy link

Sorry!
I have error..... , Can you help me... Thanks.
error message:
Traceback (most recent call last):
File "/home/frank/workspace/798/bluetooth.py", line 13, in
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
File "/home/frank/package/kivyPython2Venv/local/lib/python2.7/site-packages/jnius/reflect.py", line 106, in autoclass
c = find_javaclass(clsname)
File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:7190)
jnius.JavaException: Class not found 'android/bluetooth/BluetoothAdapter'

@evbo
Copy link

evbo commented Mar 14, 2016

In order to get this to work, I had to make use of the python-for-android annotations: @run_on_ui_thread. Is this is a new requirement?

Without them, I was getting the error: Can't create handler inside thread that has not called Looper.prepare()

from android.runnable import run_on_ui_thread
class Bluetooth(App):
    def build(self):
        return Builder.load_string(kv)

    @run_on_ui_thread
    def send(self, cmd):
        self.send_stream.write('{}\n'.format(cmd))
        self.send_stream.flush()

    @run_on_ui_thread
    def reset(self, btns):
        for btn in btns:
            btn.state = 'normal'
        paired_devices = BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray()
        Logger.info(str(paired_devices))
        if len(paired_devices):
        for device in paired_devices:
        Logger.info(str(device))
        socket = device.createRfcommSocketToServiceRecord(
            UUID.fromString("0fee0450-e95f-11e5-a837-0800200c9a66"))
        self.recv_stream = socket.getInputStream()
        self.send_stream = socket.getOutputStream()
        break
        socket.connect()
        self.send('0\n')

@jlbs86
Copy link

jlbs86 commented Apr 18, 2016

I have the same error than #frankchin :

Traceback (most recent call last):
File "bluetooth.py", line 8, in
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
File "/usr/local/lib/python2.7/dist-packages/jnius/reflect.py", line 154, in autoclass
c = find_javaclass(clsname)
File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:12117)
jnius.JavaException: Class not found 'android/bluetooth/BluetoothAdapter'

could you help me please? and thanks in advance!!

@nranudeep
Copy link

I am trying to read from the socket stream.
So when I give
data = self.recv_stream.read() after sending a command, I was being kicked out of the app?

I am newbie... Can anyone point me to the right direction?

Thanks

@riddy6421
Copy link

riddy6421 commented Jan 23, 2018

@frankchih Did you get a solution to the error?

@ankitmaisuriya
Copy link

I have one .py file, I want to send one character as a parameter through that Python function from Android application. that Python function will send the signal through Bluetooth to arduino.
Please help me out how can i call the .py function in Android application.

Process p = Runtime.getRuntime().exec("python run.py " + "A");
its showing error :
ProcessManager: waitpid on failed exec failed: No child processes
W/System.err: Error running exec(). Command: Working Directory: null Environment: null

@cagsurgunu
Copy link

cagsurgunu commented May 21, 2018

i compile bluetooth_kivy for android apk with buildozer. But my app can't run. how can fix it? My app folder includes two file: buildozer.spec and main.py(bluetooth_kivy is renamed). Do i need java file for bluetooth.

@andersonms1
Copy link

Sorry!
I have error..... , Can you help me... Thanks.
error message:
Traceback (most recent call last):
File "/home/frank/workspace/798/bluetooth.py", line 13, in
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
File "/home/frank/package/kivyPython2Venv/local/lib/python2.7/site-packages/jnius/reflect.py", line 106, in autoclass
c = find_javaclass(clsname)
File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:7190)
jnius.JavaException: Class not found 'android/bluetooth/BluetoothAdapter'

This is still relevant so...

To run this use buildozer.
See also https://github.com/b3b/able

@morgansong
Copy link

@andersonms1, for this kind of error message "jnius.JavaException: Class not found xxxxxxxxx", You have to run inside android phone instead of windows laptop.

@horald
Copy link

horald commented Mar 20, 2021

How do I install the jnius module on Pydroid? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment