java跨平台跨平台_如何用Java制作跨平台移动应用

桓智敏
2023-12-01

java跨平台跨平台

by Adrian D. Finlay

通过阿德里安·芬莱

如何用Java制作跨平台移动应用 (How to make a Cross-Platform Mobile App in Java)

Did you know that you can use Java to make cross platform mobile apps? Yes, pinch yourself, you read that right the first time! I’ll teach you the basics of how to use your existing Java knowledge to create performant apps on Android and iOS in 12 easy steps. We will do this all using JavaFX as the GUI toolkit.

您是否知道可以使用Java来制作跨平台的移动应用程序? 是的,捏自己,您第一次读对了! 我将通过12个简单的步骤,教给您有关如何使用现有Java知识在Android和iOS上创建高性能应用程序的基础知识。 我们将使用JavaFX作为GUI工具包来完成所有这些工作。

But first, some more foreground. You will need to meet the subsequent requirements to be able to build an application for both Android and iOS. However, if you do not desire to build an iOS application, you can feel free to develop on any x64 bit machine that supports Java SE 8. This project will be a Git repository built with gradle. But you do not need to create a Git repository.

但是首先,还有一些前景。 您将需要满足后续要求能构建Android iOS的应用程序。 但是,如果您不希望构建iOS应用程序,则可以在支持Java SE 8的任何x64位计算机上自由开发。该项目将是使用gradle构建的Git存储库。 但是您无需创建Git存储库。

The following are the requirements:

以下是要求

  • A JDK 1.8 Compliant JVM

    符合JDK 1.8的JVM
  • Android Command Line Tools (SDK v.27)

    Android命令行工具(SDK v.27)
  • XCode 9.2

    XCode 9.2
  • Gradle 4.2

    Gradle4.2
  • Git Large File Storage (v.2.5.0) (Unnecessary if you do not want to create a git repository)

    Git大文件存储(v.2.5.0)(如果不想创建git存储库,则不需要)
  • Preferably at least 4G RAM

    最好至少4G RAM

Impatient? Want to see an end result? Check out the completed project below.

不耐烦? 想要看到最终结果? 在下面查看完成的项目。

afinlay5/OnyxFxGradle source code repository for OnyxFx, a cross-platform (Android/iOS/Linux/macOS/Windows) JavaFX app rendering…github.com

afinlay5 / OnyxFx OnyxFx的 Gradle源代码存储库,一个跨平台(Android / iOS / Linux / macOS / Windows)JavaFX应用程序渲染… github.com

My development environment will be Fedora Linux 28 and macOS High Sierra. Now that we’ve got that out of the way, let’s dig in.

我的开发环境将是Fedora Linux 28和macOS High Sierra。 现在我们已经解决了这个问题,让我们深入研究。

1)创建一个文件夹来容纳项目 (1) Create a folder to house the project)

I hosted my project, OnyxFx, as follows: “/home/adriandavid/Projects/OnyxFx”. You are, of course, free to host the project wherever you please.

我托管了我的项目OnyxFx,如下所示:“ / home / adriandavid / Projects / OnyxFx”。 当然,您可以随时随地随意托管该项目。

2)初始化gradle,Git,设置JAVA_HOME (2) Initialize gradle, Git, set JAVA_HOME)

Open a terminal in the root of the project directory. If gradle is properly configured, you should see something like this after executing the following command:

在项目目录的根目录中打开一个终端。 如果正确配置了gradle,则在执行以下命令后,应该会看到类似以下内容:

gradle -v

You need to make sure that gradle lists your Java Development Kit (JDK) 8 installation adjacent to the section labeled “JVM”.

您需要确保gradle在标有“ JVM”的部分旁边列出您的Java Development Kit(JDK)8安装。

While there are many ways to do this, the most straightforward way is to ensure that your JAVA_HOME environmental variable is properly set.

尽管有很多方法可以做到这一点,但最直接的方法是确保正确设置JAVA_HOME环境变量。

Depending on your environment, there are many ways to do this. One way to do this in most *nix environments is to set the variable in /home/<user>/.bashrc or /etc/profile. See the manual for your operating system to ensure that your JAVA_HOME environmental variable is set correctly.

根据您的环境,有很多方法可以执行此操作。 在大多数* nix环境中,执行此操作的一种方法是在/home/<user>/.b ash rc或/ etc / pro文件中设置变量。 请参阅您的操作系统的手册,以确保正确设置了JAVA_HOME环境变量。

You can include the following lines at the end of either .bashrc or profile to ensure that JAVA_HOME is set correctly.

您可以在.bashrc或配置文件的末尾包含以下行,以确保正确设置了JAVA_HOME。

JAVA_HOME=/home/adriandavid/java/oracle_jdk1.8.0_181/export JAVA_HOME

Note: You may install Oracle’s JDK 8 here.

注意:您可以在此处安装Oracle的JDK 8。

Then, make sure that the shell reflects the above changes by running one of the following commands:

然后,通过运行以下命令之一确保外壳程序反映了上述更改:

source ~/.bashrcsource /etc/profile

Enter the following command to verify that the variable is correctly set:

输入以下命令以验证变量设置正确:

echo $JAVA_HOME

If you are still experiencing difficulty or you are using Microsoft Windows, see here.

如果您仍然遇到困难或正在使用Microsoft Windows,请参见此处

First, run git init in the project’s root directory to initialize the Git repository. Note: should you not desire to host a git repository, you may skip this step.

首先,在项目的根目录中运行git init来初始化Git存储库。 注意:如果您不希望托管git存储库,则可以跳过此步骤。

Second, run gradle init in the project’s root directory to initialize the gradle repository. This step is required.

其次,在项目的根目录中运行gradle init来初始化gradle存储库。 此步骤是必需的。

Note: You will notice that my example appears slightly different. This is because I already have gradle and Git initialized on my local environment.

注意:您会注意到我的示例看起来略有不同。 这是因为我已经在本地环境中进行了gradle和Git初始化。

3)变得时髦! 编辑gradle.build和 (3) Get groovy! Edit gradle.build and)

Hopefully Earth, Wind, & Fire can help you get groovy! Power up your favorite text editor, and edit your build.gradle located in your project’s root directory and replace the contents with the contents of the following GitHub gist.

希望地球,风和火能帮助您获得时髦! 启动您喜欢的文本编辑器,并编辑位于项目根目录中的build.gradle,并将内容替换为以下GitHub gist的内容。

These build.gradle settings configure our gradle project to use the javafxmobile plugin, which is the work horse of our project. You can learn more about the plugin here and here. Among many things, the javafxmobile plugin automates the process of downloading (from Maven Central or jcenter) and adding the iOS and Android SDKs to your application’s classpath.

这些build.gradle设置将gradle项目配置为使用javafxmobile插件,这是我们项目的工作马力。 您可以在此处此处了解有关插件的更多信息。 在许多方面,javafxmobile插件可自动执行(从Maven Central或jcenter)下载并将iOS和Android SDK添加到应用程序的类路径的过程。

If you are familiar with gradle, maven, or ant, great — you probably have an idea of what’s going on. If you are not familiar with gradle, don’t worry about it. All you need to understand is that gradle is a build tool used to automate many tasks involved in building apps such as: grabbing dependencies, project organization, and so on.

如果您熟悉gradle,maven或ant,那么太好了-您可能对发生的事情有所了解。 如果您不熟悉gradle, 请不要担心 。 您需要了解的是gradle是一个构建工具,用于自动执行构建应用程序中涉及的许多任务,例如:捕获依赖项,项目组织等。

Notice that we are targeting Android 7.1 Nougat (API version 25) and iOS 11 (we will see where this is done shortly). You may adjust these values as you see fit. Note, however, that in the case of Android, you must ensure that the API version matches the version of the SDK that you have download (more on this later).

请注意,我们的目标是Android 7.1 Nougat(API版本25)和iOS 11(我们将很快看到这样做的位置)。 您可以根据需要调整这些值。 但是请注意,对于Android,必须确保API版本与您下载的SDK版本匹配(稍后会对此进行详细介绍)。

Lastly, I will not demonstrate the production of signed executables in this tutorial. For this reason, iOSSkipSigning is set to true and we do not make use of the releaseAndroid gradle task. You can, however, provide the appropriate accommodations to produce signed apps.

最后,我不会在本教程中演示签名可执行文件的产生。 因此, iOSSkipSigning设置为true,我们不使用releaseAndroid gradle任务。 但是,您可以提供适当的便利条件来生成已签名的应用程序。

4)创建一个名为gradle.properties的新文件并进行配置 (4) Make a new file called gradle.properties and configure it)

Create a new file in the project’s root directory called gradle.properties and add the following content to the file.

在项目的根目录中创建一个名为gradle.properties的新文件,并将以下内容添加到该文件中。

robovm.device.name=iPhone-7robovm.sdk.version=11.0org.gradle.jvmargs=-Xms4g -Xmx8g

These settings tell the javafxports plugin to use an iPhone-7 as the on-board emulator, to target iOS 11, and to pass the Xms and Xmx flags to the JVM, which specifies both the initial memory pool to 4GB and the maximum heap memory pool to 8GB. This will be necessary for the compilation of the openJDK and the development of the iOS build.

这些设置告诉javafxports插件使用iPhone-7作为板上仿真器,以iOS 11为目标,并将Xms和Xmx标志传递给JVM,JVM将初始内存池指定为4GB,并指定最大堆内存池到8GB。 这对于openJDK的编译和iOS版本的开发是必需的。

5)安装Homebrew(仅适用于iOS) (5) Install Homebrew (iOS only))

If you do not have a Mac and are not intending to produce an iOS build, feel free to skip this step.

如果您没有Mac,并且不打算生产iOS版本,请随时跳过此步骤。

Open the terminal in macOS and paste the following command.

在macOS中打开终端并粘贴以下命令。

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

6)安装USB多路传输插座(仅限iOS) (6) Install the USB Multiplexing Socket (iOS only))

Only move on to this step if Homebrew has successfully installed. If you do not have a Mac and are not intending to produce an iOS build, feel free to skip this step.

如果成功安装了Homebrew,请继续执行此步骤。 如果您没有Mac,并且不打算生产iOS版本,请随时跳过此步骤。

Open the terminal in macOS and paste the following command.

在macOS中打开终端并粘贴以下命令。

brew install usbmuxd

7)抓住Android命令行工具 (7) Grab the Android Command Line Tools)

Grab Android Command Line Tools for your platform here. After the download has finished, unzip the folder and paste the contents in the directory of your choice. For me, this was /home/<user>/Android.

在此处获取适用于您平台的Android命令行工具。 下载完成后,解压缩文件夹并将其内容粘贴到您选择的目录中。 对我来说,这是/home/<user>/A机器人。

8)设置Android_HOME,获取必要的Android包 (8) Set Android_HOME, Grab necessary Android packages)

As with Java, gradle needs to know where to look to find the Android Command Line Tools. There are a few ways to do this. However, in the spirit of simplicity and consistency, we will set the ANDROID_HOME environmental variable in this tutorial. Add the following variable in the same way that we did it for JAVA_HOME. For example:

与Java一样,gradle需要知道在哪里可以找到Android命令行工具。 有几种方法可以做到这一点。 但是,本着简洁性和一致性的精神,我们将在本教程中设置ANDROID_HOME环境变量。 以与对JAVA_HOME相同的方式添加以下变量。 例如:

ANDROID_HOME=/home/adriandavid/Android/ export ANDROID_HOME

Remember to reload the shell by adding source <file> as we did for JAVA_HOME.

记住要像添加JAVA_HOME一样,通过添加source <fi >来重新加载Shell。

Now, grab the tools necessary to build the Android build. Execute the following command:

现在,抓住构建Android构建所需的工具。 执行以下命令:

# *.nix./sdkmanager "platform-tools" "build-tools;25.0.3" "platforms;android-25" "extras;android;m2repository" "extras;google;m2repository"
or
#Windowssdkmanager "platform-tools" "build-tools;25.0.3" "platforms;android-25" "extras;android;m2repository" "extras;google;m2repository"

Take careful notice that the SDK and API version we have specified in gradle.build correspond to the version we have specified in this command. Namely, “25”. Should this be misaligned, the build will not succeed.

请注意,在gradle.build中指定的SDK和API版本与在此命令中指定的版本相对应。 即“ 25”。 如果未对齐,则构建将不会成功。

9)创建应用程序的目录结构 (9) Create the application’s directory structure)

To automate the process of creating these directories, execute the following shell script.

要自动化创建这些目录的过程,请执行以下shell脚本。

Bourne-Again Shell / Korn Shell:

Bourne-Again Shell / Korn Shell:

Windows Shell (cmd):

Windows Shell(cmd):

Save the file as mkpdir.bat or mkpdir.sh and execute the file from the project’s root directory as root (or Administrator).

将文件另存为mkpdir.bat或mkpdir.sh并以root (或Administrator )身份从项目的根目录执行该文件。

# *.nixchmod +x mkdir.sh-sh ./mkpdir.sh
# Windowsmkpdir

Notice that we created directories for embedded and desktop. We will produce a desktop build, because it takes no additional work to do so. However, we will not produce any builds for embedded devices.

注意,我们为嵌入式和台式机创建了目录。 我们将生成一个桌面版本,因为它不需要任何额外的工作。 但是,我们不会为嵌入式设备生成任何版本。

10)创建您的JavaFX应用程序! (10) Create your JavaFX Application!)

Navigate to /src/<platform>/java and begin developing your JavaFx application! Application resources are stored in /src/<platform>/resources.

导航到/ src / <platform> / java并开始开发JavaFx应用程序! 应用程序资源存储在/ src / <platform> / resources中。

You can start with a simple Hello World application or look at the source code that I have put together here. OnyxFx is an application I made, following these instructions, that makes REST calls over HTTP to the OnyxFxAPI. The API, in turn, is a web scraper that will return the statistical data (points per game, rebounds per game, assists per game) for the NBA® player and season the client specifies. It returns the data as JSON, which is then parsed and displayed to the screen of the mobile app. Feel free to edit it!

您可以从一个简单的Hello World应用程序开始,或者查看我在这里整理的源代码。 OnyxFx是我按照以下说明制作的应用程序,可通过HTTP对OnyxFxAPI进行REST调用。 反过来,API是一个网络抓取工具,它将返回NBA®球员和客户指定赛季的统计数据(每场得分,每场篮板,每场助攻)。 它将数据作为JSON返回,然后将其解析并显示在移动应用程序的屏幕上。 随时编辑!

Keep in mind that although you can share source code, you should include custom edits in each copy of the source, should you want to make device specific changes.

请记住,尽管可以共享源代码,但是如果要进行设备特定的更改,则应在源的每个副本中包括自定义编辑。

Also note that the underlying compiler (MobiDevelop’s fork of RoboVM) does not fully support all Java 8 APIs. If you look very closely at my source code, you will notice that in the iOS version of the source code, I have removed unsupported API such as java.util.function.BiConsumer and java.util.Map.replace().

另请注意,底层编译器(MobiDevelop的RoboVM分支)并不完全支持所有Java 8 API。 如果您仔细查看我的源代码,您会注意到在iOS版本的源代码中,我删除了不支持的API,例如java.util.function.BiConsumerjava.util.Map.replace()

11)创建用于iOS构建的RAM磁盘(仅适用于iOS) (11) Create a RAM disk for iOS builds (iOS only))

The compilation process for iOS is very resource-heavy, as the plugin will compile the entire openJDK and other libraries twice to create a fat JAR that it will use to build your application. Therefore, you should preemptively create a RAM disk to accommodate for the memory requirements.

iOS的编译过程非常耗资源,因为该插件将编译整个openJDK和其他库两次,以创建一个胖JAR,它将用于构建您的应用程序。 因此,您应该抢先创建RAM磁盘以适应内存需求。

This step, however, is subject to your judgement of your machine’s capabilities. For context, the macOS machine that I used to compile my iOS app has 4GB of DDR2 RAM. I decided to make an 8GB RAM disk. To do so, execute the following command in the terminal.

但是,此步骤取决于您对计算机功能的判断。 就上下文而言,我用来编译iOS应用程序的macOS机器具有4GB的DDR2 RAM。 我决定制作一个8GB的RAM磁盘。 为此,请在终端中执行以下命令。

SIZE=8192 ; diskutil erasevolume HFS+ ‘RoboVM RAM Disk’ `hdiutil attach -nomount ram://$((SIZE * 8192))`

12)构建并运行您的应用程序! (12) Build and Run your application!)

To build your application, execute the gradle wrapper in the root directory from the terminal as follows.

要构建您的应用程序,请从终端在根目录中执行gradle包装器,如下所示。

./gradlew clean build

This will produce a desktop application packaged as a JAR with scripts to run the application provided in /build/distributions/<AppName.tar>; and /build/distributions/<AppName.zip>. Should you unzip the directories, you will notice the following structure:

这将产生一个打包为JAR的桌面应用程序,并带有脚本来运行/build/distributions/<AppName.t ar>中提供的应用程序; and /build/distributions/<App ; and /build/distributions/<App Name.zip>。 如果您解压缩目录,则会注意到以下结构:

Notice that in /bin there are scripts to execute the application. These scripts rely on preserving the current folder structure. Also notice that is not necessary for you to have tree installed. It is used here simply for illustrative purposes.

请注意,/ bin中有执行该应用程序的脚本。 这些脚本依赖于保留当前的文件夹结构。 另请注意,您不必安装 。 它仅在此处用于说明目的。

There is, additionally, a standalone JAR that you can use to execute the application on any desktop environment supporting JavaFX 8. To run the application, execute one of the following:

此外,还有一个独立的JAR,可用于在任何支持JavaFX 8的桌面环境上执行该应用程序。要运行该应用程序,请执行以下操作之一:

# Navigate to /build/distributions/<ProjectName>/
#On *.nixcd bin./<ProjectName>
#On Windowscd bin<ProjectName>
#Platform agnosticjava -jar OnyxFxMobile.jar (or double click, if jvm is configured to run .jar files)
Note: If the executable providing "java" is not the same vendor and/or version of the Java 8 JDK with which you built this application, the jar may not run. JavaFX 8 builds between the openJDK & Oracle JDK are incompatible.
Otherwise: /location/to/java8/bin/java -jar <ProjectName>

查看该项目的gradle任务 (View this project’s gradle tasks)

You can view this project’s gradle tasks by running the following in the project’s root directory.

您可以通过在项目的根目录中运行以下命令来查看该项目的gradle任务。

./gradlew tasks

要进行编译,请在桌面上运行 (To Compile, Run on Desktop)

The following command will run your project in the host environment.

以下命令将在宿主环境中运行您的项目。

./gradlew jar./gradlew run

You will find a standalone jar in build/libs/<AppName&gt;.jar .

您将在build/libs/<AppName&g t; .jar中找到一个独立的jar。

编译,在Android上运行 (To Compile, Run on Android)

./android #Generates a debug Android apk containing the JavaFX application.
./androidInstall #Launch the application on a connected android device.
./androidRelease #Generates a release Android apk containing the JavaFX application.
Note: You will need to configure a valid signingConfig when releasing an APK (javafxports).

You will find two APKs in build/javafxports/android.The first will be named <AppName&gt;.apk.The second will be named <AppName>-unaligned.apk.

您可以在build/javafxports/android找到两个APK,第一个命名为<AppName&g t; .apk,第二个named <AppName>-u naligned.apk。

要编译,在iOS上运行 (To Compile, Run on iOS)

./createIpa - Generates an iOS ipa containing the JavaFX app.
./launchIOSDevice - Launches app on a connected ios device.
./launchIPadSimulator - Launches app on an iPad simulator.
./launchIPhoneSimulator - Launches app on an iPhone simulator.

You will find three executables in build/javafxports/ios.The first will be named <AppName&gt;.ipa.The second will be named <AppName>.dSYM.The third will be named &lt;AppName>.app.

您将在build/javafxports/ios找到三个可执行文件,第一个名为<AppName&g t; .ipa,第二个named <AppN ame> .dSYM,第三个ll be named & lt; AppName> .app。

我的示例应用程序的一些屏幕截图 (Some screenshots of my sample app)

在桌面上 (On Desktop)

在Android上 (On Android)

在iPhone上 (On iPhone)

在iPad上 (On iPad)

开机画面 (Splash Screen)

我的总结思想 (My Closing Thoughts)

javafxports is a promising project that aims to bring JavaFX and the Java SE platform onto mobile and other devices. In a way, the tool parallels Xamarin in its efforts. However, the project has a lot of work left to be done.

javafxports是一个有前途的项目,旨在将JavaFX和Java SE平台引入移动设备和其他设备。 从某种意义上说,该工具在Xamarin的努力上与之相似。 但是,该项目还有许多工作要做。

For a start, the plugin currently does not fully support Java 8. On Android, it uses retrolambda to handle Java 8 Lambda Expressions & Method References. It technically is up to Java 6. Additional dependencies make it such that you can use Java 8. However, the process is straightforward, the builds work as expected, and the compilation time is not too long.

首先,该插件当前不完全支持Java8。在Android上,它使用Retrolambda处理Java 8 Lambda表达式和方法引用。 从技术上讲,它取决于Java6。附加的依赖关系使其可以使用Java8。但是,此过程很简单,构建按预期进行,并且编译时间不太长。

On iOS, however, the builds are extremely memory-intensive and the compilation process takes a very long time. The following is a snippet of the log for ./gradlew createIpa task.

但是,在iOS上,构建会占用大量内存,并且编译过程会花费很长时间。 以下是./gradlew createIpa任务的日志片段。

:createIpa (Thread[Task worker for ‘:’,5,main]) completed. Took 1 hrs 46 mins 40.198 secs.

In total, the process consumed about over 6GB of RAM on my machine. This is hardly ideal. However, the future is promising. A company called Gluon has developed a high performance, fully modular custom JVM fully supporting Java 9, that you can read more about here.

整个过程总共消耗了我机器上超过6GB的RAM。 这几乎不是理想的。 但是,未来是有希望的。 一家名为Gluon的公司已经开发了一种完全支持Java 9的高性能,完全模块化的定制JVM,您可以在此处了解更多信息。

This article is originally published on the blog section of my homepage, here.

本文最初发布在我主页的博客部分的此处

探索资源: (Resources to explore:)

翻译自: https://www.freecodecamp.org/news/how-to-make-a-cross-platform-mobile-app-in-java-5f8eae071ff2/

java跨平台跨平台

 类似资料: