Android apps in kivy

Приложение на python kivy для разнообразия рациона питания. От кода и до получения .apk файла для Android


Изучаю python kivy и для себя решил написал маленькое приложение, чтобы разнообразить свое питание. Решил поделиться. Статья рассчитана на новичков в kivy. Приложение занимает около 100 строк кода.

Цель создания велосипеда приложения:

  1. Избежать частых повторений в питании. Чтобы не употреблять одно и то же блюдо слишком часто.
  2. Не забывать блюда, которые ел, потом забыл и годами к ним не возвращался, потому что банально не помнил. У меня такое бывает.

Интро

Можно не читать, в интро всякая лирика.

Пришлось пожить в одной стране, в одной гостинице, где кормили ежедневно яйцами на завтрак и больше ничем, так через месяц начал чесаться. Обращался за медицинской помощью, хотя раньше никогда ничем подобным не страдал. Наученный горьким опытом после этого для себя решил допускать как можно меньше повторений в еде, чтобы ничего не успевало в организме накопиться. Это мой личный опыт, я просто рассказываю, без навязывания. Возможно, нет правил без исключения, наверное, овсянку можно есть и каждый день на протяжении десятков лет.

Скриншоты

Предположим мой рацион состоит из 50 блюд. Например, сегодня ел омлет. Нажимаю на кнопку, и омлет стал на 50 строку в очереди, а перед ним стоят 49 блюд, которые съем, чтобы опять добраться до омлета. Вот и вся логика приложения. (На скриншотах блюда нагенеренные, все совпадения случайны, к моему реальному рациону отношения не имеющие).

Исходный код и пояснения

Я сознательно не использовал kv файлы, так как код дан в учебных целях, для людей, которые знакомы с python. Все написано на голом python. В пояснениях я не буду останавливаться на объяснении python кода, а сразу перейду к специфическим фишкам Kivy.

  • Класс отвечает за запуск стартовой странички приложения, его можно назвать как угодно, например StartScreen. И наследует kivy модуль Screen. Приложение состоит из 3-х окон, вот эти окошки и создаются с помощью этого модуля
  • BoxLayout делит экран на равные части, по умолчанию горизонтально, я написал orientation=’vertical’, чтобы делить вертикально
  • Button — создает кнопки, в on_press задается, какая функция будет запущена при нажатии.
  • — добавляет кнопки в слои и в окна
  • Grid Layout чем-то напоминает тег table в html, указывается cols — кол-во колонок или rows — кол-во строк.

Можно указывать оба параметра или один параметр.
Экран будет разделен на нужное кол-во отсеков.

  • RecycleView — модуль, с помощью которого создается вертикальная прокрутка в моем приложении. Особенность RecycleView в том, что он строит скролы с элементами одинаковой ширины и высоты. И работает быстро. А есть модуль ScrollView, он может строить прокрутки с элементами разных размеров, но работает медленнее, чем RecycleView
  • — в коде часто встречаются такие строки. Я просто в качестве хранилища данных использовал родное хранилище Config kivy. Ну, пусть будет несколько тысяч блюд, нет смысла городить огород с sqlite и чем-то подобным. Все данные хранятся в одном файлике. Хранится этот файлик в той же папке, что и само приложение, если указать self.directory как в моем коде, но можно указать self.user_data_dir, чтобы этот файлик не уничтожался при перестановке или обновлениях.
  • Запуск на windows & linux & macos

    Принцип для всех операционок одинаковый:

    1. Ставим python3
    2. Ставим kivy
    3. Создаем файл main.py и втыкаем в него целиком вышеуказанный код
    4. Запускаем командой

    Программа должна заработать.

    Сборка apk файла и запуск на телефоне с андроид

    Итак, у нас есть файл с кодом программы, написанный на python. Как теперь создать приложение, чтобы его можно было запустить на телефоне с андроидом? Раньше это был достаточно мудреный процесс, требующий навыков и танцев с бубном. Теперь это не проблема.
    Вот пошаговая инструкция:

    1. Скачиваем готовую виртуальную машину от разработчиков kivy, в которой уже все настроено. https://github.com/Zen-CODE/kivybits/tree/master/KivyCompleteVM. Пароль: kivy
    2. Запускаем ее в Virtual Box.
    3. Открываем терминал и вводим следующие команды:
  • Последняя команда создает папку bin в той же директории, в bin вы найдете файл foodoptions-0.1-debug.apk, который можно закинуть на телефон, установить и наслаждаться приложением
  • Как закинуть apk файл на телефон?

    Можно, конечно, сделать это как угодно, отправить себе по почте, куда-нибудь выложить, закинуть в телеграмм и т.д., а потом скачать приложение на телефон.

    Но существует специализированный инструмент для этого. Включаем на телефоне режим разработчика, подключаем USB-кабелем. Виртуалка должна увидеть, что вы подключили телефон. Дальше устанавливаем adb:

    После установки заходим в папку bin и вводим команду

    И можно примерно через минутку увидеть на телефоне приложение после того, как увидим
    Success в консоли.

    Если вдруг приложение падает или ведет себя не так, как ожидалось, то есть вот такая команда для просмотра ошибок

    Русское имя приложения

    Если вы захотите, чтобы ваше приложение называлось по-русски, например, «Дневник питания», то надо внести изменения в файл:

    В тег appName прописывается русское название приложения, эта папка создается после первого запуска buildozer android debug. После того как файл отредактируете, вернитесь назад в папку FoodOptions и запустите buildozer android debug повторно. Файл соберется по-новой. После установки на телефон имя программы будет написано на русском.

    О файле buildozer.spec

    Вот мой файл с гитхаба: buildozer.spec
    Именно этот файл указывает buildozer-у, как именно собрать пакет.

    Там множество разных вариаций. Кому интересно, то введите внутри виртуалки команду:

    Будет создан дефолтный файл buildozer.spec с кучей комментариев и пояснений. Например, если вы хотите какую-нибудь свою иконку для приложения, то указываете в строке:

    свой файл с иконкой. И приложение соберется уже с вашей иконкой.

    Если вам надо подгрузить какой-нибудь специфический модуль, который не входит в официальную библиотеку python, то это делается в строке requirements =. В общем, рассказ о файле buildozer.spec может занять целую статью, а то и две.

    Загрузка приложения в Google Play

    Надо зарегаться, пройти все процедуры, получить ключи. И дальше запускать:

    Полученный файл apk-apkname-release.apk заливать в Google Play.

    Ссылки

    • Видео-уроки по kivy на русском языке. Лично мне понравились
    • Статьи на хабре про kivy от HeaTTheatR (и спасибо ему за помощь!)

    В принципе любой человек, который умеет программировать на python, сможет изменить приложение и легко добавить следующее:

    1. Добавить дизайн, чтобы приложение стало красивое
    2. Использовать kv-файлы, чтобы код стал более легким. Я бы привел такую аналогию: те кто знаком с веб-программированием, представьте себе код без html темплейтов и с html темплейтами. Вынос в kv-файлы кнопок, слоев и прочего — это что-то вроде jinja2 для веб-программиста. Логика остается в .py файлах, а фенечки — в kv-файлах.
    3. Добавить подсчет калорий, белка, углеводов, жиров (БЖУ)
    4. Добавить возможность фотографировать блюда

    Источник

    Building a background application on android with Kivy.

    Kivy runs on android using the python-for-android project, which support android services. This works in a simple way, you basically bundle two main.py in your application, one for the UI, one for the service. The UI can start the services on start. From that point though, things may be a little uneasy. Why? Because you have two applications, and now you have to make them talk to each over if you want to do anything useful.

    Android’s way of having an Activity and a Service talk to each other is Broadcast signals, which can be limited to part of your applications, howether, it’s not straightforward to use them with pyjnius, which is the magical interface we use to use java code from python.

    Another way is to use network, i’ve been doing it with twisted in the past, setting a twisted server in the Service, and using twisted as a client in the Activity, howether, i find this to be heavy lifting for the trivial task of communicating between two programs on the same device. And including Twisted in your app, certainly add some weight to it.

    Howether, in order to support TUIO, kivy ships with a simple OSC implementation, OSC is a simple connectionless network protocol, that allow you to pack messages, and send them to an ip/port/api URI, turns out we don’t need anything more, and a connectionless protocol avoid us dealing with disconnections (like the UI being closed, or the service not being started yet) that could give us some headaches (and certainly gave me some). We just need to have both part of the program listen for OSC messages, and have them send data to each other, if confirmation is needed, it’s possible to have a messages been sent back on a specific api.

    So let’s get started.

    getting a minimal kivy app

    The usual things, let’s put a simple UI with a Button.

    here we just load a kv string that defines a button, and return the result, nothing fancy.

    getting a minimal service

    Yeah, nothing much needed, actually, the sleep isn’t even needed, but the program have to run, and we’ll need this loop anyway.

    starting the service

    For your service to run, you need to tell your UI to start it.

    We make the test for android, so you can still test your app on desktop, by starting manually both parts.

    Packaging them for android

    both files must be named main.py , the UI one is at the root of the project, the other one is in a service directory directly under the root of the project.

    To package, i’ll be using buildozer.

    As we are using network don’t forget to add the NETWORK permission when editing buildozer.spec

    After some time, you should see the (not very exciting) app start on your plugged android device.

    setting up OSC

    Whatever the side, OSC needs a port to listen on, and to have functions to call when things happen. The basic setup is simple.

    needs to be called regularly.

    for the service, we’ll just put this call in the loop:

    And for UI, we’ll use kivy.clock.Clock’s schedule_interval method.

    Now, both sides can receive messages, that’s a good first step, but nothing will really happen, since none of them send any message.

    sending messagse

    The osc api to send message is very simple:

    now, ipAddr is by default localhost, which is fine for us, so we only need to find the api we want to hit, the data list, and the port, which will be the one the other side listens on.

    Let’s make our button send a message to the Service.

    Yes, at that point, you can run it, and see that when you press the button, your adb logcat on android, yay!

    Now, let’s make our service answer, and our UI display the answer!

    and for the UI to answer:

    The only thing a bit confusing here is that the real message is in message[2], don’t ask me why, it’s probably explained in some documenation i didn’t care enough to search for :).

    conclusion

    That’s not much code! And it should be quite easy to extend to allow for more complex patterns, detecting if your service is running or not can be done by making it send pings at regular intervals, you can also make your service fetch/work on data from somewhere else in the background, and pass it to the UI when it’s ready.

    A slightly more complex demo based on this can be found here.

    Источник

    Create a package for Android¶

    You can create a package for android using the python-for-android project. This page explains how to download and use it directly on your own machine (see Packaging with python-for-android ) or use the Buildozer tool to automate the entire process. You can also see Packaging your application for the Kivy Launcher to run kivy programs without compiling them.

    For new users, we recommend using Buildozer as the easiest way to make a full APK. You can also run your Kivy app without a compilation step with the Kivy Launcher app.

    Kivy applications can be released on an Android market such as the Play store, with a few extra steps to create a fully signed APK.

    The Kivy project includes tools for accessing Android APIs to accomplish vibration, sensor access, texting etc. These, along with information on debugging on the device, are documented at the main Android page .

    Buildozer¶

    Buildozer is a tool that automates the entire build process. It downloads and sets up all the prequisites for python-for-android, including the android SDK and NDK, then builds an apk that can be automatically pushed to the device.

    Buildozer currently works only in Linux, and is a beta release, but it already works well and can significantly simplify the apk build.

    This will install buildozer in your system. Afterwards, navigate to your project directory and run:

    This creates a buildozer.spec file controlling your build configuration. You should edit it appropriately with your app name etc. You can set variables to control most or all of the parameters passed to python-for-android.

    Finally, plug in your android device and run:

    to build, push and automatically run the apk on your device.

    Buildozer has many available options and tools to help you, the steps above are just the simplest way to build and run your APK. The full documentation is available here. You can also check the Buildozer README at https://github.com/kivy/buildozer.

    Packaging with python-for-android¶

    You can also package directly with python-for-android, which can give you more control but requires you to manually download parts of the Android toolchain.

    Packaging your application for the Kivy Launcher¶

    The Kivy launcher is an Android application that runs any Kivy examples stored on your SD Card. To install the Kivy launcher, you must:

    Go to the Kivy Launcher page on the Google Play Store

    Click on Install

    Select your phone… And you’re done!

    If you don’t have access to the Google Play Store on your phone/tablet, you can download and install the APK manually from http://kivy.org/#download.

    Once the Kivy launcher is installed, you can put your Kivy applications in the Kivy directory in your external storage directory (often available at /sdcard even in devices where this memory is internal), e.g.

    should be a directory containing:

    The file android.txt must contain:

    These options are just a very basic configuration. If you create your own APK using the tools above, you can choose many other settings.

    Installation of Examples¶

    Kivy comes with many examples, and these can be a great place to start trying the Kivy launcher. You can run them as below:

    Run the launcher and select one of the Pictures, Showcase, Touchtracer, Cymunk or other demos…

    Release on the market¶

    If you have built your own APK with Buildozer or with python-for-android, you can create a release version that may be released on the Play store or other Android markets.

    To do this, you must run Buildozer with the release parameter (e.g. buildozer android release ), or if using python-for-android use the —release option to build.py. This creates a release APK in the bin directory, which you must properly sign and zipalign. The procedure for doing this is described in the Android documentation at https://developer.android.com/studio/publish/app-signing.html#signing-manually — all the necessary tools come with the Android SDK.

    Targeting Android¶

    Kivy is designed to operate identically across platforms and as a result, makes some clear design decisions. It includes its own set of widgets and by default, builds an APK with all the required core dependencies and libraries.

    It is possible to target specific Android features, both directly and in a (somewhat) cross-platform way. See the Using Android APIs section of the Kivy on Android documentation for more details.

    Источник

    Читайте также:  Panzer corps для андроид
    Оцените статью