BeeWare Python Android

BeeWare là bộ công cụ và thư viện cho phép bạn viết các ứng dụng giao diện người dùng gốc bằng Python và với một cơ sở mã, phát hành nó trên nhiều nền tảng như iOS, Android, Windows, MacOS, Linux, Web và tvOS

Các ứng dụng Java là "Viết một lần, chạy mọi nơi".
Các ứng dụng BeeWare là "Viết một lần, triển khai mọi nơi".

Vì tôi không có kinh nghiệm tạo ứng dụng di động cho iOS hoặc Android, hãy tìm hiểu xem tôi có thể tạo ứng dụng di động Android nhanh như thế nào với BeeWare

Trong hướng dẫn này, chúng ta sẽ xây dựng một ứng dụng thời tiết đơn giản. Và trước khi bắt đầu, hãy cài đặt tất cả các phụ thuộc cần thiết

Ghi chú. Tôi sử dụng bản phân phối Linux dựa trên Ubuntu (Ubuntu 18. 04) vì vậy hướng dẫn của tôi sẽ được nhắm mục tiêu

  • Cài đặt Python
  • Chạy cái này trong thiết bị đầu cuối của bạn để cài đặt các phụ thuộc

$ sudo apt-get update
$ sudo apt-get install git python3-dev python3-venv libgirepository1.0-dev libcairo2-dev libpango1.0-dev libwebkit2gtk-4.0-37 gir1.2-webkit2-4.0

  • Tạo và kích hoạt một môi trường ảo

$ mkdir weatherman
$ cd weatherman
$ python3 -m virtualenv .venv
$source .venv/bin/activate

  • Cài đặt cặp. Trong môi trường ảo được kích hoạt của bạn, hãy chạy cái này trong terminal

$ pip install briefcase

  • Cài đặt httpx

pip install httpx

Tạo ứng dụng khung bằng Briefcase
Vẫn trong thiết bị đầu cuối của bạn, hãy chạy lệnh bên dưới.

$ briefcase new

Briefcase sẽ hỏi bạn một loạt câu hỏi và sử dụng những câu trả lời đó để thiết lập ứng dụng của bạn

Let's build a new Briefcase app!


First, we need a formal name for your application. This is the name that will
be displayed to humans whenever the name of the application is displayed. It
can have spaces and punctuation if you like, and any capitalization will be
used as you type it.

Formal Name [Hello World]: weatherman 

Next, we need a name that can serve as a machine-readable Python package name
for your application. This name must be PEP508-compliant - that means the name
may only contain letters, numbers, hyphens, and underscores; it can't contain
spaces or punctuation, and it can't start with a hyphen or underscore.

Based on your formal name, we suggest an app name of 'weatherman',
but you can use another name if you want.

App Name [weatherman]: weatherman

Now we need a bundle identifier for your application. App stores need to
protect against having multiple applications with the same name; the bundle
identifier is the namespace they use to identify applications that come from
you. The bundle identifier is usually the domain name of your company or
project, in reverse order.

For example, if you are writing an application for Example Corp, whose website
is example.com, your bundle would be ``com.example``. The bundle will be
combined with your application's machine readable name to form a complete
application identifier (e.g., com.example.notepad).

Bundle Identifier [com.example]: com.exampe.notepad

Briefcase can manage projects that contain multiple applications, so we need a
Project name. If you're only planning to have one application in this
project, you can use the formal name as the project name.

Project Name [weatherman]: weatherman

Now, we need a one line description for your application.

Description [My first application]: A Simple Android weather app.

Who do you want to be credited as the author of this application? This could be
your own name, or the name of your company you work for.

Author [Jane Developer]: Pystar

What email address should people use to contact the developers of this
application? This might be your own email address, or a generic contact address
you set up specifically for this application.

Author's Email [[email protected]]: [email protected]

What is the website URL for this application? If you don't have a website set
up yet, you can put in a dummy URL.

Application URL [https://weatherman.exampe.com/weatherman]:      

What license do you want to use for this project's code?

Select one of the following:

    [1] BSD license
    [2] MIT license
    [3] Apache Software License
    [4] GNU General Public License v2 (GPLv2)
    [5] GNU General Public License v2 or later (GPLv2+)
    [6] GNU General Public License v3 (GPLv3)
    [7] GNU General Public License v3 or later (GPLv3+)
    [8] Proprietary
    [9] Other

Project License [1]: 2

What GUI toolkit do you want to use for this project?

Select one of the following:

    [1] Toga
    [2] PySide2
    [3] PursuedPyBear
    [4] None

GUI Framework [1]: 1

Generating a new application 'weatherman'

Ứng dụng 'người thời tiết' đã được tạo. Để chạy ứng dụng của bạn, hãy nhập thiết bị đầu cuối của bạn

$ cd weatherman
$ briefcase dev

Ghi chú. giao diện của ứng dụng của bạn được xác định bởi trình quản lý cửa sổ của bạn

Ứng dụng sẽ mở ra trong một cửa sổ mới và trên hệ thống Linux + i3wm của tôi, ứng dụng trông như thế này

BeeWare Python Android

Ứng dụng hiện tại hầu như không có gì, vì vậy hãy thêm một số logic vào nó, tuy nhiên trước khi bắt đầu, chúng ta cần hiểu cách thức hoạt động của hệ thống BeeWare Widget

Ứng dụng BeeWare là một toga. Phiên bản ứng dụng và là tập hợp các hộp và tiện ích. Một hộp có thể chứa các hộp và vật dụng lồng nhau khác.
Tiện ích con tương tự như tiện ích con html và các ví dụ về tiện ích con BeeWare bao gồm.

  1. nút
  2. nhãn
  3. Nhập văn bản
  4. PasswordInput (Xem thêm)[https. // toga. đọcthedocs. io/vi/mới nhất/tham chiếu/api/widget/chỉ mục. html]

Bạn áp dụng kiểu dáng cho các hộp để xác định ứng dụng sẽ trông như thế nào. Một hộp có thể là một CỘT i. e. nó chiếm toàn bộ khung nhìn từ trên xuống dưới và mở rộng chiều cao của nó dựa trên nội dung của nó, nó cũng có thể là ROW để mở rộng khung nhìn theo chiều ngang từ trái sang phải

Hãy thêm một số logic vào ứng dụng bộ xương để làm cho nó hoạt động hữu ích. Bạn sẽ phải tạo một tài khoản trên Weatherstack và nhận TOKEN, ứng dụng của bạn sẽ cần nó để thực hiện lệnh gọi HTTP đến API thời tiết

"""
A simple weather app.
"""
from pprint import pprint
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW, LEFT, RIGHT
import httpx

TOKEN = "" #Enter your weatherstack.com token here.

BASE_URL="http://api.weatherstack.com/current"

class weatherman(toga.App):

    def startup(self):
        """
        Construct and show the Toga application.

        Usually, you would add your application to a main content box.
        We then create a main window (with a name matching the app), and
        show the main window.
        """
        main_box = toga.Box(style=Pack(direction=COLUMN))

        location_label = toga.Label("Location", style=Pack(padding=(0, 5)))
        self.location_input = toga.TextInput(style=Pack(flex=1))

        location_box = toga.Box(style=Pack(direction=ROW, padding=5))
        location_box.add(location_label)
        location_box.add(self.location_input)

        weather_box_label = toga.Label("Weather Results", style=Pack(padding=(0, 5)))
        self.weather_box_input = toga.TextInput(readonly=True, style=Pack(flex=1))
        weather_box = toga.Box(style=Pack(direction=ROW, padding=5))
        weather_box.add(weather_box_label)
        weather_box.add(self.weather_box_input)

        button = toga.Button("Fetch weather", on_press=self.weather, style=Pack(padding=5))

        main_box.add(location_box)
        main_box.add(button)
        main_box.add(weather_box)

        self.main_window = toga.MainWindow(title=self.formal_name)
        self.main_window.content = main_box
        self.main_window.show()

    def weather(self, widget):
        params = dict(access_key=TOKEN, query=self.location_input.value)
        resp = httpx.get(BASE_URL, params=params).json()
        try:
            self.weather_box_input.value = f'The weather report for  {resp["request"]["query"]} \
            {resp["current"]["temperature"]}  \
            {resp["current"]["weather_descriptions"][0]} \
            {resp["current"]["feelslike"]}'
        except ValueError:
            self.weather_box_input.value = "Location unknown!"



def main():
    return weatherman()

Bây giờ, hãy đóng gói ứng dụng mà chúng ta vừa tạo để phân phối. Trong shell kích hoạt của bạn chạy

________số 8

Để ứng dụng của bạn có thể thực thi được trên nền tảng được nhắm mục tiêu của bạn (trong trường hợp của chúng tôi là Android), nó cần được biên dịch

briefcase build

Để tìm hiểu xem quá trình biên dịch của chúng tôi có thành công hay không, bạn có thể chạy nó với

$ mkdir weatherman
$ cd weatherman
$ python3 -m virtualenv .venv
$source .venv/bin/activate
0

Điều này chạy ứng dụng đã biên dịch chứ không phải mã python mà chúng tôi đang làm việc với. Nếu ứng dụng của bạn thực thi thành công thì điều đó có nghĩa là bước biên dịch trước đó đã thành công

Làm cách nào để sử dụng BeeWare trong Android?

Đầu tiên, chạy lệnh tạo . Điều này tải xuống một mẫu ứng dụng Android và thêm mã Python của bạn vào đó. (beeware-venv) $ briefcase tạo android [helloworld] Tạo mẫu ứng dụng. Sử dụng mẫu ứng dụng. https. //github. com/beeware/briefcase-android-gradle-template. git.

Làm cách nào để cài đặt BeeWare trên Android?

Mẫu BeeWare Android .
Tạo một virtualenv bằng Python 3 (3. 5 khuyến nghị)
Cài đặt cookiecutter. .
Thêm mã của bạn vào dự án
Cài đặt vali. .
Khởi động trình giả lập Android hoặc kết nối thiết bị Android của bạn
Xây dựng và chạy ứng dụng của bạn với. thiết lập $ trăn. py android --start

Kivy hay BeeWare cái nào tốt hơn?

BeeWare và Kivy là hai khung phát triển ứng dụng di động Python tốt nhất . Cả hai khung đều có khung GUI được chấp nhận. Tuy nhiên, sự khác biệt thực sự xuất hiện trong giao diện của sản phẩm cuối cùng. Kivy là một framework trưởng thành, trong khi BeeWare còn non trẻ và vẫn đang trong giai đoạn phát triển.

Làm cách nào để sử dụng BeeWare Python?

Điều kiện tiên quyết .
Python được cài đặt trong máy của bạn
Cài đặt beeware và toga. Chạy pip3 install beeware và pip3 install toga để cài đặt chúng tương ứng
Kiến thức Python cơ bản
Một kết nối internet tốt