对于那些时候,当你想要隔离Java并给它一个快速测试。
你能像在Eclipse中一样在Android studio中运行非Android Java项目吗?
对于那些时候,当你想要隔离Java并给它一个快速测试。
你能像在Eclipse中一样在Android studio中运行非Android Java项目吗?
当前回答
我已经能够使用以下步骤做到这一点:
打开Android Studio,选择“Import Project”。 在浏览窗口中浏览到您的项目文件夹并选择它。
其他回答
在Android Studio 0.8.14中测试: 我能够以这种方式以最少的步骤运行一个标准项目: 在打开的Android Studio项目中,单击File > New Module。 单击More Modules > Java Library > Next,然后填写您喜欢的名称。 一个新的模块将作为一个文件夹出现在项目结构中与“app”文件夹相同的级别。打开它并打开新的Java类文件。
然后您可以添加您的代码,并选择构建>运行'YourClassName'。很快,你的代码就在没有Android设备的情况下运行了!
要在Android中运行java文件,请确保类具有main方法。在Android Studio 3.5中,只需右键单击文件内部并选择“运行'Filename.main()'”或单击菜单上的“运行”,并从产生的下拉菜单中选择“运行文件名”。
这就是具体的设置。
编辑配置> '+' >
在Android Studio 4.0及以上版本上,你会在IDE上得到一个选项,一个绿色的运行图标来运行相关的main()类。
在Android Studio 0.8.6 - 3.5上测试
使用这种方法,你可以在同一个项目中拥有Java模块和Android模块,还可以将Java模块作为独立的Java项目编译和运行。
Open your Android project in Android Studio. If you do not have one, create one. Click File > New Module. Select Java Library and click Next. Fill in the package name, etc and click Finish. You should now see a Java module inside your Android project. Add your code to the Java module you've just created. Click on the drop down to the left of the run button. Click Edit Configurations... In the new window, click on the plus sign at the top left of the window and select Application A new application configuration should appear, enter in the details such as your main class and classpath of your module. Click OK.
现在,如果单击run,应该会编译并运行Java模块。
如果你得到错误错误:无法找到或加载主类…,只需再次输入你的主类(就像你在步骤7中所做的那样),即使字段已经填写。单击Apply,然后单击Ok。
我的用例: 我的Android应用程序依赖于一些预先计算好的文件来运行。这些预计算文件是由一些Java代码生成的。由于这两件事是相辅相成的,所以在同一个项目中同时拥有这两个模块是最有意义的。
新-如何在你的独立项目中启用Kotlin
如果希望在独立项目中启用Kotlin,请执行以下操作。
Continuing from the last step above, add the following code to your project level build.gradle (lines to add are denoted by >>>): buildscript { >>> ext.kotlin_version = '1.2.51' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.3' >>> classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } ... Add the following code to your module level build.gradle (lines to add are denoted by >>>): apply plugin: 'java-library' >>> apply plugin: 'kotlin' dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) >>> implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" >>> runtimeClasspath files(compileKotlin.destinationDir) } ... Bonus step: Convert your main function to Kotlin! Simply change your main class to: object Main { ... @JvmStatic fun main(args: Array<String>) { // do something } ... }