我们如何引用位于我们主 Android 项目目录之外的自定义 Android 和 Java 库? [英] How do we reference custom Android and Java Libraries living outside the directory of our Main Android Project?

查看:18
本文介绍了我们如何引用位于我们主 Android 项目目录之外的自定义 Android 和 Java 库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用库的常规设置是 Android Studio 导入 库到我们主项目的根目录中.这并不是我们真正想要的,因为库的基本好处是它可以在许多项目之间共享.如果我们更新导入的库中的代码,这不会反映在之前导入到另一个项目的库的代码中.

The conventional setup for referencing libraries has Android Studio import the libraries into the root directory of our main project. That's not really what we want as the essential benefit of a library is so that it is shared between many projects. If we update code in an imported library, that's not going to be reflected in the code of a library previously imported to another project.

相反,我们的目标是创建一个 Main Android 项目,该项目可以引用存在于 Android 项目目录之外的自定义(您创建的)Android 和 Java 库模块,并且能够编辑来自以下目录的所有三个模块的代码在主 Android 项目中.也就是说,我们希望以:

Our goal, instead, is to create a Main Android project that can reference custom (that you create) Android and Java library modules that exist outside the directory of the Android project, with the ability to edit code of all three modules from within the Main Android project. That is, we want to end up with:

  • 属于我们的主要 Android 项目的根模块(应用程序");
  • 一个 Android 库模块,它存在于 Android 项目目录之外,但被我们的主 Android 项目引用.
  • 一个 Java 库模块,存在于 Android 项目目录之外,但被我们的主 Android 项目引用.

... 例如,所以我们有一个类似于...

... for example, so we have a directory structure like ...

..\LibraryRefDemo\MyMainProject
..\LibraryRefDemo\Libraries\MyAndroidLibrary
..\LibraryRefDemo\Libraries\MyJavaLibrary

换句话说,标题问题是我们如何做到这一点?".

The headline question asks, in other words, "How do we do this?".

已有类似的stackoverflow问题,例如...

There are existing similar stackoverflow questions, for example ...

但我发现这些问题和答案仅部分解决了我在这里提出的问题.

But I've found both those questions and the answers only partially address the issue I present here.

我将提供我自己问题的答案,我相信它列举了所有技巧和问题,并提供了一个分步过程.

I'm going to provide the answer to my own question which, I believe, enumerates all the tricks and gotchas and provides a step by step procedure.

我将使用 Android Studio 3.0.1 ...

I'll be using Android Studio 3.0.1 ...

推荐答案

目录

  • 命名和目录约定
  • 基本技巧
  • 创建主要的 Android 项目
  • 创建自定义 Android 库
  • 从主 Android 项目中引用自定义 Android 库
  • 创建 Java 库/模块
  • 从主项目中引用 Java 库
  • 请编辑
  • 首先我们建立我们的命名和目录约定(如果你不喜欢以下,建立你自己的约定).

    Firstly we establish our naming and directory conventions (if you don't like the following, establish your own convention).

    项目名称:PascalCase.

    Project name: PascalCase.

    ..\LibraryRefDemo\MyMainProject
    ..\LibraryRefDemo\Libraries\MyAndroidLibrary
    ..\LibraryRefDemo\Libraries\MyJavaLibrary
    

    创建新项目向导 > 创建 Android 项目:

    Create New Project Wizard > Create Android Project:

    应用名称:MyMainProject
    项目位置:..\MyMainProject

    包名:小写.

    // (package name for MyMainProject's root module: "app")
    au.com.example.mymainproject
    
    // (package name for MyAndroidLibrary's root module: "malmodule")
    au.com.example.malmodule
    
    // (package name for MyJavaLibrary' module where we placed our 
    // java code to be shared: "mjlmodule")
    au.com.example.mjlmodule 
    

    模块名称:小写.以下情况之一:

    Module name: lowercase. One of the following:

    app (MyMainProject's root module)
    malmodule (MyAndroidLibrary's root module)
    mjlmodule (The MyJavaLibrary's module where we placed our java code to be
      shared. The MyJavaModule will also contain a root "app" module 
      for reasons of gradle integration)
    

    基本技巧

    以下基本技巧以及随后的分步过程是截至 2018 年 3 月 10 日适用于 Android Studio 3.0.1 的最新版本.在完成分步程序之前,完成这项工作的基本技巧是:

    Basic tricks

    The following basic tricks, and the subsequent step-by-step procedures, are current as of 2018-03-10 for Android Studio 3.0.1. Before going through the step-by-step procedures, the basic tricks to make this work are:

    • 使用 Android Studio 而不是其他 IDE(如 IDEA IntelliJ)来创建 MyMainProject、MyAndroidLibrary 和 MyJavaLibrary.一旦设置了基本框架,就可以从任何现有项目中复制代码和资源(例如使用 Windows 资源管理器).
    • 在主 Android 项目 ("MyMainProject") settings.gradle (Project Settings) 中,我们使用类似以下内容引用库模块(而不是库项目):

    • Use Android Studio, rather than another IDE (like IDEA IntelliJ), for creating MyMainProject, MyAndroidLibrary and MyJavaLibrary. Code and resources can be copied (e.g. using Windows Explorer) from any existing projects once the basic framework has been setup.
    • In the Main Android Project ("MyMainProject") settings.gradle (Project Settings), we reference Library modules (rather than Library Projects as such) using something like the following:

    include ':app'
    
    include ':malmodule'
    // Despite the name "project" we actually need to reference the module directory
    // of a project. It doesn't matter whether there is a trailing slash '/' or not.
    project(':malmodule').projectDir =
            new File(settingsDir, '../Libraries/MyAndroidLibrary/malmodule/')
    
    include ':mjlmodule'
    // Despite the name "project" we actually need to reference the module directory
    // of a project. It doesn't matter whether there is a trailing slash '/' or not.
    project(':mjlmodule').projectDir =
            new File(settingsDir, '../Libraries/MyJavaLibrary/mjlmodule/')
    

  • 在Android项目(MyMainProject")根模块的build.gradle文件中,默认build.gradle(Module: app),添加:

    dependencies {
        ...
        // Reference module rather than project.
        implementation project(':malmodule')
        implementation project(':mjlmodule')
        ...
    }
    

  • 在创建 MyJavaLibrary 时使用独立安装的 JDK,而不是 Android 的嵌入式 JDK:
    • 文件 > 项目结构 > |SDK 位置|> JDK位置:
      • 使用嵌入式 JDK(推荐)":未勾选.
      • C:\Program Files\Java\jdk1.8.0_161
      • 分步过程如下.字符串中的正斜杠/"将代表项目窗格中的路径,Android 视图(从组合框中选择).字符串中的反斜杠\"将代表文件系统中的路径……

        The step-by-step procedure is as follows. A forward slash "/" in a string will represent a path in the Project Pane, Android View (chose from the combo box). A back slash "\" in a string will represent a path in the file system …

        创建一个 Android 项目(MyMainProject"):

        Create an Android Project ("MyMainProject"):

        • 打开 {Android Studio} 到欢迎使用 Android Studio"屏幕> [启动一个新的 Android Studio 项目] ...
        • 向导创建新项目"> |创建 Android 项目|:

        • Open {Android Studio} to the 'Welcome to Android Studio' screen > [Start a new Android Studio project] …
        • Wizard 'Create New Project' > |Create Android Project|:

        • 应用程序名称(概念上这也是项目名称"):MyMainProject
        • 公司域名:example.com.au
        • 项目位置:..\LibraryRefDemo\MyMainProject
        • 包名称:au.com.example.mymainproject
        • [下一步]

        向导 |目标 Android 设备:选择外形规格和最小 SDK|.接受默认值(或作为愿望).[下一个].

        Wizard |Target Android Devices: Select the form factors and minimum SDK|. Accept defaults (or as desire). [Next].

        添加一些hello world"资源和代码.在项目窗格中切换到 Android 视图(从组合框中):

        Add some "hello world" resources and code. In the Project Pane switch to Android View (from the combo box):

        • res/layout/activity_main.xml.添加 ID.

        • res/layout/activity_main.xml. Add id.

        <TextView
            android:id="@+id/mymainproject_output"
            android:layout_width="wrap_content"
        

      • res/values/strings.xml.添加字符串资源.

      • res/values/strings.xml. Add string resource.

        <string name="mymainproject_cool_string">From My Main Project</string>
        

      • au.com.example.mymainproject.MainActivity.引用 java 代码中的字符串资源.

      • au.com.example.mymainproject.MainActivity. Reference string rescource from java code.

        public class MainActivity extends Activity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
        
                TextView textView = (TextView) findViewById(R.id.mymainproject_output);
                String someString = getResources().getString(R.string.mymainproject_cool_string) + "\r\n";
                textView.setText(someString); 
            }
        } 
        

        要正确导入引用的类,您可能必须:将光标插入到 TextView 上;alt+回车;

        To properly import the referenced classes you may have to: insert your cursor over a TextView; alt+ enter;

        在模拟器上运行以验证 OK:运行 > 运行应用程序 (Shift+F10)...选择部署目标">(单击所需的可用虚拟设备)> [确定].

        Run against the emulator to verify OK: Run > Run app (Shift+F10)... "Select Deployment Target" > (Click on your desired Available Virtual Device) > [OK].

        等待 gradle 完成构建.观察应用程序中的字符串:

        Wait for gradle to finish building. Observe the string in your application:

        From My Main Project
        

      • 首先我们创建另一个普通的Android项目,然后我们把它变成一个Android库.

        Firstly we create another ordinary Android Project, then we turn it into an Android Library.

        将库创建为另一个普通的 Android 项目:

        Create the library as another ordinary Android Project:

        • 在 Android Studio 中关闭打开的项目(如果打开).
        • 打开 {Android Studio} 到欢迎使用 Android Studio"屏幕> [启动一个新的 Android Studio 项目]:

        • In Android Studio close the open project, if open.
        • Open {Android Studio} to the 'Welcome to Android Studio' screen > [Start a new Android Studio project]:

        • 向导创建新项目",|创建 Android 项目|.
          • 应用程序名称:MyAndroidLibrary
          • 公司域名:example.com.au
          • 项目位置:..\LibraryRefDemo\Libraries\MyAndroidLibrary
          • 包名称.:au.com.example.malmodule(我们使用这个名称而不是默认名称,以便稍后明确我们直接引用模块而不是项目).
          • [下一步]
          • Wizard "Create New Project", |Create Android Project|.
            • Application name: MyAndroidLibrary
            • Company domain: example.com.au
            • Project location: ..\LibraryRefDemo\Libraries\MyAndroidLibrary
            • Package name. : au.com.example.malmodule (We are using this name rather than the default to make it clear, later on, that we are directly referencing modules rather than projects).
            • [Next]

            等待 gradle 完成构建.

            Wait for gradle to finish building.

            添加一些 hello-world 类型代码:

            Add some hello-world type code:

            • 在malmodule/res/values/strings.xml中,添加:

            • In malmodule/res/values/strings.xml, add:

            <string name="myandroidlibrary_cool_string">From My Android Library</string>
            

          • ../res/layout/activity_main.xml(文本视图).添加 ID.

          • ../res/layout/activity_main.xml (Text View). Add id.

            <TextView
                android:id="@+id/myandroidlibrary_output"
                android:layout_width="wrap_content"
            

          • 在..\LibraryRefDemo\Libraries\MyAndroidLibrary\malmodule\src\main\java\au\com\example\malmodule\MainActivity.java中,添加onCreate方法(并导入相关类,alt+enter光标在 TextView 上):

          • In ..\LibraryRefDemo\Libraries\MyAndroidLibrary\malmodule\src\main\java\au\com\example\malmodule\MainActivity.java, add to onCreate method (and import relevant classes, alt+enter with cursor over TextView):

            public class MainActivity extends Activity {
            
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
            
                    TextView myText = (TextView) findViewById(R.id.myandroidlibrary_output);
                    String someString = getResources().getString(R.string. myandroidlibrary_cool_string) + "\r\n";
                    myText.setText(someString); 
                }
            } 
            

            要正确导入引用的类,您可能必须:将光标插入到 TextView 上;alt+回车;

            To properly import the referenced classes you may have to: insert your cursor over a TextView; alt+ enter;

            从别处复制任何现有的代码(和资源).将android代码复制到:..\LibraryRefDemo\Libraries\MyAndroidLibrary\malmodule\src\main\java\au\com\example\malmodule

            Copy any existing code (and resources) from elsewhere. Copy android code into: ..\LibraryRefDemo\Libraries\MyAndroidLibrary\malmodule\src\main\java\au\com\example\malmodule

            验证它可以作为项目运行:运行 > 运行malmodule".等待 gradle 完成构建.在模拟器中观察字符串:

            Verify it can run as a project: Run > Run 'malmodule'. Wait for gradle to finish building. Observe string in the emulator:

            From My Android Library
            

          • (从上面开始)将项目的模块转换为 Android 库:

            (Following on from above) convert a project's module to an Android library:

            • {Android Studio} > 项目面板 > Android 视图 > Gradle 脚本 > build.gradle(模块:malmodule)> 双击(打开).然后……

            • {Android Studio} > Project Panel > Android View > Gradle Scripts > build.gradle (Module: malmodule) > Double Click (to open). Then ...

            // Change ...
            apply plugin: 'com.android.application'
            
            // To ...
            apply plugin: 'com.android.library'
            

          • 也在 build.gradle (Module: malmodule) 中注释掉 applicationID.

          • Also in build.gradle (Module: malmodule) comment out applicationID.

            ...
            android {
                compileSdkVersion 26
                defaultConfig {
            //        applicationId "au.com.example.malmodule"
                    ... 
            

            注释掉而不是删除,以防我们想重新运行malmodule 作为一个普通的Android 项目进行测试.Android Studio 1.0 和错误库项目不能设置 applicationId"

            Comment out rather than delete, in case we want to re-run malmodule as an ordinary Android Project for testing purposes. Android Studio 1.0 and error "Library projects cannot set applicationId"

            工具 > Android > 将项目与 Gradle 文件同步(或单击黄色提示栏中的立即同步"链接).等待 gradle 构建完成.

            Tools > Android > Sync Project with Gradle files (or click "Sync Now" link in yellow tip bar). Wait for gradle build to finish.

            要引用您的自定义 Android 库项目(位于主项目目录之外):

            To reference your custom Android Library Project (living outside the Main Project's directory):

            • {Android Studio} > 文件 > 打开最近 > MyMainProject >打开项目"> [此窗口].
            • 项目窗格> Android 视图(从下拉菜单).
            • 打开 MyMainProject 的 settings.gradle(项目设置) 文件.添加 :malmodule 引用如下..

            • {Android Studio} > File > Open Recent > MyMainProject > 'Open Project' > [This Window].
            • Project Pane > Android View (from drop down).
            • Open MyMainProject's settings.gradle (Project Settings) file. Add :malmodule references as follows ..

            include ':app'
            
            include ':malmodule'
            // Despite the name "project" we actually need to reference the module directory
            // of a project. It doesn't matter whether there is a trailing slash '/' or not.
            project(':malmodule').projectDir =
                    new File(settingsDir, '../Libraries/MyAndroidLibrary/malmodule/')
            

          • 打开 MyMainProject 的根模块的 build.gradle 文件(即 build.gradle (Module: app)).然后添加 ...

            dependencies {
                ...
                // Reference module rather than project.
                implementation project(':malmodule')
                ...
            }
            

          • 工具 > Android > 将项目与 Gradle 文件同步(或单击黄色提示栏中的立即同步"链接).

          • Tools > Android > Sync Project with Gradle files (or click "Sync Now" link in yellow tip bar).

            验证您可以从库中引用字符串资源:

            Verify you can reference a string resource from the Library:

            • 检查 ..malmodule/res/values/strings.xml 中的以下字符串...

            • Check ..malmodule/res/values/strings.xml for the following string ...

            <string name="myandroidlibrary_cool_string">From My Android Library</string>
            

          • 检查 MyMainProject app/res/layout/activity_main.xml ...

          • Check MyMainProject app/res/layout/activity_main.xml ...

            <TextView
                android:id="@+id/mymainproject_output"
                android:layout_width="wrap_content"
            ...
            

          • 在主项目 app/java/au.com.example.mymainproject/MainActivity 中添加对 myandroidlibrary_cool_string 的引用.

          • In Main Project app/java/au.com.example.mymainproject/MainActivity add a reference to myandroidlibrary_cool_string.

            public class MainActivity extends Actvity {
            
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
            
                    TextView myText = (TextView) findViewById(R.id.mymainproject_output);
                    String someString = getResources().getString(R.string.mymainproject_cool_string) + "\r\n";
                    someString += getResources().getString(au.com.example.malmodule.R.string.myandroidlibrary_cool_string) + "\r\n";
                    myText.setText(someString); 
            
                }
            }
            

          • 从您的库清单中注释掉 MAIN/LAUNCHER 意图.否则,应用程序抽屉中将出现两个应用程序图标.

          • From your library manifest comment out the MAIN/LAUNCHER intent. Otherwise two icons for your app will appear in the App drawer.

            <activity android:name=".MainActivity">
                <!-- Don't make a main/launcher activity when being called by main app -->
                <!--<intent-filter>-->
                    <!--<action android:name="android.intent.action.MAIN" />-->
            
                    <!--<category android:name="android.intent.category.LAUNCHER" />-->
                <!--</intent-filter>-->
            </activity>
            

          • 运行您的主项目.运行 > 运行应用程序 (Shift+F10).等待 gradle 构建和模拟器加载您的应用程序.观察来自您的库的字符串反映在您的模拟器中:

          • Run your Main Project. Run > Run app (Shift+F10). Wait for gradle to build and for the emulator to load your app. Observe the string coming from your library is reflected in your emulator:

            From My Main Project
            From My Anroid Library
            

          • 更改 ..malmodule/res/values/strings.xml 中的字符串

          • Alter a string from ..malmodule/res/values/strings.xml

            <string name="myandroidlibrary_cool_string">My Android Library XXX</string>
            

          • 运行 > 应用更改 (Ctrl+F10).等待 gradle 构建和模拟器重新加载您的应用程序.观察更改后的字符串是否反映在您的模拟器中.

          • Run > Apply changes (Ctrl+F10). Wait for gradle to build and for the emulator to reload your app. Observe that the changed string is reflected in your emulator.

            (Google 和 Gradle 插件用户指南)http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-projects(Goolge Android 工具,2014 年.开发 > 工具)https://developer.android.com/studio/projects/android-library.html

            (Google, n.d. Gradle Plugin User Guide) http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-projects (Goolge Android Tools, 2014. Develop > Tools) https://developer.android.com/studio/projects/android-library.html

            使用 Java-Library 模块创建项目 ...

            Create a Project with a Java-Library module ...

            首先用一个Android模块创建一个普通的Android项目:

            First create an ordinary Android Project with an Android Module:

            • 如果打开则关闭当前项目.
            • 打开 {Android Studio} 到欢迎使用 Android Studio"屏幕> [启动新的 Android Studio 项目]:
            • 向导创建新项目"

            • Close current project if open.
            • Open {Android Studio} to the 'Welcome to Android Studio' screen > [Start a new Android Studio project]:
            • Wizard "Create New Project"

            • |创建 Android 项目|

            • |Create Android Project|

            • 应用程序名称:MyJavaLibrary
            • 公司域名:example.com.au
            • 项目位置:..\LibraryRefDemo\Libraries\MyJavaLibrary
            • 包名称:au.com.example.myjavalibrary(这将是根模块的命名空间,我们的 java 代码将位于我们随后创建的另一个模块和命名空间中).[下一个]
            • Application name: MyJavaLibrary
            • Company domain: example.com.au
            • Project location: ..\LibraryRefDemo\Libraries\MyJavaLibrary
            • Package name: au.com.example.myjavalibrary (this will be the namespace for the root module, our java code will live in another module and namespace that we'll subsequently create). [Next]

            |目标 Android 设备|.接受默认值(或根据需要).[下一个]

            |Target Android Devices|. Accept defaults (or as desired). [Next]

            打开项目面板.从组合框中选择Android"视图.

            Open Project Pane. Select "Android" View from combobox.

            创建 Java 库模块:

            Create a Java Library Module:

            • 文件>新建...>新建模块...
            • 向导创建新模块".

            • File > New ... > New Module ...
            • Wizard "Create New Module".

            • |新模块|> Java 库.[下一个]
            • |Java 库|配置您的新模块".

            • |New Module| > Java Library. [Next]
            • |Java Library| "Configure your new module".

            • 库名称:mjlmodule
            • Java 包名:au.com.example.mjlmodule
            • Java 类名:Start
            • [完成]

            不要删除 MyJavaLibrary 项目的根模块 app.如果这样做,默认情况下,您的 mjlmodule 将成功运行一次,但对代码的后续更新不会合并到第二次和后续运行中.

            Do not delete the MyJavaLibrary Project's root module, app. If you do then, by default, your mjlmodule will run once successfully but subsequent updates to code won't be incorporated into the second and subsequent runs.

            可能有一种方法可以正确整理 gradle 文件,但我的 gradle 知识有限.

            There may be a way to properly sort out the gradle files but my gradle knowledge is limited.

            在您的 Java 库模块中插入一些代码:

            In your Java Library Module shove some code in:

            • 在您新创建的 Java 类 Start 中,添加一个 main 方法.确保您的主要方法具有正确的签名(特别包括String[] args").例如,将以下类用于 hello world 目的.mjlmodule/java/au.com.example.mjlmodule/Start ...

            • In your newly created Java Class, Start, add a main method. Ensure your main method has the correct signature (specifically include "String[] args"). For example use the following class for hello world purposes. mjlmodule/java/au.com.example.mjlmodule/Start ...

            package au.com.example.mjlmodule;
            
            public class Start {
                public static void main(String[] args) {
                    System.out.println(getCoolString());
                }
            
                // Must be public because we want to reference the method directly later
                public static String getCoolString() {
                    return "From My Java Library";
                }
            } 
            

          • 项目窗格 > Android 视图(来自组合框)> Gradle 脚本 > build.gradle(模块:mjlmodule):

            • 验证应用插件集属性:

            • Verify apply plugin set propery:

            apply plugin: 'java-library'
            

          • 如下验证依赖:

          • Verify dependency as follows:

            dependencies {
                implementation fileTree(dir: 'libs', include: ['*.jar'])
            }
            
            // You can delete or comment out ...
            //sourceCompatibility = "1.7"
            //targetCompatibility = "1.7"
            

          • 使用独立安装的 JDK,而不是 Android 的嵌入式 JDK.

          • Use an independently installed JDK, not Android's Embedded JDK.

            • 文件 > 项目结构 ... > |SDK 位置|> JDK 位置:

            • File > Project Structure ... > |SDK Location| > JDK location:

            • 使用嵌入式 JDK(推荐)":未勾选.
            • C:\Program Files\Java\jdk1.8.0_161

            工具 > Android > 将项目与 Gradle 文件同步(或单击黄色提示栏中的立即同步"链接).

            Tools > Android > Sync Project with Gradle files (or click "Sync Now" link in yellow tip bar).

            运行 > 编辑配置...

            Run > Edit Configurations …

            • 点击加号 + 符号 > 申请
            • 名称:MyJavaRun
            • 主类:au.com.example.mjlmodule.Start
            • 工作目录:... \LibraryRefDemo\Libraries\MyJavaLibrary
            • 使用模块的类路径:mjlmodule
            • JRE:默认
            • [确定]

            验证模块可以运行...

            Verify module can run...

            • 在运行三角形附近的工具栏上,确保选择了MyJavaRun"配置.单击运行绿色三角形.
            • (在 gradle 构建之后)在运行"窗格中观察字符串输出:

            • On the toolbar near the run triangle ensure the " MyJavaRun" configuration is selected. Click on the run green triangle.
            • (After gradle build) observe in the "Run" pane the string output:

            From My Java Library
            

          • 从别处复制java代码文件(如果有的话):

            Copy java code files from elsewhere (if you have any):

            • 将 java 代码复制到:..\LibraryRefDemo\Libraries\MyJavaLibrary\mjlmodule\src\main\java\au\com\example\mjlmodule.您可能需要在复制的代码中更改包名称.

            • Copy java code into: ..\LibraryRefDemo\Libraries\MyJavaLibrary\mjlmodule\src\main\java\au\com\example\mjlmodule. You might have to change package names in the copied code.

            在 Android Studio 的 Project Pane 中,观察显示这些文件(您可能需要等待刷新事件.如有必要,请重新启动 {Android Studio} 以强制刷新).

            In Android Studio, Project Pane, observe these files show up (you might have to wait for a refresh event. Restart {Android Studio} if necessary to force a refresh).

            再次测试运行配置OK:

            Test run configuration OK again:

            • 对您的代码进行一些更改,例如:

            • Make some changes to your code, e.g.:

            public class Start {
                public static void main(String[] args) {
                    System.out.println(getCoolString());
                }
            
                // Must be public because we want to reference the method directly later
                public static String getCoolString() {
                    return "From My Java Library YYY";
                }
            }
            

          • 在运行三角形附近的工具栏上,确保选择了MyJavaRun"配置.单击运行绿色三角形.

          • On the toolbar near the run triangle ensure the " MyJavaRun" configuration is select. Click on the run green triangle.

            在运行"窗格中观察更新后的字符串.

            Observe the updated string comes through in the "Run" pane.

            From My Java Library YYY
            

          • 注意截至 2018-03-03 Intellij IDEA 2017.3 现在不能运行 MyJavaLibrary,因为它不支持最新的 gradle 插件.我希望这会从 IDEA 2018.1 改变.

            Note as of 2018-03-03 Intellij IDEA 2017.3 can't, now, run MyJavaLibrary due to not supporting the latest gradle plug-in. I'm expecting this will change from IDEA 2018.1.

            看...

            有时会在 3.0-alpha2 和插件的最终 3.0 版本之间停止工作.

            It is going to stop working sometimes between 3.0-alpha2 and the final 3.0 version of the plugin.

            gradle 插件导出到 Studio/IJ 以设置项目的模型正在发生重大变化.现在,它以新旧两种方式发送信息,尽管根据构建设置,前者并不总是准确的.这很快就会改变,这会破坏 IJ,直到他们可以捆绑 Studio 插件 3.0.

            The model that the gradle plugin export to Studio/IJ to setup the projects is changing in a breaking way. Right now it sort of sends information in both the old and new way though the former is not always accurate depending on the build setup. This is going to change soon and this will break IJ until they can get bundle the Studio plugin 3.0.

            https://www.reddit.com/r/androiddev/comments/6c71av/using_android_gradle_plugin_300alpha1_with/dhssvlk/不能在 IntelliJ 中使用 Android Gradle 插件 3.0.+想法

            从 MyMainProject 引用 MyJavaLibrary 模块(mjlmodule"):

            Reference MyJavaLibrary module ("mjlmodule") from MyMainProject:

            • {Android Studio} > 文件 > 打开最近 > [MyMainProject].在[此窗口]中打开.

            • {Android Studio} > File > Open Recent > [MyMainProject]. Open in [This Window].

            在Android项目(MyMainProject")settings.gradle(项目设置)添加mjlmodule信息:

            In the Android Project ("MyMainProject") settings.gradle (Project Settings) add mjlmodule info:

            include ':app'
            
            include ':malmodule'
            // Despite the name "project" we actually need to reference the module directory
            // of a project. It doesn't matter whether there is a trailing slash '/' or not.
            project(':malmodule').projectDir =
                    new File(settingsDir, '../Libraries/MyAndroidLibrary/malmodule/')
            
            include ':mjlmodule'
            // Despite the name "project" we actually need to reference the module directory
            // of a project. It doesn't matter whether there is a trailing slash '/' or not.
            project(':mjlmodule').projectDir =
                    new File(settingsDir, '../Libraries/MyJavaLibrary/mjlmodule/') 
            

          • 在MyMainProject的根模块build.gradle(Module:app)中,添加mjmodule info:

          • In MyMainProject's root module build.gradle (Module:app), add mjmodule info:

            dependencies {
                implementation project(':malmodule')
                implementation project(':mjlmodule')
            ...
            }
            

          • 工具 > Android > 将项目与 Gradle 文件同步(或点击黄色提示栏立即同步").

          • Tools > Android > Sync Project with Gradle files (or click on the yellow tip bar "Sync Now").

            验证模块可以作为 Java 应用程序运行...

            Verify module can run as a Java App ...

            • 在运行三角形附近的工具栏上,确保选择了MyJavaRun"配置.单击运行绿色三角形.
            • 在运行"窗格中观察字符串输出:From My Java Library YYY".

            验证您可以从 MyMainProject 引用 MyJavaLibrary 中的字符串资源:

            Verify you can reference a string resource in MyJavaLibrary from MyMainProject:

            • 在 ..LibraryRefDemo\Libraries\MyJavaLibrary\mjlmodule\src\main\java\au\com\example\mjlmodule\Start.java 中验证

            • Verify In ..LibraryRefDemo\Libraries\MyJavaLibrary\mjlmodule\src\main\java\au\com\example\mjlmodule\Start.java

            package au.com.example.mjlmodule;
            
            public class Start {
                public static void main(String[] args) {
                    System.out.println(getCoolString());
                }
            
                // Must be public because we want to reference the method directly later
                public static String getCoolString() {
                    return "From MyJavaLibrary YYY";
                }
            }  
            

          • 在 MyMainProject app/res/layout/activity_main.xml 中验证

          • Verify In MyMainProject app/res/layout/activity_main.xml

            <TextView
                android:id="@+id/mymainproject_output"
                android:layout_width="wrap_content"
            ...
            

          • 在 MyMainProject 中添加一些代码以从 MyJavaLibary 中提取代码.在 MyMainProject/app/java/au.com.example.mymainproject/MainActivity 中添加对 mjlmodule 字符串的引用...

          • Add some code in MyMainProject to pickup code from MyJavaLibary. In MyMainProject/app/java/au.com.example.mymainproject/MainActivity add a reference to the mjlmodule string ...

            public class MainActivity extends Activity {
            
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
            
                    TextView textView = (TextView) findViewById(R.id.mymainproject_output);
                    String someString = getResources().getString(R.string.mymainproject_cool_string) + "\r\n";
                    someString += getResources().getString(au.com.example.malmodule.R.string.myandroidlibrary_cool_string) + "\r\n";
                    someString += au.com.example.mjlmodule.Start.getCoolString() + "\r\n"; 
                    myText.setText(someString);
            
                }
            }
            

          • 运行 MyMainProject.在工具栏上选择应用程序"配置.单击绿色箭头.如果您收到错误您无法安装",则 Build > Clean MyMainProject.

          • Run MyMainProject. On the toolbar select the "app" configuration. Click the Green arrow. If you get an error "you can't install" then Build > Clean MyMainProject.

            观察来自您的库的字符串反映在您的模拟器(或连接的设备)中.

            Observe the string coming from your library is reflected in your emulator (or connected device).

            From MyMainProject
            From My Android Library XXX
            From My Java Library YYY
            

          • 修改 MyJavaLibrary 中的字符串....\LibraryRefDemo\Libraries\MyJavaLibrary\mjlmodule\src\main\java\au\com\example\mjlmodule\Start.java

            Modify a string in MyJavaLibrary. ...\LibraryRefDemo\Libraries\MyJavaLibrary\mjlmodule\src\main\java\au\com\example\mjlmodule\Start.java

            public static String getCoolString() {
                return "From My Java Library ZZZ";
            } 
            

          • 运行 > 应用更改.观察该字符串是否反映在您的模拟器(或连接的设备)中.

          • Run > Apply changes. Observe that the string is reflected in your emulator (or connected device).

            From MyMainProject
            From My Android Library XXX
            From My Java Library ZZZ
            

          • 如果出现以下情况,请大胆编辑答案:

            Please be bold in editing the answer if:

            • 存在错误;
            • 它变得过时了;
            • 你觉得有些事情可以说得更清楚;
            • 您可以简化步骤;或
            • 您可以想出其他一些很好的理由进行编辑.

            更新:

            • 2018-03-14 04:52Z.第一次发布......遵循了一次程序并对其完整性和正确性进行了审查(进行了一些小的更正).JLB.
            • 2018-10-16 04:11Z.在从主 Android 项目中引用自定义 Android 库"中添加了一个步骤来注释掉自定义 Android 库的 MAIN/LAUNCHER 意图.

            这篇关于我们如何引用位于我们主 Android 项目目录之外的自定义 Android 和 Java 库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆