Some Pyjnius tools for Kivy-Android developments.

kvdroid, updated πŸ•₯ 2023-03-21 13:32:14


A re-implementation of android java API in python with easy access to some Android functionality like Notification, Reading of Contacts, accessing Webview Cookies, etc...

The aim is to provide full access to Android API which can be used together with Python frameworks like: kivy, kivymd, etc... Or as a standalone, in which Android native UI is created with only python codes.

Compiling into APK

To compile, kivy p4a or kivy buildozer is required, and bootstrap must be set to sdl2


sh Android min-api21


``` pip install kvdroid


pip install # master version

Note: this works on android only, but you can install it on your desktop for code completion assistance


Buildozer Requirement

``` requirement = kvdroid


requirement = ```


To send notification

```python from import Color from import create_notification from import get_resource

create_notification( small_icon=get_resource("drawable").ico_nocenstore, # app icon channel_id="1", title="You have a message", text="hi, just wanted to check on you", ids=1, channel_name=f"ch1", large_icon="assets/image.png", expandable=True, small_icon_color=Color().rgb(0x00, 0xC8, 0x53), # 0x00 0xC8 0x53 is same as 00C853 big_picture="assets/image.png" ) ``` To read Contacts

```python from import get_contact_details

get_contact_details("phone_book") # gets a dictionary of all contact both contact name and phone mumbers get_contact_details("names") # gets a list of all contact names get_contact_details("mobile_no") # gets a list of all contact phone numbers ```

To get a list of all installed packages (Applications)

```python from import all_packages


""" ['', '', '', '', ''...] """ ```

To get all main activities

```python from import all_main_activities


""" [{'': ''}, {'': ''}, {'': ''}, {'': ''}...] """ ```

To check if the package is a system application

```python from import is_system_package

print(is_system_package("")) ```

To check if the package is enabled

```python from import is_package_enabled

print(is_package_enabled("")) ```

To get a specific app details

```python from import package_info


""" {'activities': ['org.chromium.settings.SettingsBlackHoleActivity', '$NetworkDashboardActivity', '', '$AdvancedAppsActivity', ''...], 'dataDir': '/data/user_de/0/', 'loadIcon': >, 'loadLabel': 'Settings', 'packageName': '', 'permissions': ['org.chromium.settings.ENABLE_INPUT_METHOD', 'android.permission.REQUEST_NETWORK_SCORES', 'android.permission.WRITE_MEDIA_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE'...], 'processName': '', 'publicSourceDir': '/system/priv-app/ArcSettings/ArcSettings.apk', 'sharedLibraryFiles': None, 'sourceDir': '/system/priv-app/ArcSettings/ArcSettings.apk'} """ ```

To get an activity info

```python from import activity_info


""" {'loadIcon': >, 'loadLabel': 'Network and Internet'} """ ```

To save a drawable object to given path as png

```python from import package_info from import save_drawable

app = package_info("") app_icon = app["loadIcon"]


save_drawable(app_icon, "< path >", "< file_name >")

That will save the app icon to given path and return the path + filename

can be used like

from kivy.uix.image import Image

Image(source=save_drawable(app_icon, "< path >", "< file_name >")) ```

To check if the given app is installed from PlayStore

```python from import package_source

print(package_source("< package_name >")) ```

To get Android WebView Cookies

```python from import get_cookies

get_cookies("https://google.login") ``` To detect keyboard height

```python from import keyboard_height

print(keyboard_height()) ``` To detect if app is installed from Play Store or not

```python from import app_source

print(app_source()) ```

To get application infos name pkg_name version_name version_code

```python from import app_info

print(app_info("name")) ```

To get application directories data app files cache ext_files ext_cache

```python from import app_dirs

print(app_dirs("files")) #/data/data/package/files print(app_dirs("ext_files"), slash = True) #/storage/sdcard0/Android/data/package/files/ ```

To get absolute screen size in dp-pixel and detect current orientation

```python from import Metrics screen = Metrics()

print(screen.orientation()) print(screen.width_dp()) print(screen.height_px()) print(screen.resolution()) ``` To check if device has a data connection.

```python from import network_status, wifi_status, mobile_status

print(network_status()) # for both wifi and mobile print(wifi_status()) # only for wifi print(mobile_status()) # only for mobile print(get_wifi_signal()) # only for wifi ``` To get Wi-Fi signal strenght.

```python from import get_wifi_signal

print(get_wifi_signal()) ```

To get network latency.

```python from import network_latency

print(network_latency()) ```

To check if device is in dark mode or not

```python from import dark_mode

print(dark_mode()) To get device informations. Available options are;'model','brand','manufacturer','version','sdk','product','base','rom','security','hardware','tags','sdk_int','total_mem','used_mem','avail_ram','total_ram','used_ram','bat_level','bat_capacity','bat_temperature','bat_voltage','bat_technology', 'bat_status', 'bat_health'```

```python from import device_info

print(device_info("model")) print(device_info("avail_ram", convert=True)) ``` To enable immersive mode

```python from import immersive_mode

immersive_mode() ``` To launch an application

```python from import launch_app

launch_app("< app_package >") ``` To launch a specific application activity

```python from import launch_app_activity

launch_app_activity("< app_package >", "< app_activity >") ``` To open target app's details page

```python from import app_details

app_details("< app_package >") ``` To detect current device's language

```python from import device_lang

print(device_lang()) # en print(device_lang("DisplayLanguage")) # English print(device_lang(option = "DisplayLanguage", display_lang = "fr")) # Anglais

""" Available options are ;

Language ---> en
ISO3Language ---> eng Country ---> US ISO3Country ---> USA DisplayCountry ---> United States DisplayName ---> English (United States) String ---> en_US DisplayLanguage ---> English LanguageTag ---> en-US """ ```

To get a list of supported languages on the device

```python from import supported_languages print(supported_languages())

""" ['af', 'agq', 'ak', 'am', 'ar', 'as', 'asa', 'ast'...] """ ```

To set statusbar color

```python from import change_statusbar_color

change_statusbar_color("#FFFFFF", "black") ``` To set navigationbar color

```python from import navbar_color

navbar_color("#FFFFFF") ``` To display a toast message

```python from import toast

toast("hello world") `` To get absolute sdcard path and media directoriesalarmdcimdownloaddocumentsmoviesmusicnotificationspicturespodcastsringtones`

```python from import sdcard

print(sdcard()) #/storage/sdcard0 print(sdcard("download")) #/storage/sdcard0/Download print(sdcard("download", slash = True)) #/storage/sdcard0/Download/

``` To get absolute external_sdcard

```python from import external_sdcard

print(external_sdcard()) ``` To get file mime Type

```python from import mime_type

mime_type = mime_type("path/to/file") print(mime_type) ```

To change default wallpaper

```python from import set_wallpaper

set_wallpaper("/sdcard/test.jpg") ``` To use text-to-speech

```python from import speech

speech("hello world", "en") ``` To use default Download Manager

```python from import download_manager

download_manager("< title >", "< description >", "< URL >", "< path >", "< file >") ``` To restart the app

```python from import restart_app

restart_app() ``` To share text via Android Share menu

```python from import share_text

share_text("hello world", title="Share", chooser=False, app_package=None, call_playstore=False, error_msg="application unavailable") ``` To share any file via Android Share menu

```python from import share_file

share_file( "< path - to - file >", "< title >", "< chooser >", "< app - package: open -with-default - app >", "< call_playstore >", "< error_msg >") share_file("/sdcard/test.pdf", title='Share', chooser=False, app_package=None, call_playstore=False, error_msg="application unavailable") To play supported music format or radio stream through Android Media Playerplayer.mPLayer = Android Media PLayer```

```python from import Player

player = Player()"< path - to - music - file >")"") # radio player.pause() player.resume() # seconds player.do_loop(True) # default is False player.is_playing() player.get_duration() player.current_position() ```

To use system-provided fonts

:warning: That function is so experimental. It should work for Android 7 and above but not been tested on much devices. It is actually for multilingual purposes to use system-provided fonts for no Latin languages. system_font() will always return the supported font from /system/fonts for the current device language. Also, you could use any language-supported font from the system just by calling the system_font function with the target language's iso639-1 or iso639-2 abbreviation such as font_name = system_font('zh') or system_font('zho').

```python from kivy.uix.label import Label from import system_font

that will return the default font for the device's current language.

Label(text = "example", font_name = system_font())

for the specific language font

Label(text = "δ½ ε₯½δΈ–η•Œ", font_name = system_font('zho')) # Language definition must be iso639-1 or iso639-2 abbreviation. ```

To cast Java Object

```python from kvdroid.cast import cast_object from import Uri

uri = Uri().fromFile("/home/java/my_document.pdf") parcelable = cast_object("parcelable", uri)

Above code is same as below code::

from import Uri from jnius import cast

uri = Uri().fromFile("/home/java/my_document.pdf") parcelable = cast("android.os.Parcelabel", uri)

''' the difference is, you dont have to remember the package name, just only the name and you are good to go. This will also be helpful for python devs who do have zero knowledge on java

Note:: not all castable java object are included you can open an issue to include all missing castables ''' ```

To access WebView cookies\ (i.e if you compiled your app with webview bootstrap or have Webview in your app)

```python from import get_cookies

print(get_cookies("")) ``` To access android package resource folders like: - drawble - layout - menu - values - mipmap - etc....

```python from import get_resource

drawable = get_resource("drawable") To get Wi-Fi IP Addresspython from import get_wifi_ip_address print(get_wifi_ip_address()) To send emailpython from import send_email send_email( recipient=["[email protected]"], subject="Hello there", body="This is kvdroid" ) To send an email with an attachment (androidx is required). \ Also note before you can share files on Android version greater \ than 10, you must specify a provider in the AndroidManifest.xml \ inside the \<application> tag e.gxml and also specify file path in the res/xml/filepath.xml of the android project folder e.gxml refer to [android developer FileProvder Documentation]( to know morepython from import send_email from os import getenv from os.path import join send_email( recipient=["[email protected]"], subject="Hello there", body="This is kvdroid", file_path=join(getenv("PYTHONHOME"), "test.txt") ) ``` To read all SMS

```python from import get_all_sms from android.permissions import Permission, request_permissions # NOQA

remember to add READ_SMS to your buildozer android.permissions

request_permissions([Permission.READ_SMS]) print(get_all_sms()) # returns a tuple of message count and messages ``` To read all Call Log

```python from import get_call_log from android.permissions import Permission, request_permissions # NOQA

remember to add READ_CALL_LOG to your buildozer android.permissions

request_permissions([Permission.READ_CALL_LOG]) print(get_call_log()) # returns a tuple of call log count and call_log ```

Since the release of Android 11 (API 30), the way file are stored became different




Read TEXT_AUTO_CAPS setting

opened on 2023-02-07 20:15:33 by antorix

Maybe Kvdroid can implement the possibility to read one more Android setting from Kivy: TEXT_AUTO_CAPS ( I need to get this setting in my app to control the text input, but have not yet found any way to do so.

Notification arguments

opened on 2023-01-23 21:28:47 by KocWozniakPiotr

Hello. I tried using the example of the create_notification()and changed big_picture and large_icon to my png icons but your example still doesn't work on android and actually crashed app when starting, also when its added to the the background service. Do I need some special formatting when adding path to the file?

There is no explanation how it really works and it would be really great to add some commenting or documentation for this feature.
Are the arguments in your example mandatory and if so are those put in your example enough to test the notification feature? If not please give a proper explanation.

Until now I used plyer module for notifying but it's not perfect and has bugs when trying to use different icons.

Thank you for your hard work on the project! Best Regards!

How to add buffer on ?

opened on 2022-12-11 00:15:21 by isaffathir

Im trying to make online music that stream music format .mp3 from url. but doesnt play music if the music not fully downloaded its mean on low speed connection the music would not played

how to add buffer so user can stream music even on low speed connection?

TTS on androd 11 not workng

opened on 2022-10-27 07:22:53 by purushottam858

just tried below code from kvdroid docs , it is not working , there is no error , but no sound too . maybe because of android version 11 .

from import speech speech("hello world", "en")

how to solve this issue ..?


i came across below comments on android 11 ,
where can i find that " manifest file " and where actually should i add those lines of codes

" You may also need to add this code to your manifest file for the TTS to work if you are targeting Android 11:


how can we get user's personal phone number ??

opened on 2022-08-14 13:24:54 by USER4247

I want to get user's personal phone number as my kivy app requirs it to function . My approach was to use otp system , byt sms cost is way too high

Listener for network

opened on 2021-06-22 07:28:26 by Kulothungan16

It will useful if we can add a listener for network if the state changes it will trigger the func that we passed in


Android for Python

GitHub Repository