Brooke  Giles

Brooke Giles

1614439359

馃毃 Android 11 Notifications In-Depth Guide

In this video, you will get a step by step instruction on how to build notifications for your Android 11 application using Jetpack and Kotlin

  • How to display text in a notification
  • Create inbox style notification
  • Create notifications with an image
  • How to display an image in a notification
  • How to use notifications

An in-depth guide on how to use Android 11 notifications and how to build notifications

#android #mobile-apps #jetpack #kotlin

What is GEEK

Buddha Community

馃毃 Android 11 Notifications In-Depth Guide

Build an Android application with Kivy Python framework

If you鈥檙e a Python developer thinking about getting started with mobile development, then the Kivy framework is your best bet. With Kivy, you can develop platform-independent applications that compile for iOS, Android, Windows, macOS, and Linux. In this article, we鈥檒l cover Android specifically because it is the most used.

We鈥檒l build a simple random number generator app that you can install on your phone and test when you are done. To follow along with this article, you should be familiar with Python. Let鈥檚 get started!

Getting started with Kivy

First, you鈥檒l need a new directory for your app. Make sure you have Python installed on your machine and open a new Python file. You鈥檒l need to install the Kivy module from your terminal using either of the commands below. To avoid any package conflicts, be sure you鈥檙e installing Kivy in a virtual environment:

pip install kivy 
//
pip3 install kivy 

Once you have installed Kivy, you should see a success message from your terminal that looks like the screenshots below:

Kivy installation

Successful Kivy installation

 

Next, navigate into your project folder. In the main.py file, we鈥檒l need to import the Kivy module and specify which version we want. You can use Kivy v2.0.0, but if you have a smartphone that is older than Android 8.0, I recommend using Kivy v1.9.0. You can mess around with the different versions during the build to see the differences in features and performance.

Add the version number right after the import kivy line as follows:

kivy.require('1.9.0')

Now, we鈥檒l create a class that will basically define our app; I鈥檒l name mine RandomNumber. This class will inherit the app class from Kivy. Therefore, you need to import the app by adding from kivy.app import App:

class RandomNumber(App): 

In the RandomNumber class, you鈥檒l need to add a function called build, which takes a self parameter. To actually return the UI, we鈥檒l use the build function. For now, I have it returned as a simple label. To do so, you鈥檒l need to import Label using the line from kivy.uix.label import Label:

import kivy
from kivy.app import App
from kivy.uix.label import Label

class RandomNumber(App):
  def build(self):
    return Label(text="Random Number Generator")

Now, our app skeleton is complete! Before moving forward, you should create an instance of the RandomNumber class and run it in your terminal or IDE to see the interface:

import kivy from kivy.app import App from kivy.uix.label import Label class RandomNumber(App):  def build(self):    return Label(text="Random Number Generator") randomApp = RandomNumber() randomApp.run()

When you run the class instance with the text Random Number Generator, you should see a simple interface or window that looks like the screenshot below:

 

Simple interface after running the code

You won鈥檛 be able to run the text on Android until you鈥檝e finished building the whole thing.

Outsourcing the interface

Next, we鈥檒l need a way to outsource the interface. First, we鈥檒l create a Kivy file in our directory that will house most of our design work. You鈥檒l want to name this file the same name as your class using lowercase letters and a .kv extension. Kivy will automatically associate the class name and the file name, but it may not work on Android if they are exactly the same.

Inside that .kv file, you need to specify the layout for your app, including elements like the label, buttons, forms, etc. To keep this demonstration simple, I鈥檒l add a label for the title Random Number, a label that will serve as a placeholder for the random number that is generated _, and a Generate button that calls the generate function.

My .kv file looks like the code below, but you can mess around with the different values to fit your requirements:

<boxLayout>:
    orientation: "vertical"
    Label:
        text: "Random Number"
        font_size: 30
        color: 0, 0.62, 0.96

    Label:
        text: "_"
        font_size: 30

    Button:
        text: "Generate"
        font_size: 15 

In the main.py file, you no longer need the Label import statement because the Kivy file takes care of your UI. However, you do need to import boxlayout, which you will use in the Kivy file.

In your main file, you need to add the import statement and edit your main.py file to read return BoxLayout() in the build method:

from kivy.uix.boxlayout import BoxLayout

If you run the command above, you should see a simple interface that has the random number title, the _ place holder, and the clickable generate button:

Random Number app rendered

Notice that you didn鈥檛 have to import anything for the Kivy file to work. Basically, when you run the app, it returns boxlayout by looking for a file inside the Kivy file with the same name as your class. Keep in mind, this is a simple interface, and you can make your app as robust as you want. Be sure to check out the Kv language documentation.

Generate the random number function

Now that our app is almost done, we鈥檒l need a simple function to generate random numbers when a user clicks the generate button, then render that random number into the app interface. To do so, we鈥檒l need to change a few things in our files.

First, we鈥檒l import the module that we鈥檒l use to generate a random number with import random. Then, we鈥檒l create a function or method that calls the generated number. For this demonstration, I鈥檒l use a range between 0 and 2000. Generating the random number is simple with the random.randint(0, 2000) command. We鈥檒l add this into our code in a moment.

Next, we鈥檒l create another class that will be our own version of the box layout. Our class will have to inherit the box layout class, which houses the method to generate random numbers and render them on the interface:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

Within that class, we鈥檒l create the generate method, which will not only generate random numbers but also manipulate the label that controls what is displayed as the random number in the Kivy file.

To accommodate this method, we鈥檒l first need to make changes to the .kv file . Since the MyRoot class has inherited the box layout, you can make MyRoot the top level element in your .kv file:

<MyRoot>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

Notice that you are still keeping all your UI specifications indented in the Box Layout. After this, you need to add an ID to the label that will hold the generated numbers, making it easy to manipulate when the generate function is called. You need to specify the relationship between the ID in this file and another in the main code at the top, just before the BoxLayout line:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

The random_label: random_label line basically means that the label with the ID random_label will be mapped to random_label in the main.py file, meaning that any action that manipulates random_label will be mapped on the label with the specified name.

We can now create the method to generate the random number in the main file:

def generate_number(self):
    self.random_label.text = str(random.randint(0, 2000))

# notice how the class method manipulates the text attributre of the random label by a# ssigning it a new random number generate by the 'random.randint(0, 2000)' funcion. S# ince this the random number generated is an integer, typecasting is required to make # it a string otherwise you will get a typeError in your terminal when you run it.

The MyRoot class should look like the code below:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

    def generate_number(self):
        self.random_label.text = str(random.randint(0, 2000))

Congratulations! You鈥檙e now done with the main file of the app. The only thing left to do is make sure that you call this function when the generate button is clicked. You need only add the line on_press: root.generate_number() to the button selection part of your .kv file:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15
            on_press: root.generate_number()

Now, you can run the app.

Compiling our app on Android

Before compiling our app on Android, I have some bad news for Windows users. You鈥檒l need Linux or macOS to compile your Android application. However, you don鈥檛 need to have a separate Linux distribution, instead, you can use a virtual machine.

To compile and generate a full Android .apk application, we鈥檒l use a tool called Buildozer. Let鈥檚 install Buildozer through our terminal using one of the commands below:

pip3 install buildozer
//
pip install buildozer

Now, we鈥檒l install some of Buildozer鈥檚 required dependencies. I am on Linux Ergo, so I鈥檒l use Linux-specific commands. You should execute these commands one by one:

sudo apt update
sudo apt install -y git zip unzip openjdk-13-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev

pip3 install --upgrade Cython==0.29.19 virtualenv 

# add the following line at the end of your ~/.bashrc file
export PATH=$PATH:~/.local/bin/

After executing the specific commands, run buildozer init. You should see an output similar to the screenshot below:

Buildozer successful initialization

The command above creates a Buildozer .spec file, which you can use to make specifications to your app, including the name of the app, the icon, etc. The .spec file should look like the code block below:

[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

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

# (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 = 0.1

# (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

# (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 = 1.9.1

#
# Android specific
#

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

# (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

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

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

# (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 = False

# (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 = 2

# (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
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#


#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

If you want to specify things like the icon, requirements, loading screen, etc., you should edit this file. After making all the desired edits to your application, run buildozer -v android debug from your app directory to build and compile your application. This may take a while, especially if you have a slow machine.

After the process is done, your terminal should have some logs, one confirming that the build was successful:

Android successful build

You should also have an APK version of your app in your bin directory. This is the application executable that you will install and run on your phone:

Android .apk in the bin directory

Conclusion

Congratulations! If you have followed this tutorial step by step, you should have a simple random number generator app on your phone. Play around with it and tweak some values, then rebuild. Running the rebuild will not take as much time as the first build.

As you can see, building a mobile application with Python is fairly straightforward, as long as you are familiar with the framework or module you are working with. Regardless, the logic is executed the same way.

Get familiar with the Kivy module and it鈥檚 widgets. You can never know everything all at once. You only need to find a project and get your feet wet as early as possible. Happy coding.

Link: https://blog.logrocket.com/build-android-application-kivy-python-framework/

#python 

Cree Una Aplicaci贸n De Android Con El Marco Kivy Python

Si es un desarrollador de Python que est谩 pensando en comenzar con el desarrollo m贸vil, entonces el marco Kivy es su mejor opci贸n. Con Kivy, puede desarrollar aplicaciones independientes de la plataforma que compilan para iOS, Android, Windows, macOS y Linux. En este art铆culo, cubriremos Android espec铆ficamente porque es el m谩s utilizado.

Construiremos una aplicaci贸n generadora de n煤meros aleatorios simple que puede instalar en su tel茅fono y probar cuando haya terminado. Para continuar con este art铆culo, debe estar familiarizado con Python. 隆Empecemos!

Primeros pasos con Kivy

Primero, necesitar谩 un nuevo directorio para su aplicaci贸n. Aseg煤rese de tener Python instalado en su m谩quina y abra un nuevo archivo de Python. Deber谩 instalar el m贸dulo Kivy desde su terminal usando cualquiera de los comandos a continuaci贸n. Para evitar conflictos de paquetes, aseg煤rese de instalar Kivy en un entorno virtual:

pip install kivy 
//
pip3 install kivy 

Una vez que haya instalado Kivy, deber铆a ver un mensaje de 茅xito de su terminal que se parece a las capturas de pantalla a continuaci贸n:

Instalaci贸n decepcionada

Instalaci贸n exitosa de Kivy

 

A continuaci贸n, navegue a la carpeta de su proyecto. En el main.pyarchivo, necesitaremos importar el m贸dulo Kivy y especificar qu茅 versi贸n queremos. Puede usar Kivy v2.0.0, pero si tiene un tel茅fono inteligente anterior a Android 8.0, le recomiendo usar Kivy v1.9.0. Puede jugar con las diferentes versiones durante la compilaci贸n para ver las diferencias en las caracter铆sticas y el rendimiento.

Agregue el n煤mero de versi贸n justo despu茅s de la import kivyl铆nea de la siguiente manera:

kivy.require('1.9.0')

Ahora, crearemos una clase que b谩sicamente definir谩 nuestra aplicaci贸n; Voy a nombrar el m铆o RandomNumber. Esta clase heredar谩 la appclase de Kivy. Por lo tanto, debe importar appagregando from kivy.app import App:

class RandomNumber(App): 

En la RandomNumberclase, deber谩 agregar una funci贸n llamada build, que toma un selfpar谩metro. Para devolver la interfaz de usuario, usaremos la buildfunci贸n. Por ahora, lo tengo devuelto como una simple etiqueta. Para hacerlo, deber谩 importar Labelusando la l铆nea from kivy.uix.label import Label:

import kivy
from kivy.app import App
from kivy.uix.label import Label

class RandomNumber(App):
  def build(self):
    return Label(text="Random Number Generator")

隆Ahora, el esqueleto de nuestra aplicaci贸n est谩 completo! Antes de continuar, debe crear una instancia de la RandomNumberclase y ejecutarla en su terminal o IDE para ver la interfaz:

importar kivy de kivy.app importar aplicaci贸n de kivy.uix.label clase de etiqueta de importaci贸n RandomNumber(App): def build(self): return Label(text="Generador de n煤meros aleatorios") randomApp = RandomNumber() randomApp.run()

Cuando ejecuta la instancia de clase con el texto Random Number Generator, deber铆a ver una interfaz o ventana simple que se parece a la siguiente captura de pantalla:

 

Interfaz simple despu茅s de ejecutar el c贸digo.

No podr谩 ejecutar el texto en Android hasta que haya terminado de construir todo.

Externalizaci贸n de la interfaz

A continuaci贸n, necesitaremos una forma de subcontratar la interfaz. Primero, crearemos un archivo Kivy en nuestro directorio que albergar谩 la mayor parte de nuestro trabajo de dise帽o. Querr谩 nombrar este archivo con el mismo nombre que su clase usando letras min煤sculas y una .kvextensi贸n. Kivy asociar谩 autom谩ticamente el nombre de la clase y el nombre del archivo, pero es posible que no funcione en Android si son exactamente iguales.

Dentro de ese .kvarchivo, debe especificar el dise帽o de su aplicaci贸n, incluidos elementos como la etiqueta, los botones, los formularios, etc. Para simplificar esta demostraci贸n, agregar茅 una etiqueta para el t铆tulo Random Number, una etiqueta que servir谩 como marcador de posici贸n. para el n煤mero aleatorio que se genera _, y un Generatebot贸n que llama a la generatefunci贸n.

Mi .kvarchivo se parece al siguiente c贸digo, pero puede jugar con los diferentes valores para que se ajusten a sus requisitos:

<boxLayout>:
    orientation: "vertical"
    Label:
        text: "Random Number"
        font_size: 30
        color: 0, 0.62, 0.96

    Label:
        text: "_"
        font_size: 30

    Button:
        text: "Generate"
        font_size: 15 

En el main.pyarchivo, ya no necesita la Labeldeclaraci贸n de importaci贸n porque el archivo Kivy se encarga de su interfaz de usuario. Sin embargo, necesita importar boxlayout, que utilizar谩 en el archivo Kivy.

En su archivo principal, debe agregar la declaraci贸n de importaci贸n y editar su main.pyarchivo para leer return BoxLayout()el buildm茅todo:

from kivy.uix.boxlayout import BoxLayout

Si ejecuta el comando anterior, deber铆a ver una interfaz simple que tiene el t铆tulo del n煤mero aleatorio, el _marcador de posici贸n y el generatebot贸n en el que se puede hacer clic:

Aplicaci贸n de n煤meros aleatorios renderizada

Tenga en cuenta que no tuvo que importar nada para que funcione el archivo Kivy. B谩sicamente, cuando ejecuta la aplicaci贸n, regresa boxlayoutbuscando un archivo dentro del archivo Kivy con el mismo nombre que su clase. Tenga en cuenta que esta es una interfaz simple y puede hacer que su aplicaci贸n sea tan robusta como desee. Aseg煤rese de consultar la documentaci贸n del idioma Kv .

Generar la funci贸n de n煤meros aleatorios

Ahora que nuestra aplicaci贸n est谩 casi terminada, necesitaremos una funci贸n simple para generar n煤meros aleatorios cuando un usuario haga clic en el generatebot贸n y luego mostrar ese n煤mero aleatorio en la interfaz de la aplicaci贸n. Para hacerlo, necesitaremos cambiar algunas cosas en nuestros archivos.

Primero, importaremos el m贸dulo que usaremos para generar un n煤mero aleatorio con import random. Luego, crearemos una funci贸n o m茅todo que llame al n煤mero generado. Para esta demostraci贸n, usar茅 un rango entre 0y 2000. Generar el n煤mero aleatorio es simple con el random.randint(0, 2000)comando. Agregaremos esto a nuestro c贸digo en un momento.

A continuaci贸n, crearemos otra clase que ser谩 nuestra propia versi贸n del box layout. Nuestra clase tendr谩 que heredar la box layoutclase, que alberga el m茅todo para generar n煤meros aleatorios y representarlos en la interfaz:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

Dentro de esa clase, crearemos el generatem茅todo, que no solo generar谩 n煤meros aleatorios, sino que tambi茅n manipular谩 la etiqueta que controla lo que se muestra como n煤mero aleatorio en el archivo Kivy.

Para acomodar este m茅todo, primero necesitaremos hacer cambios en el .kvarchivo. Dado que la MyRootclase ha heredado el box layout, puede crear MyRootel elemento de nivel superior en su .kvarchivo:

<MyRoot>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

Tenga en cuenta que todav铆a mantiene todas las especificaciones de la interfaz de usuario con sangr铆a en el archivo Box Layout. Despu茅s de esto, debe agregar una identificaci贸n a la etiqueta que contendr谩 los n煤meros generados, lo que facilita la manipulaci贸n cuando generatese llama a la funci贸n. Debe especificar la relaci贸n entre la ID en este archivo y otra en el c贸digo principal en la parte superior, justo antes de la BoxLayoutl铆nea:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

La random_label: random_labell铆nea b谩sicamente significa que la etiqueta con el ID random_labelse asignar谩 a random_labelen el main.pyarchivo, lo que significa que cualquier acci贸n que manipula random_labelser谩n mapeados en la etiqueta con el nombre especificado.

Ahora podemos crear el m茅todo para generar el n煤mero aleatorio en el archivo principal:

def generate_number(self):
    self.random_label.text = str(random.randint(0, 2000))

# notice how the class method manipulates the text attributre of the random label by a# ssigning it a new random number generate by the 'random.randint(0, 2000)' funcion. S# ince this the random number generated is an integer, typecasting is required to make # it a string otherwise you will get a typeError in your terminal when you run it.

La MyRootclase deber铆a parecerse al siguiente c贸digo:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

    def generate_number(self):
        self.random_label.text = str(random.randint(0, 2000))

隆Felicidades! Ya ha terminado con el archivo principal de la aplicaci贸n. Lo 煤nico que queda por hacer es asegurarse de llamar a esta funci贸n cuando se haga generateclic en el bot贸n. Solo necesita agregar la l铆nea on_press: root.generate_number()a la parte de selecci贸n de botones de su .kvarchivo:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15
            on_press: root.generate_number()

Ahora, puede ejecutar la aplicaci贸n.

Compilando nuestra aplicaci贸n en Android

Antes de compilar nuestra aplicaci贸n en Android, tengo malas noticias para los usuarios de Windows. Necesitar谩 Linux o macOS para compilar su aplicaci贸n de Android. Sin embargo, no necesita tener una distribuci贸n de Linux separada, en su lugar, puede usar una m谩quina virtual.

Para compilar y generar una .apkaplicaci贸n Android completa , usaremos una herramienta llamada Buildozer . Instalemos Buildozer a trav茅s de nuestra terminal usando uno de los siguientes comandos:

pip3 install buildozer
//
pip install buildozer

Ahora, instalaremos algunas de las dependencias requeridas de Buildozer. Estoy en Linux Ergo, as铆 que usar茅 comandos espec铆ficos de Linux. Debe ejecutar estos comandos uno por uno:

sudo apt update
sudo apt install -y git zip unzip openjdk-13-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev

pip3 install --upgrade Cython==0.29.19 virtualenv 

# add the following line at the end of your ~/.bashrc file
export PATH=$PATH:~/.local/bin/

Despu茅s de ejecutar los comandos espec铆ficos, ejecute buildozer init. Deber铆a ver un resultado similar a la captura de pantalla a continuaci贸n:

Inicializaci贸n exitosa de Buildozer

El comando anterior crea un .specarchivo Buildozer , que puede usar para hacer especificaciones para su aplicaci贸n, incluido el nombre de la aplicaci贸n, el 铆cono, etc. El .specarchivo debe verse como el bloque de c贸digo a continuaci贸n:

[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

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

# (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 = 0.1

# (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

# (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 = 1.9.1

#
# Android specific
#

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

# (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

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

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

# (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 = False

# (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 = 2

# (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
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#


#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

Si desea especificar cosas como el 铆cono, los requisitos, la pantalla de carga, etc., debe editar este archivo. Despu茅s de realizar todas las ediciones deseadas en su aplicaci贸n, ejecute buildozer -v android debugdesde el directorio de su aplicaci贸n para construir y compilar su aplicaci贸n. Esto puede llevar un tiempo, especialmente si tiene una m谩quina lenta.

Una vez finalizado el proceso, su terminal deber铆a tener algunos registros, uno que confirme que la compilaci贸n fue exitosa:

Construcci贸n exitosa de Android

Tambi茅n debe tener una versi贸n APK de su aplicaci贸n en su directorio bin. Este es el ejecutable de la aplicaci贸n que instalar谩 y ejecutar谩 en su tel茅fono:

Android .apk en el directorio bin

Conclusi贸n

隆Felicidades! Si ha seguido este tutorial paso a paso, deber铆a tener una aplicaci贸n simple de generador de n煤meros aleatorios en su tel茅fono. Juega con 茅l y ajusta algunos valores, luego reconstruye. Ejecutar la reconstrucci贸n no llevar谩 tanto tiempo como la primera compilaci贸n.

Como puede ver, crear una aplicaci贸n m贸vil con Python es bastante sencillo , siempre que est茅 familiarizado con el marco o m贸dulo con el que est谩 trabajando. Independientemente, la l贸gica se ejecuta de la misma manera.

Familiar铆cese con el m贸dulo Kivy y sus widgets. Nunca se puede saber todo a la vez. Solo necesita encontrar un proyecto y mojarse los pies lo antes posible. Codificaci贸n feliz.

Enlace: https://blog.logrocket.com/build-android-application-kivy-python-framework/

#python 

KivyPython銉曘儸銉笺儬銉兗銈倰浣跨敤銇椼仸Android銈€儣銉偙銉笺偡銉с兂銈掓绡夈仚銈

銇傘仾銇熴亴銉€儛銈ゃ儷闁嬬櫤銈掑銈併倠銇撱仺銈掕冦亪銇︺亜銈婸ython闁嬬櫤鑰呫仾銈銆並ivy銉曘儸銉笺儬銉兗銈銇屾渶鍠勩伄绛栥仹銇欍侹ivy銈掍娇鐢ㄣ仚銈嬨仺銆乮OS銆丄ndroid銆乄indows銆乵acOS銆併亰銈堛伋Linux鐢ㄣ伀銈炽兂銉戙偆銉仌銈屻倠銉椼儵銉冦儓銉曘偐銉笺儬銇緷瀛樸仐銇亜銈€儣銉偙銉笺偡銉с兂銈掗枊鐧恒仹銇嶃伨銇欍傘亾銇浜嬨仹銇丄ndroid銇屾渶銈備娇鐢ㄣ仌銈屻仸銇勩倠銇熴倎銆佺壒銇獳ndroid銇仱銇勩仸瑾槑銇椼伨銇欍

绨″崢銇贡鏁般偢銈с儘銉兗銈裤兗銈€儣銉倰浣滄垚銇椼伨銇欍傘亾銇偄銉椼儶銈掓惡甯浕瑭便伀銈ゃ兂銈广儓銉笺儷銇椼仸銆佸畬浜嗐仐銇熴倝銉嗐偣銉堛仹銇嶃伨銇欍傘亾銇浜嬨倰缍氥亼銈嬨伀銇丳ython銇簿閫氥仐銇︺亜銈嬪繀瑕併亴銇傘倞銇俱仚銆傚銈併伨銇椼倗銇嗭紒

Kivy銈掍娇銇勫銈併倠

銇俱仛銆併偄銉椼儶鐢ㄣ伄鏂般仐銇勩儑銈c儸銈儓銉亴蹇呰銇仾銈娿伨銇欍傘優銈枫兂銇玃ython銇屻偆銉炽偣銉堛兗銉仌銈屻仸銇勩倠銇撱仺銈掔⒑瑾嶃仐銆佹柊銇椼亜Python銉曘偂銈ゃ儷銈掗枊銇嶃伨銇欍備互涓嬨伄銈炽優銉炽儔銇亜銇氥倢銇嬨倰浣跨敤銇椼仸銆併偪銉笺儫銉娿儷銇嬨倝Kivy銉€偢銉ャ兗銉倰銈ゃ兂銈广儓銉笺儷銇欍倠蹇呰銇屻亗銈娿伨銇欍傘儜銉冦偙銉笺偢銇鍚堛倰閬裤亼銈嬨仧銈併伀銆並ivy銈掍划鎯崇挵澧冦伀銈ゃ兂銈广儓銉笺儷銇椼仸銇勩倠銇撱仺銈掔⒑瑾嶃仐銇︺亸銇犮仌銇勩

pip install kivy 
//
pip3 install kivy 

Kivy銈掋偆銉炽偣銉堛兗銉仚銈嬨仺銆佷互涓嬨伄銈广偗銉兗銉炽偡銉с儍銉堛伄銈堛亞銇垚鍔熴儭銉冦偦銉笺偢銇屻偪銉笺儫銉娿儷銇嬨倝琛ㄧず銇曘倢銇俱仚銆

銇屻仯銇嬨倞銇椼仧銈ゃ兂銈广儓銉笺儷

Kivy銇偆銉炽偣銉堛兗銉伀鎴愬姛

 

娆°伀銆併儣銉偢銈с偗銉堛儠銈┿儷銉銇Щ鍕曘仐銇俱仚銆傘亾銇main.py銉曘偂銈ゃ儷銇с並ivy銉€偢銉ャ兗銉倰銈ゃ兂銉濄兗銉堛仐銆佸繀瑕併仾銉愩兗銈搞儳銉炽倰鎸囧畾銇欍倠蹇呰銇屻亗銈娿伨銇欍侹ivy v2.0.0銈掍娇鐢ㄣ仹銇嶃伨銇欍亴銆丄ndroid 8.0銈堛倞鍙ゃ亜銈广優銉笺儓銉曘偐銉炽倰浣跨敤銇椼仸銇勩倠鍫村悎銇並ivyv1.9.0銈掍娇鐢ㄣ仚銈嬨亾銇ㄣ倰銇婂嫥銈併仐銇俱仚銆傘儞銉儔涓伀銇曘伨銇栥伨銇儛銉笺偢銉с兂銈掋亜銇樸仯銇︺佹鑳姐仺銉戙儠銈┿兗銉炪兂銈广伄閬曘亜銈掔⒑瑾嶃仹銇嶃伨銇欍

import kivy娆°伄銈堛亞銇佽銇洿寰屻伀銉愩兗銈搞儳銉崇暘鍙枫倰杩藉姞銇椼伨銇欍

kivy.require('1.9.0')

娆°伀銆佸熀鏈殑銇偄銉椼儶銈掑畾缇┿仚銈嬨偗銉┿偣銈掍綔鎴愩仐銇俱仚銆傜銇悕鍓嶃倰浠樸亼銇俱仚RandomNumber銆傘亾銇偗銉┿偣銇appKivy銇嬨倝銈儵銈广倰缍欐壙銇椼伨銇欍傘仐銇熴亴銇c仸銆佹app銈掕拷鍔犮仐銇︺偆銉炽儩銉笺儓銇欍倠蹇呰銇屻亗銈娿伨銇from kivy.app import App

class RandomNumber(App): 

銇с伅RandomNumber銈儵銈广伅銆佸懠銇冲嚭銇曘倢銇熼枹鏁般倰杩藉姞銇欍倠蹇呰銇屻亗銈娿伨銇build銇ㄣ倞銆self銉戙儵銉°兗銈裤倰銆傚疅闅涖伀UI銈掕繑銇欍伀銇併亾銇build闁㈡暟銈掍娇鐢ㄣ仐銇俱仚銆備粖銇仺銇撱倣銆佸崢绱斻仾銉┿儥銉仺銇椼仸杩旈併仐銇︺亜銇俱仚銆傘仢銇仧銈併伀銇佹Label銇銈掍娇鐢ㄣ仐銇︺偆銉炽儩銉笺儓銇欍倠蹇呰銇屻亗銈娿伨銇from kivy.uix.label import Label

import kivy
from kivy.app import App
from kivy.uix.label import Label

class RandomNumber(App):
  def build(self):
    return Label(text="Random Number Generator")

銇撱倢銇с併偄銉椼儶銇偣銈便儷銉堛兂銇屽畬鎴愩仐銇俱仐銇熴傚厛銇层個鍓嶃伀銆RandomNumber銈儵銈广伄銈ゃ兂銈广偪銉炽偣銈掍綔鎴愩仐銆併偪銉笺儫銉娿儷銇俱仧銇疘DE銇у疅琛屻仐銇︺併偆銉炽偪銉笺儠銈с偆銈广倰纰鸿獚銇欍倠蹇呰銇屻亗銈娿伨銇欍

import kivy from kivy.app import App from kivy.uix.label import Label class RandomNumber锛圓pp锛夛細def build锛坰elf锛夛細return Label锛坱ext = "Random Number Generator"锛塺andomApp = RandomNumber锛堬級randomApp.run锛堬級

銉嗐偔銈广儓銈掍娇鐢ㄣ仐銇︺偗銉┿偣銈ゃ兂銈广偪銉炽偣銈掑疅琛屻仚銈嬨仺銆Random Number Generator娆°伄銈广偗銉兗銉炽偡銉с儍銉堛伄銈堛亞銇崢绱斻仾銈ゃ兂銈裤兗銉曘偋銈ゃ偣銇俱仧銇偊銈c兂銉夈偊銇岃〃绀恒仌銈屻伨銇欍

 

銈炽兗銉夈倰瀹熻銇椼仧寰屻伄銈枫兂銉椼儷銇偆銉炽偪銉笺儠銈с偆銈

銇欍伖銇︺伄妲嬬瘔銇屽畬浜嗐仚銈嬨伨銇с丄ndroid銇с儐銈偣銉堛倰瀹熻銇欍倠銇撱仺銇仹銇嶃伨銇涖倱銆

銈ゃ兂銈裤兗銉曘偋銉笺偣銇偄銈︺儓銈姐兗銈枫兂銈

娆°伀銆併偆銉炽偪銉笺儠銈с兗銈广倰銈€偊銉堛偨銉笺偡銉炽偘銇欍倠鏂规硶銇屽繀瑕併伀銇倞銇俱仚銆傘伨銇氥併儑銈c儸銈儓銉伀Kivy銉曘偂銈ゃ儷銈掍綔鎴愩仐銇俱仚銆傘亾銇儠銈°偆銉伀銇併伝銇ㄣ倱銇┿伄瑷▓浣滄キ銇屽惈銇俱倢銇︺亜銇俱仚銆傘亾銇儠銈°偆銉伀銇佸皬鏂囧瓧銇.kv鎷″嫉瀛愩倰浣跨敤銇椼仸銆併偗銉┿偣銇ㄥ悓銇樺悕鍓嶃倰浠樸亼銈嬨亾銇ㄣ亴銇с亶銇俱仚銆侹ivy銇偗銉┿偣鍚嶃仺銉曘偂銈ゃ儷鍚嶃倰鑷嫊鐨勩伀闁㈤d粯銇戙伨銇欍亴銆併仢銈屻倝銇屻伨銇c仧銇忓悓銇樸仹銇傘倠鍫村悎銆丄ndroid銇с伅姗熻兘銇椼仾銇勫彲鑳芥с亴銇傘倞銇俱仚銆

銇濄伄.kv銉曘偂銈ゃ儷鍐呫仹銆併儵銉欍儷銆併儨銈裤兂銆併儠銈┿兗銉犮仾銇┿伄瑕佺礌銈掑惈銈銈€儣銉伄銉偆銈€偊銉堛倰鎸囧畾銇欍倠蹇呰銇屻亗銈娿伨銇欍傘亾銇儑銉€倰绨″崢銇仚銈嬨仧銈併伀銆併偪銈ゃ儓銉Random Number銇儵銉欍儷銆併儣銉兗銈广儧銉儉銉笺仺銇椼仸姗熻兘銇欍倠銉┿儥銉倰杩藉姞銇椼伨銇欍傜敓鎴愩仌銈屻倠涔辨暟_銆併亰銈堛伋闁㈡暟Generate銈掑懠銇冲嚭銇欍儨銈裤兂generate

绉併伄.kv銉曘偂銈ゃ儷銇互涓嬨伄銈炽兗銉夈伄銈堛亞銇銇堛伨銇欍亴銆佽浠躲伀鍚堛倧銇涖仸銇曘伨銇栥伨銇ゃ倰銇勩仒銈嬨亾銇ㄣ亴銇с亶銇俱仚銆

<boxLayout>:
    orientation: "vertical"
    Label:
        text: "Random Number"
        font_size: 30
        color: 0, 0.62, 0.96

    Label:
        text: "_"
        font_size: 30

    Button:
        text: "Generate"
        font_size: 15 

銇撱伄main.py銉曘偂銈ゃ儷銇с伅Label銆並ivy銉曘偂銈ゃ儷銇孶I銈掑嚘鐞嗐仚銈嬨仧銈併乮mport銈广儐銉笺儓銉°兂銉堛伅涓嶈銇仾銈娿伨銇椼仧銆傘仧銇犮仐銆boxlayoutKivy銉曘偂銈ゃ儷銇т娇鐢ㄣ仚銈嬨倰銈ゃ兂銉濄兗銉堛仚銈嬪繀瑕併亴銇傘倞銇俱仚銆

銉°偆銉炽儠銈°偆銉仹銆乮mport銈广儐銉笺儓銉°兂銉堛倰杩藉姞銇椼main.py銉曘偂銈ゃ儷銈掔法闆return BoxLayout()銇椼仸build銉°偨銉冦儔銇ц銇垮彇銈嬪繀瑕併亴銇傘倞銇俱仚銆

from kivy.uix.boxlayout import BoxLayout

涓婅銇偝銉炪兂銉夈倰瀹熻銇欍倠銇ㄣ佷贡鏁般伄銈裤偆銉堛儷銆_銉椼儸銉笺偣銉涖儷銉銉笺併亰銈堛伋銈儶銉冦偗鍙兘銇generate銉溿偪銉炽倰鍌欍亪銇熴偡銉炽儣銉仾銈ゃ兂銈裤兗銉曘偋銈ゃ偣銇岃〃绀恒仌銈屻伨銇欍

銉兂銉銉兂銈般仌銈屻仧涔辨暟銈€儣銉

Kivy銉曘偂銈ゃ儷銈掓鑳姐仌銇涖倠銇熴倎銇綍銈傘偆銉炽儩銉笺儓銇欍倠蹇呰銇屻仾銇嬨仯銇熴亾銇ㄣ伀娉ㄦ剰銇椼仸銇忋仩銇曘亜銆傚熀鏈殑銇併偄銉椼儶銈掑疅琛屻仚銈boxlayout銇ㄣ併偗銉┿偣銇ㄥ悓銇樺悕鍓嶃伄Kivy銉曘偂銈ゃ儷鍐呫伄銉曘偂銈ゃ儷銈掓绱€仐銇︽埢銈娿伨銇欍傘亾銈屻伅銈枫兂銉椼儷銇偆銉炽偪銉笺儠銈с兗銈广仹銇傘倞銆併偄銉椼儶銈掑繀瑕併伀蹇溿仒銇﹀爡鐗€伀銇欍倠銇撱仺銇屻仹銇嶃伨銇欍Kv瑷瑾炪伄銉夈偔銉ャ儭銉炽儓銈蹇呫仛纰鸿獚銇椼仸銇忋仩銇曘亜銆

涔辨暟闁㈡暟銈掔敓鎴愩仚銈

銈€儣銉亴銇汇伡瀹屾垚銇椼仧銇仹銆併儲銉笺偠銉笺亴generate銉溿偪銉炽倰銈儶銉冦偗銇椼仧銇ㄣ亶銇贡鏁般倰鐢熸垚銇椼併仢銇贡鏁般倰銈€儣銉伄銈ゃ兂銈裤兗銉曘偋銈ゃ偣銇儸銉炽儉銉兂銈般仚銈嬬啊鍗樸仾闁㈡暟銇屽繀瑕併伀銇倞銇俱仚銆傘仢銇仧銈併伀銇併儠銈°偆銉唴銇亜銇忋仱銇嬨伄澶夋洿銈掕銇嗗繀瑕併亴銇傘倞銇俱仚銆

銇俱仛銆併仹涔辨暟銈掔敓鎴愩仚銈嬨仧銈併伀浣跨敤銇欍倠銉€偢銉ャ兗銉倰銈ゃ兂銉濄兗銉堛仐銇俱仚import random銆傛銇佺敓鎴愩仌銈屻仧鐣彿銈掑懠銇冲嚭銇欓枹鏁般伨銇熴伅銉°偨銉冦儔銈掍綔鎴愩仐銇俱仚銆傘亾銇儑銉€仹銇佺銇枔銇瘎鍥层倰浣跨敤銇椼伨銇02000銆傘亾銇random.randint(0, 2000)銈炽優銉炽儔銈掍娇鐢ㄣ仚銈嬨仺銆佷贡鏁般倰绨″崢銇敓鎴愩仹銇嶃伨銇欍傘亾銈屻倰銇欍亹銇偝銉笺儔銇拷鍔犮仐銇俱仚銆

娆°伀銆佺嫭鑷伄銉愩兗銈搞儳銉炽仺銇倠鍒ャ伄銈儵銈广倰浣滄垚銇椼伨銇box layout銆傘亾銇box layout銈儵銈广伅銆佷贡鏁般倰鐢熸垚銇椼仸銈ゃ兂銈裤兗銉曘偋銈ゃ偣涓娿仹銉兂銉銉兂銈般仚銈嬨儭銈姐儍銉夈倰鍚個銈儵銈广倰缍欐壙銇欍倠蹇呰銇屻亗銈娿伨銇欍

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

銇濄伄銈儵銈瑰唴銇сgenerate涔辨暟銈掔敓鎴愩仚銈嬨仩銇戙仹銇亸銆並ivy銉曘偂銈ゃ儷銇贡鏁般仺銇椼仸琛ㄧず銇曘倢銈嬨倐銇倰鍒跺尽銇欍倠銉┿儥銉倰鎿嶄綔銇欍倠銉°偨銉冦儔銈掍綔鎴愩仐銇俱仚銆

銇撱伄鏂规硶銇蹇溿仚銈嬨伀銇佹渶鍒濄伀.kv銉曘偂銈ゃ儷銇鏇淬倰鍔犮亪銈嬪繀瑕併亴銇傘倞銇俱仚銆備互鏉MyRoot銈儵銈广亴缍欐壙銇椼仸銇勩倠box layout銆併亗銇仧銇屼綔銈嬨亾銇ㄣ亴銇с亶銈MyRoot銇傘仾銇熴伄銉堛儍銉椼儸銉欍儷銇绱.kv銉曘偂銈ゃ儷銈掞細

<MyRoot>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

銇с偆銉炽儑銉炽儓銇曘倢銇熴仚銇广仸銇甎I浠曟銈掍繚鎸併仐銇︺亜銈嬨亾銇ㄣ伀娉ㄦ剰銇椼仸銇忋仩銇曘亜Box Layout銆傘亾銇緦銆佺敓鎴愩仌銈屻仧鐣彿銈掍繚鎸併仚銈婭D銈掋儵銉欍儷銇拷鍔犮仐銇︺generate闁㈡暟銇屽懠銇冲嚭銇曘倢銇熴仺銇嶃伀绨″崢銇搷浣溿仹銇嶃倠銈堛亞銇仚銈嬪繀瑕併亴銇傘倞銇俱仚銆傘亾銇儠銈°偆銉伄ID銇ㄣ佷笂閮ㄣ伄銉°偆銉炽偝銉笺儔銇垾銇甀D銇ㄣ伄闁總銈掋佹銇BoxLayout琛屻伄鐩村墠銇寚瀹氥仚銈嬪繀瑕併亴銇傘倞銇俱仚銆

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

銇撱伄random_label: random_label琛屻伅鍩烘湰鐨勩伀銆両Drandom_label銈掓寔銇ゃ儵銉欍儷銇屻儠銈°偆銉random_label鍐呫伀銉炪儍銉椼仌銈屻倠銇撱仺銈main.py鎰忓懗銇椼伨銇欍傘仱銇俱倞銆佹搷浣random_label銇欍倠銈€偗銈枫儳銉炽伅銇欍伖銇︺佹寚瀹氥仌銈屻仧鍚嶅墠銇儵銉欍儷銇優銉冦儣銇曘倢銇俱仚銆

銇撱倢銇с併儭銈ゃ兂銉曘偂銈ゃ儷銇贡鏁般倰鐢熸垚銇欍倠銉°偨銉冦儔銈掍綔鎴愩仹銇嶃伨銇欍

def generate_number(self):
    self.random_label.text = str(random.randint(0, 2000))

# notice how the class method manipulates the text attributre of the random label by a# ssigning it a new random number generate by the 'random.randint(0, 2000)' funcion. S# ince this the random number generated is an integer, typecasting is required to make # it a string otherwise you will get a typeError in your terminal when you run it.

MyRoot銇撱伄銈儵銈广伅銆佷互涓嬨伄銈炽兗銉夈伄銈堛亞銇仾銈娿伨銇欍

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

    def generate_number(self):
        self.random_label.text = str(random.randint(0, 2000))

銇娿倎銇с仺銇嗭紒銇撱倢銇с併偄銉椼儶銇儭銈ゃ兂銉曘偂銈ゃ儷銇屽畬鎴愩仐銇俱仐銇熴傘亗銇ㄣ伅銆generate銉溿偪銉炽亴銈儶銉冦偗銇曘倢銇熴仺銇嶃伀蹇呫仛銇撱伄闁㈡暟銈掑懠銇冲嚭銇欍倛銇嗐伀銇椼仸銇忋仩銇曘亜銆傘儠銈°偆銉伄on_press: root.generate_number()銉溿偪銉抽伕鎶為儴鍒嗐伀琛屻倰杩藉姞銇欍倠銇犮亼銇ф笀銇.kv銇俱仚銆

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15
            on_press: root.generate_number()

銇撱倢銇с併偄銉椼儶銈掑疅琛屻仹銇嶃伨銇欍

Android銇с偄銉椼儶銈掋偝銉炽儜銈ゃ儷銇欍倠

Android銇с偄銉椼儶銈掋偝銉炽儜銈ゃ儷銇欍倠鍓嶃伀銆乄indows銉︺兗銈躲兗銇仺銇c仸鎮亜銉嬨儱銉笺偣銇屻亗銈娿伨銇欍侫ndroid銈€儣銉偙銉笺偡銉с兂銈掋偝銉炽儜銈ゃ儷銇欍倠銇伅銆丩inux銇俱仧銇痬acOS銇屽繀瑕併仹銇欍傘仧銇犮仐銆佸嬪垾銇甃inux銉囥偅銈广儓銉儞銉ャ兗銈枫儳銉炽倰鐢ㄦ剰銇欍倠蹇呰銇仾銇忋佷唬銈忋倞銇划鎯炽優銈枫兂銈掍娇鐢ㄣ仹銇嶃伨銇欍

瀹屽叏銇狝ndroid.apk銈€儣銉偙銉笺偡銉с兂銈掋偝銉炽儜銈ゃ儷銇椼仸鐢熸垚銇欍倠銇伅銆Buildozer銇ㄣ亜銇嗐儎銉笺儷銈掍娇鐢ㄣ仐銇俱仚銆備互涓嬨伄銈炽優銉炽儔銇亜銇氥倢銇嬨倰浣跨敤銇椼仸銆併偪銉笺儫銉娿儷銇嬨倝Buildozer銈掋偆銉炽偣銉堛兗銉仐銇俱仐銈囥亞銆

pip3 install buildozer
//
pip install buildozer

娆°伀銆丅uildozer銇繀瑕併仾渚濆瓨闁總銇亜銇忋仱銇嬨倰銈ゃ兂銈广儓銉笺儷銇椼伨銇欍傜銇疞inuxErgo銈掍娇鐢ㄣ仐銇︺亜銈嬨伄銇с丩inux鍥烘湁銇偝銉炪兂銉夈倰浣跨敤銇椼伨銇欍傘亾銈屻倝銇偝銉炪兂銉夈倰1銇ゃ仛銇ゅ疅琛屻仚銈嬪繀瑕併亴銇傘倞銇俱仚銆

sudo apt update
sudo apt install -y git zip unzip openjdk-13-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev

pip3 install --upgrade Cython==0.29.19 virtualenv 

# add the following line at the end of your ~/.bashrc file
export PATH=$PATH:~/.local/bin/

鐗瑰畾銇偝銉炪兂銉夈倰瀹熻銇椼仧寰屻併倰瀹熻銇buildozer init銇俱仚銆備互涓嬨伄銈广偗銉兗銉炽偡銉с儍銉堛伄銈堛亞銇嚭鍔涖亴琛ㄧず銇曘倢銇俱仚銆

Buildozer銇垵鏈熷寲銇屾垚鍔熴仐銇俱仐銇

涓婅銇偝銉炪兂銉夈伅Buildozer.spec銉曘偂銈ゃ儷銈掍綔鎴愩仐銇俱仚銆傘亾銇儠銈°偆銉倰浣跨敤銇椼仸銆併偄銉椼儶銇悕鍓嶃倓銈€偆銈炽兂銇仼銈掋偄銉椼儶銇寚瀹.spec銇с亶銇俱仚銆傘儠銈°偆銉伅娆°伄銈炽兗銉夈儢銉儍銈伄銈堛亞銇仾銈娿伨銇欍

[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

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

# (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 = 0.1

# (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

# (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 = 1.9.1

#
# Android specific
#

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

# (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

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

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

# (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 = False

# (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 = 2

# (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
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#


#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

銈€偆銈炽兂銆佽浠躲併儹銉笺儔鐢婚潰銇仼銈掓寚瀹氥仚銈嬪牬鍚堛伅銆併亾銇儠銈°偆銉倰绶ㄩ泦銇欍倠蹇呰銇屻亗銈娿伨銇欍傘偄銉椼儶銈便兗銈枫儳銉炽伀蹇呰銇仚銇广仸銇法闆嗐倰琛屻仯銇熷緦buildozer -v android debug銆併偄銉椼儶銉囥偅銉偗銉堛儶銇嬨倝瀹熻銇椼仸銆併偄銉椼儶銈便兗銈枫儳銉炽倰銉撱儷銉夈亰銈堛伋銈炽兂銉戙偆銉仐銇俱仚銆傜壒銇綆閫熴伄銉炪偡銉炽倰浣跨敤銇椼仸銇勩倠鍫村悎銇併亾銈屻伀鏅傞枔銇屻亱銇嬨倠銇撱仺銇屻亗銈娿伨銇欍

銉椼儹銈汇偣銇屽畬浜嗐仚銈嬨仺銆佺鏈伀銇勩亸銇ゃ亱銇儹銈般亴琛ㄧず銇曘倢銆併儞銉儔銇屾垚鍔熴仐銇熴亾銇ㄣ倰纰鸿獚銇с亶銇俱仚銆

Android銇垚鍔熴仐銇熴儞銉儔

銇俱仧銆乥in銉囥偅銉偗銉堛儶銇偄銉椼儶銇瓵PK銉愩兗銈搞儳銉炽亴蹇呰銇с仚銆傘亾銈屻伅銆佹惡甯浕瑭便伀銈ゃ兂銈广儓銉笺儷銇椼仸瀹熻銇欍倠銈€儣銉偙銉笺偡銉с兂銇疅琛屽彲鑳姐儠銈°偆銉仹銇欍

bin銉囥偅銉偗銉堛儶銇瓵ndroid.apk

绲愯珫

銇娿倎銇с仺銇嗭紒銇撱伄銉併儱銉笺儓銉偄銉倰銈广儐銉冦儣銉愩偆銈广儐銉冦儣銇у疅琛屻仐銇熷牬鍚堛伅銆侀浕瑭便伀鍗樼磾銇贡鏁般偢銈с儘銉兗銈裤兗銈€儣銉亴銈ゃ兂銈广儓銉笺儷銇曘倢銇︺亜銈嬨伅銇氥仹銇欍傘仢銈屻倰銇勩仒銇c仸銆併亜銇忋仱銇嬨伄鍊ゃ倰寰鏁淬仐銇︺亱銈夈佸啀妲嬬瘔銇椼仸銇忋仩銇曘亜銆傚啀妲嬬瘔銇疅琛屻伅銆佹渶鍒濄伄銉撱儷銉夈伝銇╂檪闁撱伅銇嬨亱銈娿伨銇涖倱銆

銇旇Η銇仺銇娿倞銆丳ython銈掍娇鐢ㄣ仐銇熴儮銉愩偆銉偄銉椼儶銈便兗銈枫儳銉炽伄妲嬬瘔銇佷娇鐢ㄣ仐銇︺亜銈嬨儠銉兗銉犮儻銉笺偗銇俱仧銇儮銈搞儱銉笺儷銇簿閫氥仐銇︺亜銈嬮檺銈娿銇嬨仾銈婄啊鍗銇с仚銆傘仺銇亱銇忋併儹銈搞儍銈伅鍚屻仒鏂规硶銇у疅琛屻仌銈屻伨銇欍

Kivy銉€偢銉ャ兗銉仺銇濄伄銈︺偅銈搞偋銉冦儓銇叄銈屻仸銇忋仩銇曘亜銆傘仚銇广仸銈掍竴搴︺伀鐭ャ倠銇撱仺銇仹銇嶃伨銇涖倱銆傘儣銉偢銈с偗銉堛倰瑕嬨仱銇戙仸銆併仹銇嶃倠銇犮亼鏃┿亸瓒炽倰婵°倝銇欍仩銇戙仹銇欍傘儚銉冦償銉笺偝銉笺儑銈c兂銈般

銉兂銈細https//blog.logrocket.com/build-android-application-kivy-python-framework/

#python 

Kaia  Schmitt

Kaia Schmitt

1659817260

SDK for Connecting to AWS IoT From A Device using Embedded C

AWS IoT Device SDK for Embedded C

Overview

The AWS IoT Device SDK for Embedded C (C-SDK) is a collection of C source files under the MIT open source license that can be used in embedded applications to securely connect IoT devices to AWS IoT Core. It contains MQTT client, HTTP client, JSON Parser, AWS IoT Device Shadow, AWS IoT Jobs, and AWS IoT Device Defender libraries. This SDK is distributed in source form, and can be built into customer firmware along with application code, other libraries and an operating system (OS) of your choice. These libraries are only dependent on standard C libraries, so they can be ported to various OS's - from embedded Real Time Operating Systems (RTOS) to Linux/Mac/Windows. You can find sample usage of C-SDK libraries on POSIX systems using OpenSSL (e.g. Linux demos in this repository), and on FreeRTOS using mbedTLS (e.g. FreeRTOS demos in FreeRTOS repository).

For the latest release of C-SDK, please see the section for Releases and Documentation.

C-SDK includes libraries that are part of the FreeRTOS 202012.01 LTS release. Learn more about the FreeRTOS 202012.01 LTS libraries by clicking here.

License

The C-SDK libraries are licensed under the MIT open source license.

Features

C-SDK simplifies access to various AWS IoT services. C-SDK has been tested to work with AWS IoT Core and an open source MQTT broker to ensure interoperability. The AWS IoT Device Shadow, AWS IoT Jobs, and AWS IoT Device Defender libraries are flexible to work with any MQTT client and JSON parser. The MQTT client and JSON parser libraries are offered as choices without being tightly coupled with the rest of the SDK. C-SDK contains the following libraries:

coreMQTT

The coreMQTT library provides the ability to establish an MQTT connection with a broker over a customer-implemented transport layer, which can either be a secure channel like a TLS session (mutually authenticated or server-only authentication) or a non-secure channel like a plaintext TCP connection. This MQTT connection can be used for performing publish operations to MQTT topics and subscribing to MQTT topics. The library provides a mechanism to register customer-defined callbacks for receiving incoming PUBLISH, acknowledgement and keep-alive response events from the broker. The library has been refactored for memory optimization and is compliant with the MQTT 3.1.1 standard. It has no dependencies on any additional libraries other than the standard C library, a customer-implemented network transport interface, and optionally a customer-implemented platform time function. The refactored design embraces different use-cases, ranging from resource-constrained platforms using only QoS 0 MQTT PUBLISH messages to resource-rich platforms using QoS 2 MQTT PUBLISH over TLS connections.

See memory requirements for the latest release here.

coreHTTP

The coreHTTP library provides the ability to establish an HTTP connection with a server over a customer-implemented transport layer, which can either be a secure channel like a TLS session (mutually authenticated or server-only authentication) or a non-secure channel like a plaintext TCP connection. The HTTP connection can be used to make "GET" (include range requests), "PUT", "POST" and "HEAD" requests. The library provides a mechanism to register a customer-defined callback for receiving parsed header fields in an HTTP response. The library has been refactored for memory optimization, and is a client implementation of a subset of the HTTP/1.1 standard.

See memory requirements for the latest release here.

coreJSON

The coreJSON library is a JSON parser that strictly enforces the ECMA-404 JSON standard. It provides a function to validate a JSON document, and a function to search for a key and return its value. A search can descend into nested structures using a compound query key. A JSON document validation also checks for illegal UTF8 encodings and illegal Unicode escape sequences.

See memory requirements for the latest release here.

corePKCS11

The corePKCS11 library is an implementation of the PKCS #11 interface (API) that makes it easier to develop applications that rely on cryptographic operations. Only a subset of the PKCS #11 v2.4 standard has been implemented, with a focus on operations involving asymmetric keys, random number generation, and hashing.

The Cryptoki or PKCS #11 standard defines a platform-independent API to manage and use cryptographic tokens. The name, "PKCS #11", is used interchangeably to refer to the API itself and the standard which defines it.

The PKCS #11 API is useful for writing software without taking a dependency on any particular implementation or hardware. By writing against the PKCS #11 standard interface, code can be used interchangeably with multiple algorithms, implementations and hardware.

Generally vendors for secure cryptoprocessors such as Trusted Platform Module (TPM), Hardware Security Module (HSM), Secure Element, or any other type of secure hardware enclave, distribute a PKCS #11 implementation with the hardware. The purpose of corePKCS11 mock is therefore to provide a PKCS #11 implementation that allows for rapid prototyping and development before switching to a cryptoprocessor specific PKCS #11 implementation in production devices.

Since the PKCS #11 interface is defined as part of the PKCS #11 specification replacing corePKCS11 with another implementation should require little porting effort, as the interface will not change. The system tests distributed in corePKCS11 repository can be leveraged to verify the behavior of a different implementation is similar to corePKCS11.

See memory requirements for the latest release here.

AWS IoT Device Shadow

The AWS IoT Device Shadow library enables you to store and retrieve the current state one or more shadows of every registered device. A device鈥檚 shadow is a persistent, virtual representation of your device that you can interact with from AWS IoT Core even if the device is offline. The device state is captured in its "shadow" is represented as a JSON document. The device can send commands over MQTT to get, update and delete its latest state as well as receive notifications over MQTT about changes in its state. The device鈥檚 shadow(s) are uniquely identified by the name of the corresponding "thing", a representation of a specific device or logical entity on the AWS Cloud. See Managing Devices with AWS IoT for more information on IoT "thing". This library supports named shadows, a feature of the AWS IoT Device Shadow service that allows you to create multiple shadows for a single IoT device. More details about AWS IoT Device Shadow can be found in AWS IoT documentation.

The AWS IoT Device Shadow library has no dependencies on additional libraries other than the standard C library. It also doesn鈥檛 have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any JSON library (see demos with coreMQTT and coreJSON).

See memory requirements for the latest release here.

AWS IoT Jobs

The AWS IoT Jobs library enables you to interact with the AWS IoT Jobs service which notifies one or more connected devices of a pending 鈥淛ob鈥. A Job can be used to manage your fleet of devices, update firmware and security certificates on your devices, or perform administrative tasks such as restarting devices and performing diagnostics. For documentation of the service, please see the AWS IoT Developer Guide. Interactions with the Jobs service use the MQTT protocol. This library provides an API to compose and recognize the MQTT topic strings used by the Jobs service.

The AWS IoT Jobs library has no dependencies on additional libraries other than the standard C library. It also doesn鈥檛 have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any JSON library (see demos with libmosquitto and coreJSON).

See memory requirements for the latest release here.

AWS IoT Device Defender

The AWS IoT Device Defender library enables you to interact with the AWS IoT Device Defender service to continuously monitor security metrics from devices for deviations from what you have defined as appropriate behavior for each device. If something doesn鈥檛 look right, AWS IoT Device Defender sends out an alert so you can take action to remediate the issue. More details about Device Defender can be found in AWS IoT Device Defender documentation. This library supports custom metrics, a feature that helps you monitor operational health metrics that are unique to your fleet or use case. For example, you can define a new metric to monitor the memory usage or CPU usage on your devices.

The AWS IoT Device Defender library has no dependencies on additional libraries other than the standard C library. It also doesn鈥檛 have any platform dependencies, such as threading or synchronization. It can be used with any MQTT library and any JSON library (see demos with coreMQTT and coreJSON).

See memory requirements for the latest release here.

AWS IoT Over-the-air Update

The AWS IoT Over-the-air Update (OTA) library enables you to manage the notification of a newly available update, download the update, and perform cryptographic verification of the firmware update. Using the OTA library, you can logically separate firmware updates from the application running on your devices. You can also use the library to send other files (e.g. images, certificates) to one or more devices registered with AWS IoT. More details about OTA library can be found in AWS IoT Over-the-air Update documentation.

The AWS IoT Over-the-air Update library has a dependency on coreJSON for parsing of JSON job document and tinyCBOR for decoding encoded data streams, other than the standard C library. It can be used with any MQTT library, HTTP library, and operating system (e.g. Linux, FreeRTOS) (see demos with coreMQTT and coreHTTP over Linux).

See memory requirements for the latest release here.

AWS IoT Fleet Provisioning

The AWS IoT Fleet Provisioning library enables you to interact with the AWS IoT Fleet Provisioning MQTT APIs in order to provison IoT devices without preexisting device certificates. With AWS IoT Fleet Provisioning, devices can securely receive unique device certificates from AWS IoT when they connect for the first time. For an overview of all provisioning options offered by AWS IoT, see device provisioning documentation. For details about Fleet Provisioning, refer to the AWS IoT Fleet Provisioning documentation.

See memory requirements for the latest release here.

AWS SigV4

The AWS SigV4 library enables you to sign HTTP requests with Signature Version 4 Signing Process. Signature Version 4 (SigV4) is the process to add authentication information to HTTP requests to AWS services. For security, most requests to AWS must be signed with an access key. The access key consists of an access key ID and secret access key.

See memory requirements for the latest release here.

backoffAlgorithm

The backoffAlgorithm library is a utility library to calculate backoff period using an exponential backoff with jitter algorithm for retrying network operations (like failed network connection with server). This library uses the "Full Jitter" strategy for the exponential backoff with jitter algorithm. More information about the algorithm can be seen in the Exponential Backoff and Jitter AWS blog.

Exponential backoff with jitter is typically used when retrying a failed connection or network request to the server. An exponential backoff with jitter helps to mitigate the failed network operations with servers, that are caused due to network congestion or high load on the server, by spreading out retry requests across multiple devices attempting network operations. Besides, in an environment with poor connectivity, a client can get disconnected at any time. A backoff strategy helps the client to conserve battery by not repeatedly attempting reconnections when they are unlikely to succeed.

The backoffAlgorithm library has no dependencies on libraries other than the standard C library.

See memory requirements for the latest release here.

Sending metrics to AWS IoT

When establishing a connection with AWS IoT, users can optionally report the Operating System, Hardware Platform and MQTT client version information of their device to AWS. This information can help AWS IoT provide faster issue resolution and technical support. If users want to report this information, they can send a specially formatted string (see below) in the username field of the MQTT CONNECT packet.

Format

The format of the username string with metrics is:

<Actual_Username>?SDK=<OS_Name>&Version=<OS_Version>&Platform=<Hardware_Platform>&MQTTLib=<MQTT_Library_name>@<MQTT_Library_version>

Where

  • is the actual username used for authentication, if username and password are used for authentication. When username and password based authentication is not used, this is an empty value.
  • is the Operating System the application is running on (e.g. Ubuntu)
  • is the version number of the Operating System (e.g. 20.10)
  • is the Hardware Platform the application is running on (e.g. RaspberryPi)
  • is the MQTT Client library being used (e.g. coreMQTT)
  • is the version of the MQTT Client library being used (e.g. 1.1.0)

Example

  • Actual_Username = 鈥渋otuser鈥, OS_Name = Ubuntu, OS_Version = 20.10, Hardware_Platform_Name = RaspberryPi, MQTT_Library_Name = coremqtt, MQTT_Library_version = 1.1.0. If username is not used, then 鈥渋otuser鈥 can be removed.
/* Username string:
 * iotuser?SDK=Ubuntu&Version=20.10&Platform=RaspberryPi&MQTTLib=coremqtt@1.1.0
 */

#define OS_NAME                   "Ubuntu"
#define OS_VERSION                "20.10"
#define HARDWARE_PLATFORM_NAME    "RaspberryPi"
#define MQTT_LIB                  "coremqtt@1.1.0"

#define USERNAME_STRING           "iotuser?SDK=" OS_NAME "&Version=" OS_VERSION "&Platform=" HARDWARE_PLATFORM_NAME "&MQTTLib=" MQTT_LIB
#define USERNAME_STRING_LENGTH    ( ( uint16_t ) ( sizeof( USERNAME_STRING ) - 1 ) )

MQTTConnectInfo_t connectInfo;
connectInfo.pUserName = USERNAME_STRING;
connectInfo.userNameLength = USERNAME_STRING_LENGTH;
mqttStatus = MQTT_Connect( pMqttContext, &connectInfo, NULL, CONNACK_RECV_TIMEOUT_MS, pSessionPresent );

Versioning

C-SDK releases will now follow a date based versioning scheme with the format YYYYMM.NN, where:

  • Y represents the year.
  • M represents the month.
  • N represents the release order within the designated month (00 being the first release).

For example, a second release in June 2021 would be 202106.01. Although the SDK releases have moved to date-based versioning, each library within the SDK will still retain semantic versioning. In semantic versioning, the version number itself (X.Y.Z) indicates whether the release is a major, minor, or point release. You can use the semantic version of a library to assess the scope and impact of a new release on your application.

Releases and Documentation

All of the released versions of the C-SDK libraries are available as git tags. For example, the last release of the v3 SDK version is available at tag 3.1.2.

202108.00

API documentation of 202108.00 release

This release introduces the refactored AWS IoT Fleet Provisioning library and the new AWS SigV4 library.

Additionally, this release brings minor version updates in the AWS IoT Over-the-Air Update and corePKCS11 libraries.

202103.00

API documentation of 202103.00 release

This release includes a major update to the APIs of the AWS IoT Over-the-air Update library.

Additionally, AWS IoT Device Shadow library introduces a minor update by adding support for named shadow, a feature of the AWS IoT Device Shadow service that allows you to create multiple shadows for a single IoT device. AWS IoT Jobs library introduces a minor update by introducing macros for $next job ID and compile-time generation of topic strings. AWS IoT Device Defender library introduces a minor update that adds macros to API for custom metrics feature of AWS IoT Device Defender service.

corePKCS11 also introduces a patch update by removing the pkcs11configPAL_DESTROY_SUPPORTED config and mbedTLS platform abstraction layer of DestroyObject. Lastly, no code changes are introduced for backoffAlgorithm, coreHTTP, coreMQTT, and coreJSON; however, patch updates are made to improve documentation and CI.

202012.01

API documentation of 202012.01 release

This release includes AWS IoT Over-the-air Update(Release Candidate), backoffAlgorithm, and PKCS #11 libraries. Additionally, there is a major update to the coreJSON and coreHTTP APIs. All libraries continue to undergo code quality checks (e.g. MISRA-C compliance), and Coverity static analysis. In addition, all libraries except AWS IoT Over-the-air Update and backoffAlgorithm undergo validation of memory safety with the C Bounded Model Checker (CBMC) automated reasoning tool.

202011.00

API documentation of 202011.00 release

This release includes refactored HTTP client, AWS IoT Device Defender, and AWS IoT Jobs libraries. Additionally, there is a major update to the coreJSON API. All libraries continue to undergo code quality checks (e.g. MISRA-C compliance), Coverity static analysis, and validation of memory safety with the C Bounded Model Checker (CBMC) automated reasoning tool.

202009.00

API documentation of 202009.00 release

This release includes refactored MQTT, JSON Parser, and AWS IoT Device Shadow libraries for optimized memory usage and modularity. These libraries are included in the SDK via Git submoduling. These libraries have gone through code quality checks including verification that no function has a GNU Complexity score over 8, and checks against deviations from mandatory rules in the MISRA coding standard. Deviations from the MISRA C:2012 guidelines are documented under MISRA Deviations. These libraries have also undergone both static code analysis from Coverity static analysis, and validation of memory safety and data structure invariance through the CBMC automated reasoning tool.

If you are upgrading from v3.x API of the C-SDK to the 202009.00 release, please refer to Migration guide from v3.1.2 to 202009.00 and newer releases. If you are using the C-SDK v4_beta_deprecated branch, note that we will continue to maintain this branch for critical bug fixes and security patches but will not add new features to it. See the C-SDK v4_beta_deprecated branch README for additional details.

v3.1.2

Details available here.

Porting Guide for 202009.00 and newer releases

All libraries depend on the ISO C90 standard library and additionally on the stdint.h library for fixed-width integers, including uint8_t, int8_t, uint16_t, uint32_t and int32_t, and constant macros like UINT16_MAX. If your platform does not support the stdint.h library, definitions of the mentioned fixed-width integer types will be required for porting any C-SDK library to your platform.

Porting coreMQTT

Guide for porting coreMQTT library to your platform is available here.

Porting coreHTTP

Guide for porting coreHTTP library is available here.

Porting AWS IoT Device Shadow

Guide for porting AWS IoT Device Shadow library is available here.

Porting AWS IoT Device Defender

Guide for porting AWS IoT Device Defender library is available here.

Porting AWS IoT Over-the-air Update

Guide for porting OTA library to your platform is available here.

Migration guide from v3.1.2 to 202009.00 and newer releases

MQTT Migration

Migration guide for MQTT library is available here.

Shadow Migration

Migration guide for Shadow library is available here.

Jobs Migration

Migration guide for Jobs library is available here.

Branches

main branch

The main branch hosts the continuous development of the AWS IoT Embedded C SDK (C-SDK) libraries. Please be aware that the development at the tip of the main branch is continuously in progress, and may have bugs. Consider using the tagged releases of the C-SDK for production ready software.

v4_beta_deprecated branch (formerly named v4_beta)

The v4_beta_deprecated branch contains a beta version of the C-SDK libraries, which is now deprecated. This branch was earlier named as v4_beta, and was renamed to v4_beta_deprecated. The libraries in this branch will not be released. However, critical bugs will be fixed and tested. No new features will be added to this branch.

Getting Started

Cloning

This repository uses Git Submodules to bring in the C-SDK libraries (eg, MQTT ) and third-party dependencies (eg, mbedtls for POSIX platform transport layer). Note: If you download the ZIP file provided by GitHub UI, you will not get the contents of the submodules (The ZIP file is also not a valid git repository). If you download from the 202012.00 Release Page page, you will get the entire repository (including the submodules) in the ZIP file, aws-iot-device-sdk-embedded-c-202012.00.zip. To clone the latest commit to main branch using HTTPS:

git clone --recurse-submodules https://github.com/aws/aws-iot-device-sdk-embedded-C.git

Using SSH:

git clone --recurse-submodules git@github.com:aws/aws-iot-device-sdk-embedded-C.git

If you have downloaded the repo without using the --recurse-submodules argument, you need to run:

git submodule update --init --recursive

When building with CMake, submodules are also recursively cloned automatically. However, -DBUILD_CLONE_SUBMODULES=0 can be passed as a CMake flag to disable this functionality. This is useful when you'd like to build CMake while using a different commit from a submodule.

Configuring Demos

The libraries in this SDK are not dependent on any operating system. However, the demos for the libraries in this SDK are built and tested on a Linux platform. The demos build with CMake, a cross-platform build tool.

Prerequisites

  • CMake 3.2.0 or any newer version for utilizing the build system of the repository.
  • C90 compiler such as gcc
    • Due to the use of mbedtls in corePKCS11, a C99 compiler is required if building the PKCS11 demos or the CMake install target.
  • Although not a part of the ISO C90 standard, stdint.h is required for fixed-width integer types that include uint8_t, int8_t, uint16_t, uint32_t and int32_t, and constant macros like UINT16_MAX, while stdbool.h is required for boolean parameters in coreMQTT. For compilers that do not provide these header files, coreMQTT provides the files stdint.readme and stdbool.readme, which can be renamed to stdint.h and stdbool.h, respectively, to provide the required type definitions.
  • A supported operating system. The ports provided with this repo are expected to work with all recent versions of the following operating systems, although we cannot guarantee the behavior on all systems.
    • Linux system with POSIX sockets, threads, RT, and timer APIs. (We have tested on Ubuntu 18.04).

Build Dependencies

The follow table shows libraries that need to be installed in your system to run certain demos. If a dependency is not installed and cannot be built from source, demos that require that dependency will be excluded from the default all target.

DependencyVersionUsage
OpenSSL1.1.0 or laterAll TLS demos and tests with the exception of PKCS11
Mosquitto Client1.4.10 or laterAWS IoT Jobs Mosquitto demo

AWS IoT Account Setup

You need to setup an AWS account and access the AWS IoT console for running the AWS IoT Device Shadow library, AWS IoT Device Defender library, AWS IoT Jobs library, AWS IoT OTA library and coreHTTP S3 download demos. Also, the AWS account can be used for running the MQTT mutual auth demo against AWS IoT broker. Note that running the AWS IoT Device Defender, AWS IoT Jobs and AWS IoT Device Shadow library demos require the setup of a Thing resource for the device running the demo. Follow the links to:

The MQTT Mutual Authentication and AWS IoT Shadow demos include example AWS IoT policy documents to run each respective demo with AWS IoT. You may use the MQTT Mutual auth and Shadow example policies by replacing [AWS_REGION] and [AWS_ACCOUNT_ID] with the strings of your region and account identifier. While the IoT Thing name and MQTT client identifier do not need to match for the demos to run, the example policies have the Thing name and client identifier identical as per AWS IoT best practices.

It can be very helpful to also have the AWS Command Line Interface tooling installed.

Configuring mutual authentication demos of MQTT and HTTP

You can pass the following configuration settings as command line options in order to run the mutual auth demos. Make sure to run the following command in the root directory of the C-SDK:

## optionally find your-aws-iot-endpoint from the command line
aws iot describe-endpoint --endpoint-type iot:Data-ATS
cmake -S . -Bbuild
-DAWS_IOT_ENDPOINT="<your-aws-iot-endpoint>" -DCLIENT_CERT_PATH="<your-client-certificate-path>" -DCLIENT_PRIVATE_KEY_PATH="<your-client-private-key-path>" 

In order to set these configurations manually, edit demo_config.h in demos/mqtt/mqtt_demo_mutual_auth/ and demos/http/http_demo_mutual_auth/ to #define the following:

  • Set AWS_IOT_ENDPOINT to your custom endpoint. This is found on the Settings page of the AWS IoT Console and has a format of ABCDEFG1234567.iot.<aws-region>.amazonaws.com where <aws-region> can be an AWS region like us-east-2.
    • Optionally, it can also be found with the AWS CLI command aws iot describe-endpoint --endpoint-type iot:Data-ATS.
  • Set CLIENT_CERT_PATH to the path of the client certificate downloaded when setting up the device certificate in AWS IoT Account Setup.
  • Set CLIENT_PRIVATE_KEY_PATH to the path of the private key downloaded when setting up the device certificate in AWS IoT Account Setup.

It is possible to configure ROOT_CA_CERT_PATH to any PEM-encoded Root CA Certificate. However, this is optional because CMake will download and set it to AmazonRootCA1.pem when unspecified.

Configuring AWS IoT Device Defender and AWS IoT Device Shadow demos

To build the AWS IoT Device Defender and AWS IoT Device Shadow demos, you can pass the following configuration settings as command line options. Make sure to run the following command in the root directory of the C-SDK:

cmake -S . -Bbuild -DAWS_IOT_ENDPOINT="<your-aws-iot-endpoint>" -DROOT_CA_CERT_PATH="<your-path-to-amazon-root-ca>" -DCLIENT_CERT_PATH="<your-client-certificate-path>" -DCLIENT_PRIVATE_KEY_PATH="<your-client-private-key-path>" -DTHING_NAME="<your-registered-thing-name>"

An Amazon Root CA certificate can be downloaded from here.

In order to set these configurations manually, edit demo_config.h in the demo folder to #define the following:

  • Set AWS_IOT_ENDPOINT to your custom endpoint. This is found on the Settings page of the AWS IoT Console and has a format of ABCDEFG1234567.iot.us-east-2.amazonaws.com.
  • Set ROOT_CA_CERT_PATH to the path of the root CA certificate downloaded when setting up the device certificate in AWS IoT Account Setup.
  • Set CLIENT_CERT_PATH to the path of the client certificate downloaded when setting up the device certificate in AWS IoT Account Setup.
  • Set CLIENT_PRIVATE_KEY_PATH to the path of the private key downloaded when setting up the device certificate in AWS IoT Account Setup.
  • Set THING_NAME to the name of the Thing created in AWS IoT Account Setup.

Configuring the AWS IoT Fleet Provisioning demo

To build the AWS IoT Fleet Provisioning Demo, you can pass the following configuration settings as command line options. Make sure to run the following command in the root directory of the C-SDK:

cmake -S . -Bbuild -DAWS_IOT_ENDPOINT="<your-aws-iot-endpoint>" -DROOT_CA_CERT_PATH="<your-path-to-amazon-root-ca>" -DCLAIM_CERT_PATH="<your-claim-certificate-path>" -DCLAIM_PRIVATE_KEY_PATH="<your-claim-private-key-path>" -DPROVISIONING_TEMPLATE_NAME="<your-template-name>" -DDEVICE_SERIAL_NUMBER="<your-serial-number>"

An Amazon Root CA certificate can be downloaded from here.

To create a provisioning template and claim credentials, sign into your AWS account and visit here. Make sure to enable the "Use the AWS IoT registry to manage your device fleet" option. Once you have created the template and credentials, modify the claim certificate's policy to match the sample policy.

In order to set these configurations manually, edit demo_config.h in the demo folder to #define the following:

  • Set AWS_IOT_ENDPOINT to your custom endpoint. This is found on the Settings page of the AWS IoT Console and has a format of ABCDEFG1234567.iot.us-east-2.amazonaws.com.
  • Set ROOT_CA_CERT_PATH to the path of the root CA certificate downloaded when setting up the device certificate in AWS IoT Account Setup.
  • Set CLAIM_CERT_PATH to the path of the claim certificate downloaded when setting up the template and claim credentials.
  • Set CLAIM_PRIVATE_KEY_PATH to the path of the private key downloaded when setting up the template and claim credentials.
  • Set PROVISIONING_TEMPLATE_NAME to the name of the provisioning template created.
  • Set DEVICE_SERIAL_NUMBER to an arbitrary string representing a device identifier.

Configuring the S3 demos

You can pass the following configuration settings as command line options in order to run the S3 demos. Make sure to run the following command in the root directory of the C-SDK:

cmake -S . -Bbuild -DS3_PRESIGNED_GET_URL="s3-get-url" -DS3_PRESIGNED_PUT_URL="s3-put-url"

S3_PRESIGNED_PUT_URL is only needed for the S3 upload demo.

In order to set these configurations manually, edit demo_config.h in demos/http/http_demo_s3_download_multithreaded, and demos/http/http_demo_s3_upload to #define the following:

  • Set S3_PRESIGNED_GET_URL to a S3 presigned URL with GET access.
  • Set S3_PRESIGNED_PUT_URL to a S3 presigned URL with PUT access.

You can generate the presigned urls using demos/http/common/src/presigned_urls_gen.py. More info can be found here.

Configure S3 Download HTTP Demo using SigV4 Library:

Refer this demos/http/http_demo_s3_download/README.md to follow the steps needed to configure and run the S3 Download HTTP Demo using SigV4 Library that generates the authorization HTTP header needed to authenticate the HTTP requests send to S3.

Setup for AWS IoT Jobs demo

  1. The demo requires the Linux platform to contain curl and libmosquitto. On a Debian platform, these dependencies can be installed with:
    apt install curl libmosquitto-dev

If the platform does not contain the libmosquitto library, the demo will build the library from source.

libmosquitto 1.4.10 or any later version of the first major release is required to run this demo.

  1. A job that specifies the URL to download for the demo needs to be created on the AWS account for the Thing resource that will be used by the demo.
    The job can be created directly from the AWS IoT console or using the aws cli tool.

The following creates a job that specifies a Linux Kernel link for downloading.

 aws iot create-job \
        --job-id 'job_1' \
        --targets arn:aws:iot:us-west-2:<account-id>:thing/<thing-name> \
        --document '{"url":"https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.8.5.tar.xz"}'

Prerequisites for the AWS Over-The-Air Update (OTA) demos

  1. To perform a successful OTA update, you need to complete the prerequisites mentioned here.
  2. A code signing certificate is required to authenticate the update. A code signing certificate based on the SHA-256 ECDSA algorithm will work with the current demos. An example of how to generate this kind of certificate can be found here.

Scheduling an OTA Update Job

After you build and run the initial executable you will have to create another executable and schedule an OTA update job with this image.

  1. Increase the version of the application by setting macro APP_VERSION_BUILD in demos/ota/ota_demo_core_[mqtt/http]/demo_config.h to a different version than what is running.
  2. Rebuild the application using the build steps below into a different directory, say build-dir-2.
  3. Rename the demo executable to reflect the change, e.g. mv ota_demo_core_mqtt ota_demo_core_mqtt2
  4. Create an OTA job:
    1. Go to the AWS IoT Core console.
    2. Manage 鈫 Jobs 鈫 Create 鈫 Create a FreeRTOS OTA update job 鈫 Select the corresponding name for your device from the thing list.
    3. Sign a new firmware 鈫 Create a new profile 鈫 Select any SHA-ECDSA signing platform 鈫 Upload the code signing certificate(from prerequisites) and provide its path on the device.
    4. Select the image 鈫 Select the bucket you created during the prerequisite steps 鈫 Upload the binary build-dir-2/bin/ota_demo2.
    5. The path on device should be the absolute path to place the executable and the binary name: e.g. /home/ubuntu/aws-iot-device-sdk-embedded-C-staging/build-dir/bin/ota_demo_core_mqtt2.
    6. Select the IAM role created during the prerequisite steps.
    7. Create the Job.
  5. Run the initial executable again with the following command: sudo ./ota_demo_core_mqtt or sudo ./ota_demo_core_http.
  6. After the initial executable has finished running, go to the directory where the downloaded firmware image resides which is the path name used when creating an OTA job.
  7. Change the permissions of the downloaded firmware to make it executable, as it may be downloaded with read (user default) permissions only: chmod 775 ota_demo_core_mqtt2
  8. Run the downloaded firmware image with the following command: sudo ./ota_demo_core_mqtt2

Building and Running Demos

Before building the demos, ensure you have installed the prerequisite software. On Ubuntu 18.04 and 20.04, gcc, cmake, and OpenSSL can be installed with:

sudo apt install build-essential cmake libssl-dev

Build a single demo

  • Go to the root directory of the C-SDK.
  • Run cmake to generate the Makefiles: cmake -S . -Bbuild && cd build
  • Choose a demo from the list below or alternatively, run make help | grep demo:
defender_demo
http_demo_basic_tls
http_demo_mutual_auth
http_demo_plaintext
http_demo_s3_download
http_demo_s3_download_multithreaded
http_demo_s3_upload
jobs_demo_mosquitto
mqtt_demo_basic_tls
mqtt_demo_mutual_auth
mqtt_demo_plaintext
mqtt_demo_serializer
mqtt_demo_subscription_manager
ota_demo_core_http
ota_demo_core_mqtt
pkcs11_demo_management_and_rng
pkcs11_demo_mechanisms_and_digests
pkcs11_demo_objects
pkcs11_demo_sign_and_verify
shadow_demo_main
  • Replace demo_name with your desired demo then build it: make demo_name
  • Go to the build/bin directory and run any demo executables from there.

Build all configured demos

  • Go to the root directory of the C-SDK.
  • Run cmake to generate the Makefiles: cmake -S . -Bbuild && cd build
  • Run this command to build all configured demos: make
  • Go to the build/bin directory and run any demo executables from there.

Running corePKCS11 demos

The corePKCS11 demos do not require any AWS IoT resources setup, and are standalone. The demos build upon each other to introduce concepts in PKCS #11 sequentially. Below is the recommended order.

  1. pkcs11_demo_management_and_rng
  2. pkcs11_demo_mechanisms_and_digests
  3. pkcs11_demo_objects
  4. pkcs11_demo_sign_and_verify
    1. Please note that this demo requires the private and public key generated from pkcs11_demo_objects to be in the directory the demo is executed from.

Alternative option of Docker containers for running demos locally

Install Docker:

curl -fsSL https://get.docker.com -o get-docker.sh

sh get-docker.sh

Installing Mosquitto to run MQTT demos locally

The following instructions have been tested on an Ubuntu 18.04 environment with Docker and OpenSSL installed.

Download the official Docker image for Mosquitto 1.6.14. This version is deliberately chosen so that the Docker container can load certificates from the host system. Any version after 1.6.14 will drop privileges as soon as the configuration file has been read (before TLS certificates are loaded).

docker pull eclipse-mosquitto:1.6.14

If a Mosquitto broker with TLS communication needs to be run, ignore this step and proceed to the next step. A Mosquitto broker with plain text communication can be run by executing the command below.

docker run -it -p 1883:1883 --name mosquitto-plain-text eclipse-mosquitto:1.6.14

Set BROKER_ENDPOINT defined in demos/mqtt/mqtt_demo_plaintext/demo_config.h to localhost.

Ignore the remaining steps unless a Mosquitto broker with TLS communication also needs to be run.

For TLS communication with Mosquitto broker, server and CA credentials need to be created. Use OpenSSL commands to generate the credentials for the Mosquitto server.

# Generate CA key and certificate. Provide the Subject field information as appropriate for CA certificate.
openssl req -x509 -nodes -sha256 -days 365 -newkey rsa:2048 -keyout ca.key -out ca.crt
# Generate server key and certificate.# Provide the Subject field information as appropriate for Server certificate. Make sure the Common Name (CN) field is different from the root CA certificate.
openssl req -nodes -sha256 -new -keyout server.key -out server.csr # Sign with the CA cert.
openssl x509 -req -sha256 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365

Note: Make sure to use different Common Name (CN) detail between the CA and server certificates; otherwise, SSL handshake fails with exactly same Common Name (CN) detail in both the certificates.

port 8883

cafile /mosquitto/config/ca.crt
certfile /mosquitto/config/server.crt
keyfile /mosquitto/config/server.key

# Use this option for TLS mutual authentication (where client will provide CA signed certificate)
#require_certificate true
tls_version tlsv1.2
#use_identity_as_username true

Create a mosquitto.conf file to use port 8883 (for TLS communication) and providing path to the generated credentials.

Run the docker container from the local directory containing the generated credential and mosquitto.conf files.

docker run -it -p 8883:8883 -v $(pwd):/mosquitto/config/ --name mosquitto-basic-tls eclipse-mosquitto:1.6.14

Update demos/mqtt/mqtt_demo_basic_tls/demo_config.h to the following:
Set BROKER_ENDPOINT to localhost.
Set ROOT_CA_CERT_PATH to the absolute path of the CA certificate created in step 4. for the local Mosquitto server.

Installing httpbin to run HTTP demos locally

Run httpbin through port 80:

docker pull kennethreitz/httpbin
docker run -p 80:80 kennethreitz/httpbin

SERVER_HOST defined in demos/http/http_demo_plaintext/demo_config.h can now be set to localhost.

To run http_demo_basic_tls, download ngrok in order to create an HTTPS tunnel to the httpbin server currently hosted on port 80:

./ngrok http 80 # May have to use ./ngrok.exe depending on OS or filename of the executable

ngrok will provide an https link that can be substituted in demos/http/http_demo_basic_tls/demo_config.h and has a format of https://ABCDEFG12345.ngrok.io.

Set SERVER_HOST in demos/http/http_demo_basic_tls/demo_config.h to the https link provided by ngrok, without https:// preceding it.

You must also download the Root CA certificate provided by the ngrok https link and set ROOT_CA_CERT_PATH in demos/http/http_demo_basic_tls/demo_config.h to the file path of the downloaded certificate.

Installation

The C-SDK libraries and platform abstractions can be installed to a file system through CMake. To do so, run the following command in the root directory of the C-SDK. Note that installation is not required to run any of the demos.

cmake -S . -Bbuild -DBUILD_DEMOS=0 -DBUILD_TESTS=0
cd build
sudo make install

Note that because make install will automatically build the all target, it may be useful to disable building demos and tests with -DBUILD_DEMOS=0 -DBUILD_TESTS=0 unless they have already been configured. Super-user permissions may be needed if installing to a system include or system library path.

To install only a subset of all libraries, pass -DINSTALL_LIBS to install only the libraries you need. By default, all libraries will be installed, but you may exclude any library that you don't need from this list:

-DINSTALL_LIBS="DEFENDER;SHADOW;JOBS;OTA;OTA_HTTP;OTA_MQTT;BACKOFF_ALGORITHM;HTTP;JSON;MQTT;PKCS"

By default, the install path will be in the project directory of the SDK. You can also set -DINSTALL_TO_SYSTEM=1 to install to the system path for headers and libraries in your OS (e.g. /usr/local/include & /usr/local/lib for Linux).

Upon entering make install, the location of each library will be specified first followed by the location of all installed headers:

-- Installing: /usr/local/lib/libaws_iot_defender.so
-- Installing: /usr/local/lib/libaws_iot_shadow.so
...
-- Installing: /usr/local/include/aws/defender.h
-- Installing: /usr/local/include/aws/defender_config_defaults.h
-- Installing: /usr/local/include/aws/shadow.h
-- Installing: /usr/local/include/aws/shadow_config_defaults.h

You may also set an installation path of your choice by passing the following flags through CMake. Make sure to run the following command in the root directory of the C-SDK:

cmake -S . -Bbuild -DBUILD_DEMOS=0 -DBUILD_TESTS=0 \
-DCSDK_HEADER_INSTALL_PATH="/header/path" -DCSDK_LIB_INSTALL_PATH="/lib/path"
cd build
sudo make install

POSIX platform abstractions are used together with the C-SDK libraries in the demos. By default, these abstractions are also installed but can be excluded by passing the flag: -DINSTALL_PLATFORM_ABSTRACTIONS=0.

Lastly, a custom config path for any specific library can also be specified through the following CMake flags, allowing libraries to be compiled with a config of your choice:

-DDEFENDER_CUSTOM_CONFIG_DIR="defender-config-directory"
-DSHADOW_CUSTOM_CONFIG_DIR="shadow-config-directory"
-DJOBS_CUSTOM_CONFIG_DIR="jobs-config-directory"
-DOTA_CUSTOM_CONFIG_DIR="ota-config-directory"
-DHTTP_CUSTOM_CONFIG_DIR="http-config-directory"
-DJSON_CUSTOM_CONFIG_DIR="json-config-directory"
-DMQTT_CUSTOM_CONFIG_DIR="mqtt-config-directory"
-DPKCS_CUSTOM_CONFIG_DIR="pkcs-config-directory"

Note that the file name of the header should not be included in the directory.

Generating Documentation

Note: For pre-generated documentation, please visit Releases and Documentation section.

The Doxygen references were created using Doxygen version 1.9.2. To generate the Doxygen pages, use the provided Python script at tools/doxygen/generate_docs.py. Please ensure that each of the library submodules under libraries/standard/ and libraries/aws/ are cloned before using this script.

cd <CSDK_ROOT>
git submodule update --init --recursive --checkout
python3 tools/doxygen/generate_docs.py

The generated documentation landing page is located at docs/doxygen/output/html/index.html.


Author: aws
Source code: https://github.com/aws/aws-iot-device-sdk-embedded-C
License: MIT license

#aws 

Autumn  Blick

Autumn Blick

1593867420

Top Android Projects with Source Code

Android Projects with Source Code 鈥 Your entry pass into the world of Android

Hello Everyone, welcome to this article, which is going to be really important to all those who鈥檙e in dilemma for their projects and the project submissions. This article is also going to help you if you鈥檙e an enthusiast looking forward to explore and enhance your Android skills. The reason is that we鈥檙e here to provide you the best ideas of Android Project with source code that you can choose as per your choice.

These project ideas are simple suggestions to help you deal with the difficulty of choosing the correct projects. In this article, we鈥檒l see the project ideas from beginners level and later we鈥檒l move on to intermediate to advance.

top android projects with source code

Android Projects with Source Code

Before working on real-time projects, it is recommended to create a sample hello world project in android studio and get a flavor of project creation as well as execution: Create your first android project

Android Projects for beginners

1. Calculator

build a simple calculator app in android studio source code

Android Project: A calculator will be an easy application if you have just learned Android and coding for Java. This Application will simply take the input values and the operation to be performed from the users. After taking the input it鈥檒l return the results to them on the screen. This is a really easy application and doesn鈥檛 need use of any particular package.

To make a calculator you鈥檇 need Android IDE, Kotlin/Java for coding, and for layout of your application, you鈥檇 need XML or JSON. For this, coding would be the same as that in any language, but in the form of an application. Not to forget creating a calculator initially will increase your logical thinking.

Once the user installs the calculator, they鈥檙e ready to use it even without the internet. They鈥檒l enter the values, and the application will show them the value after performing the given operations on the entered operands.

Source Code: Simple Calculator Project

2. A Reminder App

Android Project: This is a good project for beginners. A Reminder App can help you set reminders for different events that you have throughout the day. It鈥檒l help you stay updated with all your tasks for the day. It can be useful for all those who are not so good at organizing their plans and forget easily. This would be a simple application just whose task would be just to remind you of something at a particular time.

To make a Reminder App you need to code in Kotlin/Java and design the layout using XML or JSON. For the functionality of the app, you鈥檇 need to make use of AlarmManager Class and Notifications in Android.

In this, the user would be able to set reminders and time in the application. Users can schedule reminders that would remind them to drink water again and again throughout the day. Or to remind them of their medications.

3. Quiz Application

Android Project: Another beginner鈥檚 level project Idea can be a Quiz Application in android. Here you can provide the users with Quiz on various general knowledge topics. These practices will ensure that you鈥檙e able to set the layouts properly and slowly increase your pace of learning the Android application development. In this you鈥檒l learn to use various Layout components at the same time understanding them better.

To make a quiz application you鈥檒l need to code in Java and set layouts using xml or java whichever you prefer. You can also use JSON for the layouts whichever preferable.

In the app, questions would be asked and answers would be shown as multiple choices. The user selects the answer and gets shown on the screen if the answers are correct. In the end the final marks would be shown to the users.

4. Simple Tic-Tac-Toe

android project tic tac toe game app

Android Project: Tic-Tac-Toe is a nice game, I guess most of you all are well aware of it. This will be a game for two players. In this android game, users would be putting X and O in the given 9 parts of a box one by one. The first player to arrange X or O in an adjacent line of three wins.

To build this game, you鈥檇 need Java and XML for Android Studio. And simply apply the logic on that. This game will have a set of three matches. So, it鈥檒l also have a scoreboard. This scoreboard will show the final result at the end of one complete set.

Upon entering the game they鈥檒l enter their names. And that鈥檚 when the game begins. They鈥檒l touch one of the empty boxes present there and get their turn one by one. At the end of the game, there would be a winner declared.

Source Code: Tic Tac Toe Game Project

5. Stopwatch

Android Project: A stopwatch is another simple android project idea that will work the same as a normal handheld timepiece that measures the time elapsed between its activation and deactivation. This application will have three buttons that are: start, stop, and hold.

This application would need to use Java and XML. For this application, we need to set the timer properly as it is initially set to milliseconds, and that should be converted to minutes and then hours properly. The users can use this application and all they鈥檇 need to do is, start the stopwatch and then stop it when they are done. They can also pause the timer and continue it again when they like.

6. To Do App

Android Project: This is another very simple project idea for you as a beginner. This application as the name suggests will be a To-Do list holding app. It鈥檒l store the users schedules and their upcoming meetings or events. In this application, users will be enabled to write their important notes as well. To make it safe, provide a login page before the user can access it.

So, this app will have a login page, sign-up page, logout system, and the area to write their tasks, events, or important notes. You can build it in android studio using Java and XML at ease. Using XML you can build the user interface as user-friendly as you can. And to store the users鈥 data, you can use SQLite enabling the users to even delete the data permanently.

Now for users, they will sign up and get access to the write section. Here the users can note down the things and store them permanently. Users can also alter the data or delete them. Finally, they can logout and also, login again and again whenever they like.

7. Roman to decimal converter

Android Project: This app is aimed at the conversion of Roman numbers to their significant decimal number. It鈥檒l help to check the meaning of the roman numbers. Moreover, it will be easy to develop and will help you get your hands on coding and Android.

You need to use Android Studio, Java for coding and XML for interface. The application will take input from the users and convert them to decimal. Once it converts the Roman no. into decimal, it will show the results on the screen.

The users are supposed to just enter the Roman Number and they鈥檒l get the decimal values on the screen. This can be a good android project for final year students.

8. Virtual Dice Roller

Android Project: Well, coming to this part that is Virtual Dice or a random no. generator. It is another simple but interesting app for computer science students. The only task that it would need to do would be to generate a number randomly. This can help people who鈥檙e often confused between two or more things.

Using a simple random number generator you can actually create something as good as this. All you鈥檇 need to do is get you hands-on OnClick listeners. And a good layout would be cherry on the cake.

The user鈥檚 task would be to set the range of the numbers and then click on the roll button. And the app will show them a randomly generated number. Isn鈥檛 it interesting ? Try soon!

9. A Scientific Calculator App

Android Project: This application is very important for you as a beginner as it will let you use your logical thinking and improve your programming skills. This is a scientific calculator that will help the users to do various calculations at ease.

To make this application you鈥檇 need to use Android Studio. Here you鈥檇 need to use arithmetic logics for the calculations. The user would need to give input to the application that will be in terms of numbers. After that, the user will give the operator as an input. Then the Application will calculate and generate the result on the user screen.

10. SMS App

Android Project: An SMS app is another easy but effective idea. It will let you send the SMS to various no. just in the same way as you use the default messaging application in your phone. This project will help you with better understanding of SMSManager in Android.

For this application, you would need to implement Java class SMSManager in Android. For the Layout you can use XML or JSON. Implementing SMSManager into the app is an easy task, so you would love this.

The user would be provided with the facility to text to whichever number they wish also, they鈥檇 be able to choose the numbers from the contact list. Another thing would be the Textbox, where they鈥檒l enter their message. Once the message is entered they can happily click on the send button.

#android tutorials #android application final year project #android mini projects #android project for beginners #android project ideas #android project ideas for beginners #android projects #android projects for students #android projects with source code #android topics list #intermediate android projects #real-time android projects