Android studio python community edition

Полноценное Python приложение на Android

В этой статье я хотел бы рассказать о том, как создать полноценное приложение на Python для Android. Нет, это не очередной мануал для создания скрипта для sl4a, это мануал по созданию полноценного приложения с UI, возможностью собрать apk и выложить на Android Market. Заодно я хотел бы похвалиться своим первым приложением на google.play, это не hello world, а полезное приложение для фотографов, хотя и узко специализированное.

Начну рассказ пожалуй с самого приложения и завершу рассказам о том как оно делалось.

isortViewer

Мне как фотографу приходится тратить много времени на сортировку и отбор фотографий. Не всегда хочется сидеть за рабочим компьютером, когда под рукой есть ноутбук, смартфон или планшет, но копировать туда десятки гигабайт raw или jpeg файлов, а потом синхронизировать с рабочим компьютером — сомнительное удовольствие. Именно поэтому я создал программы isortManager и isortViewer, которые значительно облегчили мне работу по сортировке и отбору фотографий. Теперь заниматься отбором и сортировкой фотографий я могу лежа на пляже диване или скучая в пробке 🙂

Копипаст описания и пара скриншотов:
isortViewer — программа для фотографов, которая позволяет легко и быстрой отбирать и сортировать тысячи фотографий (raw или jpg) с фотосессий на ваших android смартфонах и планшетах. При этом, нет необходимости копировать десятки гигабайт jpg или raw файлов на устройство. Просто воспользуйтесь бесплатной программой isortManager для компьютера, которая сохранит все в один небольшой файл проекта:
1. Скачайте и запустите isortManager с официального сайта;
2. Создайте проект и добавьте папки с фотографиями. Поддерживаются форматы: jpg и raw (cr2, nef, orf и т.д.). В итоге у вас получится небольшой файл проекта (примерно 150 мб на несколько тысяч фотографий, будь то jpg или raw формат);
3. Скопируйте на ваше android устройство файл проекта, откройте в isortViewer. Вы можете помечать фотографии «на удаление», а так же, ставить рейтинги от 1 до 5 звезд;
4. После этого, скопируйте файл проекта обратно и примените изменения в isortManager. Кроме удаления выбранных фотографий, вы можете копировать или перемещать отмеченные фотографии. Например, фотографии с «5 звезд» можно скопировать в папку «шедевры», а «1 звезда» переместить в папку «хлам».

Приложение абсолютно бесплатно и доступно на google.play, однако донейты приветствуются.

Исходники доступны на официальном сайте!

Как это делалось

Так как python лучший язык программирования в мире кроме python я ничего не знаю, решено было написать приложение на python.

isortManager

С isortManager для PC проблем не возникло, создание GUI сборки под windows уже давно обкатано и работает он очень просто: с помощью dcraw выдирает jpg превьюшки из raw файлов, ресайзит из с помощью PIL и складывает в один файл с достаточно простой структурой. Был изобретен свой весолипед с контейнером для хранения фотографий и метаданных (полный путь к фотографии, отметка «на удаление» и отметка рейтинга), так как, например, zip или tar формат, не могут изменять один файл в архиве (метаданные), требую перепаковки всех файлов. Файлы просто пишутся один за другим подряд и в блоке метаданных (обычный repr питоновского словаря) в конце сохраняется смещения начала файлов, плюс в конце файла пишется размер блока метаданных. GUI написано на Tkinter (люблю я его за быстроту написания и за малый размер итоговой сборки), вот собственно скриншот:

И да, все это работает и на linux, и даже быстрее чем на windows )

isortViewer для android

Всего я нашел два способа заставить python приложение работать как полноценное приложение на android, это pygame for android и проект kivy.
Pygame — более низкоуровневый, все UI пришлось бы рисовать вручную, что отняло бы много времени, поэтому был выбран фреймворк kivy. Итак:

Это замечательный фрейморк для написания приложение для windows, linux, MacOS, android и iOS. Поддерживается мультитач, UI рисутется через OpenGL, значит должно работать аппаратное ускорение. Увидеть работу виджетов можно установив демонстрационное приложение Kivy Showcase. Есть возможность использования некоторых платформо специфичных функций, например, вибро или акселерометр, с помощью модуля android.

Читайте также:  Android device factory reset

Для разработки я бы рекомендовал использовать linux, тем более, apk собираются именно в этой OS.

Hello World выглядит так:

Причем этот код будет работать на всех заявленных платформах. Пропадает необходимость в тестировании приложения в эмуляторе. Достаточно запустить скрипт на исполнение в своей любимой IDE и увидеть результат на экране компьютера, без задержек на компиляцию, запуск эмулятора и пр. Если вы все же хотите увидеть как это будет выглядеть непосредственно на устройстве, просто установите Kivy Launcher, скопируйте файлы проекта на карту памяти и запустите. Дебажить при этом можно при помощи adb logcat.
Если вы используете библиотеку android, которой нет на PC, но хочется запускать приложение не только на android, воспользуйте такой конструкцией:

Сборка apk достаточно проста и описана на этой странице. После сборки релиза, достаточно подписать свое приложение (я использовал этот мануал) и выложить в google play.

Плюсы kivy:

  • Быстрая разработка под различные платформы, практически без доработки кода.
  • Доступен широкий выбор виджетов
  • Высокая скорость работы. Весь ресурсоемкий вынесен в С модули. Сам интерпретатор python на android работает нативно.
  • Фремворк включает в себя множество инструментов, например анимация, кеширование и пр.
  • upd: Доступ к камере, буферу обмена, микрофону. Написать свой видеоплеер можно буквально за 20 строк.

Минусы kivy:

  • Большой размер apk файла. Проект с 300 кб ресурсов (скрипты, графика) собирается в 7 мб apk. Хотя, думаю, есть возможность это как то оптимизировать.
  • Невозможность (пока), восстанавливать работу после сворачивания — приложение закрывается

В следующей своей статье, я расскажу более подробно о процессе написания приложения «с нуля», расжевывая каждую строчку кода.

Хотелось бы сразу пресечь холивары на тему «для android только java, python не нужен». Я считаю, не важно, какие технологии «под капотом», главное чтоб приложение было качественным.
Сфера применения kivy может быть огромной. Сейчас на моем счету несколько приложений, написанных под заказ, где python с фремворком kivy показал себя с хорошей стороны. Например, ровно за один час, было написано приложение, для сети сервисных центров. Приложение работает в режиме киоска и установлено на дешевые китайские планшеты, которые висят в холле. Клиент набирает номер заказа, далее по WiFi планшет соединяется с сервером и сообщает статус заказа.

Источник

Как настроить интерпретатор Python в студии Android

Я пытаюсь использовать python в студии Android в качестве бэкэнд-кода для работы с переменными и получения ответа. Моя MainActivity находится на Java, и для кода Python создается каталог. когда я пытаюсь написать код на python, он сообщает, что «для модуля не настроен интерпретатор python», я добавил Chaquopy и подключаемый модуль сообщества Python. Также я хочу знать, как я могу отправить переменные для моей MainActivity на python и наоборот.

Я пытаюсь добавить Python в студию Android. Я пробовал Chaquopy, а также плагин сообщества Python. Я тоже пытался найти ответы в разных местах и путеводителях. Но до сих пор нет Удачи.

Это MainActivity, и я хочу отправить свою переменную «a» в файл python, чтобы с ней поработали.

2 ответа

когда я пытаюсь написать код на python, он сообщает, что «для модуля не настроен интерпретатор python»

Только некоторые функции плагина Python Community Edition будут правильно работать в Android Studio. Вы по-прежнему можете писать свой код Python в Android Studio, если хотите, но большая часть поддержки IDE будет недоступна.

как я могу отправить переменные для моей MainActivity на python и наоборот.

  • Меню файла
  • Структура проекта
  • Спуститесь в «Настройки платформы»
  • SDKs
  • нажмите кнопку +
  • Выберите «Python SDK»
  • Я выбрал «System Interpreter», но виртуальная среда envs обычно будет лучшим выбором.
  • После настройки SDK нажмите «Модули» в разделе «Настройки проекта».
  • Нажмите +
  • Выберите «Python» для своего типа модуля.

В комментарии говорится, что SDK не существует в Android Studio. Скриншот, демонстрирующий это для меня:

Источник

Building Android Apps With Python: Part -1

Step by Step Guide to Build Android Apps using Python

Aug 5, 2020 · 7 min read

Introduction

Are you curious about developing android apps but Java is not your companion? Android universe is mainly build using Java, Kotlin, Flutter, and Corona using Lua Scripting Language (mainly gaming engine, used in games like angry birds) but in recent times, Python has made its way into every domain and android is no different. In this series of articles, we will look at how to set-up the required environment, the basics of developing an android app, referencing the documentation, and how to move ahead with your projects.

Читайте также:  Как обновить прошу андроид

Kivy — The Godfather

Android devel o pment in Python has been made possible only because of an open-source Python library for developing mobile apps and other multi-touch application software that is Kivy. Its initial release was in 2011 and a stable one in 2019! Kivy not only supports android application development but its applications can be run on IOS, Linux, OS X, Windows, and Android. It is written in Python and Cython, and most of the core developers are from Russia.

We will use Kivy a lot for the front-end of the application but with another package and why we require that package will be covered shortly.

Setting the environment

It’s usually a good practice to set-up a new environment for new projects as:

  1. It helps in maintaining the different versions of different libraries. For example, ML flow requires a lower version of Numpy and when you try to install ML flow in the base directory, it conflicts with the pre-installed libraries and makes it difficult to manage different versions.
  2. It helps in isolating custom codes and makes it easier while deploying your application on any platform.

I use the Conda package manager for creating and managing my environments. You can use any other package manager but to follow along with me, you can use Conda (see this guide to set up Conda and anaconda). Open up your Conda terminal and type:

Replace ‘name-of-env’ with your custom name and ‘version’ of your choice but greater than 3.5. I will use Python 3.7. To list all the Conda environments, type:

The output will be similar to this:

Here is the link to the cheat-sheet of Conda in-case you are interested in exploring more about this. Now, after checking the name here, activate the environment like this:

We are ready to install the required libraries. As we are using python, pip is a great way to install and manage python packages. To install Kivy and its dependencies, type the following command one-by-one:

A bonus tip: Make a file called requirements.txt, copy the above lines in the file, place the file in a known location and terminal run:

It will install all the dependencies at one go!

We are ready to develop some awesome applications, but there is one problem here. In the beginning, I told you we need an additional package to be used with Kivy. Just install it for now and we will discuss the why part later in the article.

Let’s code!

The part you have been waiting for so long is here. I am using Pycharm IDE for coding because it’s easy to code for me, but you can use VSCode, Sublime, or spyder as per your wish. Before I start, we need to understand some points here:

  1. An android app has a front-end (UI/UX) or the interactive part where the user interacts with your application and all the inputs are given via this layer.
  2. The inputs are transferred to the backend layer, which is our python code. This backend layer controls the flow, processes the outputs, and the content to be displayed on the screen.
  3. Here, Object-Oriented Programming is highly used and most of the programming will be done using this concept so if you are lacking in this then I would suggest you follow this video by Keith Galli on OOP.

Now quickly open up your IDE and start with this basic code of Hello World!

After running this program you will see this output:

Let me explain this code line by line:

  1. The first line imports the base app from the Kivy library.
  2. Now we need to display some text on the screen and for displaying any text, we use Label functionality and as I told that these are UI/UX things, we will import them from the “kivy.uix” directory.
  3. The third line (ignore the white-space) of the code is where our OOP concept comes into play. The App which we have imported from the “kivy.app” is the base class of the App. What it means is that the Kivy sets up all the essential things to run our app and we need to inherit this app class, change it, and build our application. The name of this class should start with capitals and it also serves as the name of the app which can be changed later on so you can name it anything you want.
  4. def build function is the app entry point. All the things defined here will be built first and the first screen or the main screen is passed here. It returns the Label, and it has a property of text which has the value “Hello World”. Read more about labels here.
  5. Then the last line calls this main class and runs it.
Читайте также:  Как нарисовать анимацию андроид

Problem with Kivy

This how we build our first app but did you notice one thing that the background is automatically black and text is white? I haven’t even mentioned this in the code. Kivy takes it by default. Now we move to the interesting part, let’s build a simple button with no enhancement in Kivy:

Its output is like this:

This is a very unattractive look and imagines you are using an app that has an interface like this. I would uninstall that app and won’t even rate it! Enhancing features in Kivy is a tedious process and requires a lot of code. Don’t believe me? Look at the code to create a rectangular flat button placed at the center with a blue border, blue text, and white background:

Don’t grasp the code as it is beyond your scope for now but just look at the output now:

Doesn’t it look nice now!

Introducing Kivymd

Now we have talked a lot about Kivy and we know it provides the platform for building applications. KivyMD is a collection of Material Design compliant widgets for use with Kivy and approximately Google’s Material Design spec as close as possible without sacrificing ease of use or application performance. It is based on Kivy and is easier to code. It is very similar to Kivy and just adds MD at starting in every element and widget, plus it has a wide variety of other new elements. Now see the code in Kivymd to generate the same output button:

Try to run this script and you will see the same output as returned by long Kivy code.

Some more things to consider

  1. Performance Issues: The app you will develop will work perfectly fine on your local machine, but when you try to run it in android, the animations are not so smooth. Also, as it still runs as an instance of python, it is slow.
  2. Convert to android: One of the major tasks is to convert the python Kivy application into an Android package (APK) and it can only be done on a Linux OS. The additional packages like python-to-android, Android SDK, bulldozer are heavy and require a lot of time to build and debug the app. All the Kivy and Kivymd libraries are converted into Cython, and these are used by the Android system. This process is usually done with high precision.
  3. Still under development: This is an open-source project, and still a lot of work is going on under the hood. Always try to update the packages so you don’t face any issues.

Conclusion and what’s next

This was an introductory lesson to building android apps in python. We learned what is Kivy, why, and how to use environments, built a basic app in Kivy, compared Kivy and Kivymd with an example of a button code. In the next article, we will continue our journey and explore various other key elements in Kivymd. If you liked this article, follow me on medium so you receive notifications about upcoming parts. With that said sayonara!

You can find me here:
LinkedIn: Link

Источник

Оцените статью