1

I tried to implement this Python/ Pyjnus Bluetooth code to my own code where I am also trying to build a Bluetooth connection to a HC-05 Module with an Android App built with the Kivy and KivyMD Framework, but I got different errors while compiling and testing with PyCharm and also after compiling the Code to an APK by looking at the adb logcat log. So I'm here to ask everyone who reads this question for Help.

I implemented the linked code above as Alex(who wrote this code) did and also called the getAndroidBluetoothSocket Method by an MDIconbutton press. Therefore I "renamed" the AndroidBluetooth Class with AndroidBluetooth = AndroidBluetoothClass(). I have also added some print and toast Messages to debug the application.

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.toast import toast
from jnius import autoclass

layout = '''
BoxLayout:
    id: boxlayout
    orientation:'vertical'
    adaptive_size: True

    MDIconButton:
        icon: "bluetooth"
        pos_hint: {'center_x':0.5,'center_y':0.875}
        user_font_size: "40sp"
        on_release: AndroidBluetooth.getAndroidBluetoothSocket('HC-05')
'''

class AndroidBluetoothClass:

    def getAndroidBluetoothSocket(self,DeviceName):
        toast("AndroidBluetoothSocket")
        print("AndroidBluetoothSocket")
        paired_devices = self.BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray()
        socket = None
        for device in paired_devices:
            if device.getName() == DeviceName:
                socket = device.createRfcommSocketToServiceRecord(
                    self.UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
                self.ReceiveData = self.BufferReader(self.InputStream(socket.getInputStream()))
                self.SendData = socket.getOutputStream()
                socket.connect()
                self.ConnectionEstablished = True
                print('Bluetooth Connection successful')
                toast("Bluetooth Connection successful")
        return self.ConnectionEstablished

    def BluetoothSend(self, Message, *args):
        toast("Bluetooth send")
        print("Bluetooth send")
        if self.ConnectionEstablished == True:
            self.SendData.write(Message)
        else:
            print('Bluetooth device not connected')

    def BluetoothReceive(self,*args):
        toast("Bluetooth receive")
        print("Bluetooth receive")
        DataStream = ''
        if self.ConnectionEstablished == True:
            DataStream = str(self.ReceiveData.readline())
        return DataStream

    def __init__(self):
        toast("Bluetooth init")
        print("Bluetooth init")
        self.BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
        self.BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
        self.BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket')
        self.UUID = autoclass('java.util.UUID')
        self.BufferReader = autoclass('java.io.BufferedReader')
        self.InputStream = autoclass('java.io.InputStreamReader')
        self.ConnectionEstablished = False

    def __del__(self):
        toast("Bluetooth del")
        print('class AndroidBluetooth destroyer')

AndroidBluetooth = AndroidBluetoothClass()

class TestApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Green"
        return Builder.load_string(layout)

TestApp().run()

After trying to run the code in PyCharm on my Windows PC the following errors occur: [Picture of log]: https://i.stack.imgur.com/BWIz8.png

But I think those errors only occur because the Windows System can't work with those Android API Methods.

So I tried to compile it to an APK via Buildozer and run the APK.

# (str) Title of your application
title = Slider_debug

# (str) Package name
package.name = debug

# (str) Package domain (needed for android/ios packaging)
package.domain = org.mydebugapp

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 1.4

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy==2.0.0,https://github.com/kivymd/KivyMD/archive/master.zip,sdl2_ttf==2.0.15,pillow,pyjnius

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

# OSX Specific
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 2.0.0

# Android specific

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 1
#user

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
android.permissions = INTERNET,BLUETOOTH_ADMIN,BLUETOOTH
#user

# (int) Target Android API, should be as high as possible.
#android.api = 23

# (int) Minimum API your APK will support.
android.minapi = 22

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 19b

# (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi.
#android.ndk_api = 21

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
#android.skip_update = True

# (bool) If True, then automatically accept SDK license
# agreements. This is intended for automation only. If set to False,
# the default, you will be shown the license when first running
# buildozer.
# android.accept_sdk_license = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (str) Android app theme, default is ok for Kivy-based app
# android.apptheme = "@android:style/Theme.NoTitleBar"

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
#android.gradle_dependencies =

# (list) add java compile options
# this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option
# see https://developer.android.com/studio/write/java8-support for further information
# android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8"

# (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies}
# please enclose in double quotes 
# e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }"
#android.add_gradle_repositories =

# (list) packaging options to add 
# see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html
# can be necessary to solve conflicts in gradle_dependencies
# please enclose in double quotes 
# e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'"
#android.add_gradle_repositories =

# (list) Java classes to add as activities to the manifest.
#android.add_activities = com.example.ExampleActivity

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = standard

# (list) Android additional libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_arm64_v8a = libs/android-v8/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (list) Android shared libraries which will be added to AndroidManifest.xml using <uses-library> tag
#android.uses_library =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64
android.arch = armeabi-v7a

# (int) overrides automatic versionCode computation (used in build.gradle)
# this is not the same as app version and should only be edited if you know what you're doing
# android.numeric_version = 1

# Python for android (p4a) specific

# (str) python-for-android fork to use, defaults to upstream (kivy)
#p4a.fork = kivy

# (str) python-for-android branch to use, defaults to master
#p4a.branch = master

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

# (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask)
#p4a.port =

# iOS specific

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# Alternately, specify the URL and branch of a git checkout:
ios.kivy_ios_url = https://github.com/kivy/kivy-ios
ios.kivy_ios_branch = master

# Another platform dependency: ios-deploy
# Uncomment to use a custom checkout
#ios.ios_deploy_dir = ../ios_deploy
# Or specify URL and branch
ios.ios_deploy_url = https://github.com/phonegap/ios-deploy
ios.ios_deploy_branch = 1.7.0

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 1
#user

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
# ...

The Compilation worked fine and I installed it on a Huawei P8lite (Android 6.0). But the App crashed after pushing the Bluetooth Button. After running the adb logcat command on the CMD I got this log:

12-19 22:25:25.989 14966 14998 I python  : Initializing Python for Android
12-19 22:25:25.989 14966 14998 I python  : Setting additional env vars from p4a_env_vars.txt
12-19 22:25:25.989 14966 14998 I python  : Changing directory to the one provided by ANDROID_ARGUMENT
12-19 22:25:25.989 14966 14998 I python  : /data/user/0/org.mydebugapp.debug/files/app
12-19 22:25:25.993 14966 14998 I python  : Preparing to initialize python
12-19 22:25:25.993 14966 14998 I python  : _python_bundle dir exists
12-19 22:25:25.993 14966 14998 I python  : calculated paths to be...
12-19 22:25:25.993 14966 14998 I python  : /data/user/0/org.mydebugapp.debug/files/app/_python_bundle/stdlib.zip:/data/user/0/org.mydebugapp.debug/files/app/_python_bundle/modules
12-19 22:25:26.008 14966 14998 I python  : set wchar paths...
12-19 22:25:26.039 14966 14966 I HwSecImmHelper: mSecurityInputMethodService is null
12-19 22:25:26.039  3052  3074 I ActivityManager: Displayed org.mydebugapp.debug/org.kivy.android.PythonActivity: +493ms
12-19 22:25:26.039 14966 14966 I HwSecImmHelper: mSecurityInputMethodService is null
12-19 22:25:26.044  2457  2457 E HAL     : load: id=gralloc != hmi->id=gralloc
12-19 22:25:26.048  2457  2506 I [Gralloc]: alloc w[720] h[1208] format[1] usage[3842]
12-19 22:25:26.050  2457  2506 I [Gralloc]: alloc succ handle[0x558c9efd60] stride[720]
12-19 22:25:26.052  3759  3759 I GoogleInputMethodServic: GoogleInputMethodService.onFinishInput():3446
12-19 22:25:26.056  3759  3759 I GoogleInputMethodServic: GoogleInputMethodService.onStartInput():2028
12-19 22:25:26.057  3759  3759 I DeviceUnlockedTag: DeviceUnlockedTag.notifyDeviceLockStatusChanged():38 Notify device unlocked.
12-19 22:25:26.061  2457  2457 E HAL     : load: id=gralloc != hmi->id=gralloc
12-19 22:25:26.065  3848  3848 I HwLauncher: Launcher mUnlockScreenRunnbale  getOrientationEnabled false
12-19 22:25:26.065  3848  3848 I HwLauncher: Launcher onStop()
12-19 22:25:26.207 14966 14998 I python  : Initialized python
12-19 22:25:26.207 14966 14998 I python  : AND: Init threads
12-19 22:25:26.211 14966 14998 I python  : testing python print redirection
12-19 22:25:26.214 14966 14998 I python  : Android path ['.', '/data/user/0/org.mydebugapp.debug/files/app/_python_bundle/stdlib.zip', '/data/user/0/org.mydebugapp.debug/files/app/_python_bundle/modules', '/data/user/0/org.mydebugapp.debug/files/app/_python_bundle/site-packages']
12-19 22:25:26.214 14966 14998 I python  : os.environ is environ({'PATH': '/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin', 'ANDROID_BOOTLOGO': '1', 'ANDROID_ROOT': '/system', 'ANDROID_ASSETS': '/system/app', 'ANDROID_DATA': '/data', 'ANDROID_STORAGE': '/storage', 'EXTERNAL_STORAGE': '/sdcard', 'ASEC_MOUNTPOINT': '/mnt/asec', 'BOOTCLASSPATH': '/system/framework/core-libart.jar:/system/framework/conscrypt.jar:/system/framework/okhttp.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/telephony-common.jar:/system/framework/voip-common.jar:/system/framework/ims-common.jar:/system/framework/apache-xml.jar:/system/framework/org.apache.http.legacy.boot.jar:/system/framework/hwEmui.jar:/system/framework/hwTelephony-common.jar:/system/framework/hwframework.jar:/system/framework/org.simalliance.openmobileapi.jar:/system/framework/hwaps.jar:/system/framework/hwcustEmui.jar:/system/framework/hwcustTelephony-common.jar:/system/framework/hwcustframework.jar:/system/framework/VireCustomFramework.jar', 'SYSTEMSERVERCLASSPATH': '/system/framework/services.jar:/system/framework/ethernet-service.jar:/system/framework/wifi-service.jar:/system/framework/hwServices.jar:/system/framework/hwWifi-service.jar:/system/framework/hwcustServices.jar:/system/framework/hwcustwifi-service.jar', 'OEM_ROOT': '/hw_oem', 'CUST_POLICY_DIRS': '/system/emui/base:/system/emui/oversea:/system/emui:/system/global:/system/etc:/hw_oem:/cust/hw/normal:/data/cust:/cust_spec', 'ANDROID_PROPERTY_WORKSPACE': '11,0', 'ANDROID_SOCKET_zygote_secondary': '12', 'ANDROID_ENTRYPOINT': 'main.pyc', 'ANDROID_ARGUMENT': '/data/user/0/org.mydebugapp.debug/files/app', 'ANDROID_APP_PATH': '/data/user/0/org.mydebugapp.debug/files/app', 'ANDROID_PRIVATE': '/data/user/0/org.mydebugapp.debug/files', 'ANDROID_UNPACK': '/data/user/0/org.mydebugapp.debug/files/app', 'PYTHONHOME': '/data/user/0/org.mydebugapp.debug/files/app', 'PYTHONPATH': '/data/user/0/org.mydebugapp.debug/files/app:/data/user/0/org.mydebugapp.debug/files/app/lib', 'PYTHONOPTIMIZE': '2', 'P4A_BOOTSTRAP': 'SDL2', 'PYTHON_NAME': 'python', 'P4A_IS_WINDOWED': 'False', 'P4A_ORIENTATION': 'portrait', 'P4A_NUMERIC_VERSION': 'None', 'P4A_MINSDK': '22', 'LC_CTYPE': 'C.UTF-8'})
12-19 22:25:26.214 14966 14998 I python  : Android kivy bootstrap done. __name__ is __main__
12-19 22:25:26.214 14966 14998 I python  : AND: Ran string
12-19 22:25:26.214 14966 14998 I python  : Run user program, change dir and execute entrypoint
12-19 22:25:26.616 14966 14998 I python  : [INFO   ] [Logger      ] Record log in /data/user/0/org.mydebugapp.debug/files/app/.kivy/logs/kivy_21-12-19_7.txt
12-19 22:25:26.616 14966 14998 I python  : [INFO   ] [Kivy        ] v2.0.0
12-19 22:25:26.617 14966 14998 I python  : [INFO   ] [Kivy        ] Installed at "/data/user/0/org.mydebugapp.debug/files/app/_python_bundle/site-packages/kivy/__init__.pyc"
12-19 22:25:26.617 14966 14998 I python  : [INFO   ] [Python      ] v3.8.9 (default, Dec 19 2021, 14:43:16)
12-19 22:25:26.617 14966 14998 I python  : [Clang 8.0.2 (https://android.googlesource.com/toolchain/clang 40173bab62ec7462
12-19 22:25:26.618 14966 14998 I python  : [INFO   ] [Python      ] Interpreter at ""
12-19 22:25:26.625 14966 14998 I python  : [INFO   ] [KivyMD      ] 1.0.0.dev0, git-Unknown, 2021-12-19 (installed at "/data/user/0/org.mydebugapp.debug/files/app/_python_bundle/site-packages/kivymd/__init__.pyc")
12-19 22:25:26.640 14966 14998 I python  : [INFO   ] [Factory     ] 186 symbols loaded
12-19 22:25:29.594 14966 14998 I python  : [INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer ignored)
12-19 22:25:29.695 14966 14998 I python  : [INFO   ] [Text        ] Provider: sdl2
12-19 22:25:30.506  2483  2483 E Thermal-daemon: [ap] temp_new :27  temp_old :26
12-19 22:25:30.506  2483  2483 E Thermal-daemon: Report temperature: [ap] temp :27  report_threshold:1
12-19 22:25:30.693 14966 14998 I python  : [INFO   ] [Window      ] Provider: sdl2
12-19 22:25:30.757 14966 14998 E libEGL  : validate_display:255 error 3008 (EGL_BAD_DISPLAY)
12-19 22:25:30.762  2457  4025 I [Gralloc]: alloc w[720] h[1160] format[1] usage[3842]
12-19 22:25:30.765  2457  4025 I [Gralloc]: alloc succ handle[0x558ca98890] stride[720]
12-19 22:25:30.768 14966 14998 I python  : [INFO   ] [GL          ] Using the "OpenGL ES 2" graphics system
12-19 22:25:30.770 14966 14998 I python  : [INFO   ] [GL          ] Backend used <sdl2>
12-19 22:25:30.771 14966 14998 I python  : [INFO   ] [GL          ] OpenGL version <b'OpenGL ES 2.0'>
12-19 22:25:30.772 14966 14998 I python  : [INFO   ] [GL          ] OpenGL vendor <b'ARM'>
12-19 22:25:30.773 14966 14998 I python  : [INFO   ] [GL          ] OpenGL renderer <b'Mali-450 MP'>
12-19 22:25:30.774 14966 14998 I python  : [INFO   ] [GL          ] OpenGL parsed version: 2, 0
12-19 22:25:30.774 14966 14998 I python  : [INFO   ] [GL          ] Texture max size <4096>
12-19 22:25:30.775 14966 14998 I python  : [INFO   ] [GL          ] Texture max units <8>
12-19 22:25:30.833 14966 14998 I python  : [INFO   ] [Window      ] auto add sdl2 input provider
12-19 22:25:30.836 14966 14998 I python  : [INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
12-19 22:25:31.426 14966 14998 I python  : Bluetooth init
12-19 22:25:31.481  2457 10316 I [Gralloc]: alloc w[236] h[82] format[1] usage[3842]
12-19 22:25:31.481  2457 10316 I [Gralloc]: alloc succ handle[0x558ca27100] stride[236]
12-19 22:25:31.482  2457  2508 I [Gralloc]: alloc w[236] h[82] format[1] usage[3842]
12-19 22:25:31.482  2457  2508 I [Gralloc]: alloc succ handle[0x558cb15680] stride[236]
12-19 22:25:31.482  2457  2508 I [Gralloc]: alloc w[236] h[82] format[1] usage[3842]
12-19 22:25:31.483  2457  2508 I [Gralloc]: alloc succ handle[0x558cad4c10] stride[236]
12-19 22:25:31.483  2457  2508 I [Gralloc]: alloc w[236] h[82] format[1] usage[3842]
12-19 22:25:31.483  2457  2508 I [Gralloc]: alloc succ handle[0x558cad4de0] stride[236]
12-19 22:25:31.508  2457  2457 E HAL     : load: id=gralloc != hmi->id=gralloc
12-19 22:25:31.893 14966 14998 I python  : [INFO   ] [GL          ] NPOT texture support is available
12-19 22:25:33.037 14966 14998 I python  : [WARNING] Deprecated property "<OptionProperty name=theme_text_color>" of object "<kivymd.uix.button.button.MDIconButton object at 0xd341a760>" was accessed, it will be removed in a future version
12-19 22:25:33.041 14966 14998 I python  : [WARNING] [Base        ] Unknown <android> provider
12-19 22:25:33.042 14966 14998 I python  : [INFO   ] [Base        ] Start application main loop
12-19 22:25:33.046 14966 14998 I python  : [WARNING] Deprecated property "<ColorProperty name=text_color>" of object "<kivymd.uix.button.button.MDIconButton object at 0xd341a760>" was accessed, it will be removed in a future version
12-19 22:25:33.118  2457  2457 E HAL     : load: id=gralloc != hmi->id=gralloc
12-19 22:25:33.548  2457  2508 I [Gralloc]: alloc w[720] h[1160] format[1] usage[3842]
12-19 22:25:33.559  2457  2508 I [Gralloc]: alloc succ handle[0x558caac420] stride[720]
12-19 22:25:33.583  2457  2457 E HAL     : load: id=gralloc != hmi->id=gralloc
12-19 22:25:35.507  2483  2483 E Thermal-daemon: [charger_ic] temp_new :28  temp_old :27
12-19 22:25:35.507  2483  2483 E Thermal-daemon: Report temperature: [charger_ic] temp :28  report_threshold:1
12-19 22:25:44.413  3052  3314 E InputReader: QEEXO fs_classify_touch NULL, not calling FingerSense
12-19 22:25:44.453  3052  3314 E InputReader: QEEXO fs_touch_up NULL, not calling FingerSense
12-19 22:25:44.477 14966 14998 I python  : [INFO   ] [Base        ] Leaving application in progress...
12-19 22:25:44.478 14966 14998 I python  :  Traceback (most recent call last):
12-19 22:25:44.479 14966 14998 I python  :    File "/content/.buildozer/android/app/main.py", line 82, in <module>
12-19 22:25:44.480 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/app.py", line 950, in run
12-19 22:25:44.482 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/base.py", line 582, in runTouchApp
12-19 22:25:44.484 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/base.py", line 347, in mainloop
12-19 22:25:44.485 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/base.py", line 391, in idle
12-19 22:25:44.486 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/base.py", line 342, in dispatch_input
12-19 22:25:44.487 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/base.py", line 308, in post_dispatch_input
12-19 22:25:44.488 14966 14998 I python  :    File "kivy/_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
12-19 22:25:44.490 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivymd/uix/button/button.py", line 814, in on_touch_up
12-19 22:25:44.491 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivymd/uix/behaviors/ripple_behavior.py", line 311, in on_touch_up
12-19 22:25:44.492 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/uix/behaviors/button.py", line 179, in on_touch_up
12-19 22:25:44.493 14966 14998 I python  :    File "kivy/_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
12-19 22:25:44.494 14966 14998 I python  :    File "kivy/_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
12-19 22:25:44.496 14966 14998 I python  :    File "kivy/_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
12-19 22:25:44.497 14966 14998 I python  :    File "/content/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/debug/kivy/lang/builder.py", line 57, in custom_callback
12-19 22:25:44.498 14966 14998 I python  :    File "<string>", line 11, in <module>
12-19 22:25:44.499 14966 14998 I python  :  NameError: name 'AndroidBluetooth' is not defined
12-19 22:25:44.499 14966 14998 I python  : Python for android ended.

And the NameError: name 'AndroidBluetooth' is not defined at the very end of the log. I don't know what to do with this error message (In my Opinion the Class and the call of the Class is correct).

Do you have any ideas on how to solve this misbehaviour? Thanks in advance for your answers.

1 Answers1

0

I have solved the Question with the help of the Kivy Discord Server. The basic idea was correct but the definition of the AndroidBluetoothClass has to take place in the build Method of the App Class.

Therefore the attribute has to be called like this: app.android_bluetooth.getAndroidBluetoothSocket('HC-05')

Working code:

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.toast import toast
from jnius import autoclass

layout = '''
BoxLayout:
    id: boxlayout
    orientation:'vertical'
    adaptive_size: True

    MDIconButton:
        icon: "bluetooth"
        pos_hint: {'center_x':0.5,'center_y':0.875}
        user_font_size: "40sp"
        on_release: app.android_bluetooth.getAndroidBluetoothSocket('HC-05')
'''

class AndroidBluetoothClass:

    def getAndroidBluetoothSocket(self,DeviceName):
        toast("AndroidBluetoothSocket")
        print("AndroidBluetoothSocket")
        paired_devices = self.BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray()
        socket = None
        for device in paired_devices:
            if device.getName() == DeviceName:
                socket = device.createRfcommSocketToServiceRecord(
                    self.UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
                self.ReceiveData = self.BufferReader(self.InputStream(socket.getInputStream()))
                self.SendData = socket.getOutputStream()
                socket.connect()
                self.ConnectionEstablished = True
                print('Bluetooth Connection successful')
                toast("Bluetooth Connection successful"

        return self.ConnectionEstablished


    def BluetoothSend(self, Message, *args):
        toast("Bluetooth send")
        print("Bluetooth send")
        if self.ConnectionEstablished == True:
            self.SendData.write(Message)
        else:
            print('Bluetooth device not connected')


    def BluetoothReceive(self,*args):
        toast("Bluetooth receive")
        print("Bluetooth receive")
        DataStream = ''
        if self.ConnectionEstablished == True:
            DataStream = str(self.ReceiveData.readline())
        return DataStream

    def __init__(self):
        toast("Bluetooth init")
        print("Bluetooth init")
        self.BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
        self.BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
        self.BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket')
        self.UUID = autoclass('java.util.UUID')
        self.BufferReader = autoclass('java.io.BufferedReader')
        self.InputStream = autoclass('java.io.InputStreamReader')
        self.ConnectionEstablished = False
        toast("Bluetooth init finish")
        print("Bluetooth init finish")


    def __del__(self):
        toast("Bluetooth del")
        print('class AndroidBluetooth destroyer')

class TestApp(MDApp):

    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Green"
        self.android_bluetooth = AndroidBluetoothClass()
        return Builder.load_string(layout)

TestApp().run()

I hope that this solution works for everyone with this issue.