Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the OS / Peripherals with Kivy?

I'm writing a program with Kivy.

Under "desktop" OSes it would be normal to use the keyboard for input, and my code does so.

class ProgLayout( FloatLayout ):
    def __init__(self, **kwargs):
        super( ProgLayout, self ).__init__(**kwargs)
        # Keyboard Handling (if any)
        self.keyboard = Window.request_keyboard(self.keyboard_closed, self)
        self.keyboard.bind(on_key_down=self.on_keyboard_down)
        self.keyboard.bind(on_key_up=self.on_keyboard_up)
        self.key_states = { 'up':False, 'down':False, 'left':False, 'right':False }

    def on_keyboard_down( self, keyboard, keycode, text, modifiers ):
        #print("ON_KEYBOARD_DOWN")
        #print('The key', keycode, 'have been pressed')
        #print(' - text is %r' % text)
        #print(' - modifiers are %r' % modifiers)

        junk, key = keycode
        keymap = { 'up':Directions.NORTH, 'down':Directions.SOUTH, 'left':Directions.WEST, 'right':Directions.EAST }
        if ( key in ( 'up', 'down', 'left', 'right' ) ):
            self.key_states[ key ] = True
            self.handleKeys()

    def on_keyboard_up( self, keyboard, keycode ):
        #print("ON_KEYBOARD_UP")
        junk, key = keycode
        if ( key in ( 'up', 'down', 'left', 'right' ) ):
            self.key_states[ key ] = False
            self.handleKeys()

However, when the app starts under Android (I suspect) opening the keyboard induces the onscreen-keyboard to appear. Obviously the soft-keyboard can be dismissed, but a better solution is to only open the keyboard if a hardware keyboard is present - or just not automatically use it for Android.

Is there a way to determine if a physical keyboard is present on Kivy?

Is there a way to determine if my app is running on Android (ah, I guess platform.system() or sys.platform).

EDIT: buildozer fails to build the .APK if I include sys or platform in the buildozer.spec manifest. Importing sys still seems to work despite this. But on my android tablet, sys.platform reports "linux", so that's not a way forward.

like image 846
Kingsley Avatar asked Oct 23 '25 14:10

Kingsley


1 Answers

As the commenter @Erik points out, the solution to determining the current platform is kivy.utils.platform.

from kivy.utils import platform

...

if ( kivy.utils.platform != 'android' ):
    # open the keyboard, since we're not android

As the documentation states:

A string identifying the current operating system. It is one of: ‘win’, ‘linux’, ‘android’, ‘macosx’, ‘ios’ or ‘unknown’.

like image 132
Kingsley Avatar answered Oct 25 '25 13:10

Kingsley