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

查看:75
本文介绍了我们如何引用主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项目目录之外,但由我们的Main 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 ...

  • Android studio add external project to build.gradle
  • How to share a single library source across multiple projects

但是我发现这些问题和答案都只能部分解决我在此处提出的问题.

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库
  • 请编辑
  • Table of Contents

    • Naming and Directory Conventions
    • Basic tricks
    • Create Main Android Project
    • Create Custom Android Library
    • Reference Custom Android Library from Main Android Project
    • Create Java Library/Module
    • Reference Java Library from Main Project
    • Please edit
    • 首先,我们建立命名和目录约定(如果您不喜欢以下约定,请建立自己的约定).

      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:

      Application Name: MyMainProject
      Project Location: ..\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)
      

      基本技巧

      以下基本技巧以及后续的分步过程是针对Android Studio 3.0.1的最新版本(截至2018年3月10日). 在执行分步过程之前,完成此工作的基本技巧是:

      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),添加:

    • In the Android Project ("MyMainProject") root module's build.gradle file, by default build.gradle (Module: app), add:

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

    • 创建MyJavaLibrary时,请使用独立安装的JDK,而不要使用Android的Embedded JDK:
      • 文件>项目结构> | SDK位置| > JDK位置:
        • 使用嵌入式JDK(推荐)":未选中.
        • C:\ Program Files \ Java \ jdk1.8.0_161
        • When creating MyJavaLibrary use an independently installed JDK, not Android's Embedded JDK:
          • File > Project Structure > |SDK Location| > JDK location:
            • "Use embedded JDK (recommended)": unticked.
            • 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
              • [下一步]
              • Application Name (conceptually this is also the "Project Name"): MyMainProject
              • Company domain: example.com.au
              • Project Location: ..\LibraryRefDemo\MyMainProject
              • Package name: au.com.example.mymainproject
              • [Next]

              向导|目标Android设备:选择外形尺寸和最小SDK |.接受默认值(或根据需要). [Next].

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

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

              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(模块: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 (Project Settings)文件.如下添加: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)).然后添加...

                • Open MyMainProject's root module's build.gradle file (i.e. build.gradle (Module: app)).Then add ...

                  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"
                  ...
                  

                • 在Main Project 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,nd Gradle插件用户指南) 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库模块创建项目...

                  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设备|.接受默认值(或根据需要). [Next]

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

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

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

                  创建Java库模块:

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

                  • 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
                  • [完成]
                  • Library name: mjlmodule
                  • Java package name: au.com.example.mjlmodule
                  • Java class name: Start
                  • [Finish]

                  请勿删除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类中,单击开始",添加一个main方法.确保您的main方法具有正确的签名(具体包括"String [] args").例如,将以下类用于世界您好. mjlmodule/java/au.com.example.mjlmodule/开始...

                  • 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 (Module: 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的Embedded 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:Default
                  • [确定]
                  • Click on plus + symbol > Application
                  • Name: MyJavaRun
                  • Main class: au.com.example.mjlmodule.Start
                  • Working Directory: ... \LibraryRefDemo\Libraries\MyJavaLibrary
                  • Use classpath of module: mjlmodule
                  • JRE: Default
                  • [OK]

                  验证模块可以运行...

                  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的项目窗格中,观察到这些文件显示出来(您可能需要等待刷新事件.如果需要强制刷新,请重新启动{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).

                  再次测试运行配置,确定:

                  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年3月3日开始的注释,由于不支持最新的gradle插件,Intellij IDEA 2017.3现在无法运行MyJavaLibrary.我希望这将从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/ 无法将Android Gradle Plugin 3.0.+与IntelliJ一起使用想法

                  从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 (Project Settings)添加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信息:

                • 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 App运行...

                  Verify module can run as a Java App ...

                  • 在运行三角形附近的工具栏上,确保已选择"MyJavaRun"配置.单击运行绿色三角形.
                  • 在运行"窗格中观察字符串输出:来自My Java库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.在工具栏上,选择应用程序"配置.单击绿色箭头. 如果出现错误无法安装",则选择生成">清理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.首次发布...已经遵循了一次程序,并对其完整性和正确性进行了审查(进行了一些小的更正).捷豹路虎.
                  • 2018-10-16 04:11Z.在从主Android项目引用自定义Android库"中添加了注释自定义Android库的MAIN/LAUNCHER意图的步骤.

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

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