Program Club

여러 프로젝트에서 단일 라이브러리 소스를 공유하는 방법

proclub 2020. 12. 12. 11:38
반응형

여러 프로젝트에서 단일 라이브러리 소스를 공유하는 방법


제목과 같은 질문. 비슷한 질문이 여기 에 있었고 그 당시 유일한 해결 방법은 프로젝트를 로컬 Maven 저장소에 게시하는 것입니다.

이 문제는 Android Studio 0.5. +에서 수정 되었습니까 (일부 주장대로)? 그것에서 릴리스 노트 "모듈 콘텐츠 루트 외부 소스 폴더에 대한 지원이"라는 문장이있다. 그러면 마침내 프로젝트 폴더 외부에서 라이브러리를 가져올 수 있습니까?

File-> Import Project를 시도했지만 작동하지 않습니다.

편집 2 : 최신 솔루션에 대한 수락 된 답변보기 (0.8 이상)

편집하다:

내 프로젝트 디렉토리 구조에는 main다음과 같은 모듈이 하나만 있습니다.

MyApp
    main
        build.gradle
        src
    build.gradle
    settings.gradle

라이브러리 프로젝트 디렉토리에는 다음과 같은 이름의 모듈이 하나만 있습니다 lib(새 라이브러리 프로젝트를 만들 때 모두 자동 생성됨).

MyLibrary
    lib
        build.gradle
        src
    build.gradle
    settings.gradle

다음 줄이에 추가됩니다 MyApp/settings.gradle.

include ':main', '..:MyLibrary'

에 다음이 추가됩니다 MyApp/main/build.gradle.

dependencies {
    compile project(':..:MyLibrary')
}

결과는 다음과 같은 오류입니다.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':main'.
> Configuration with name 'default' not found.

참고로 라이브러리 프로젝트 MyLibrary자체는 오류없이 컴파일 할 수 있습니다. 문제 settings.gradle는 도서관 프로젝트 구조를 인식하지 못하는 것 같습니다 .


(버전 2.1 이상 기준) :

다음은 프로젝트 디렉토리 외부에서 라이브러리 소스를 공유하기 위해 취한 단계입니다. 일반 Java 라이브러리 대신 내 코드가 Android 모듈로 컴파일되지만 해당 라이브러리 모듈은 기본 프로젝트 내에 포함되어 있지 않습니다. 코드 중복이없고 모든 프로젝트에 대해 하나의 라이브러리 코드 세트 만 유지하면되는 한 괜찮습니다.

1) 파일-> 새 프로젝트. 도서관 프로젝트에 이름을 지정하십시오 (여기서는 LibraryProject). 나머지 단계를 계속하여 일반 프로젝트를 만듭니다 (이는 라이브러리 용이므로 "활동 추가"를 선택했습니다).

2) 기본적으로 Android 스튜디오는 프로젝트 폴더 내에 "app"이라는 이름의 모듈을 생성합니다. 실제 애플리케이션 모듈과 이름 충돌을 방지하려면 모듈 이름을 다른 이름으로 변경하십시오 (왼쪽 패널에서 "app"모듈을 마우스 오른쪽 버튼으로 클릭-> 리팩터링-> 이름 변경).

3) build.gradle 라이브러리 모듈 폴더 내부 에서 맨 위 줄을 변경하십시오.

apply plugin: 'com.android.application'

...에

apply plugin: 'com.android.library'

그런 다음 "defaultConfig"에서 "applicationId"줄을 제거합니다. 또한 이것은 라이브러리이므로 Manifest.xml에서도 xlmns:...네임 스페이스와 <application ..>본문을 제거하십시오 . 그게 라이브러리 부분입니다. 이제 메인 애플리케이션을 생성 / 수정하려면 :

4) 새 프로젝트 인 경우 먼저 새 프로젝트 파일-> 새 프로젝트-> 응용 프로그램 이름을 만듭니다.

5) 열기 settings.gradle(모든 프로젝트에 이러한 파일이 하나만 있어야 함) 다음 줄을 포함합니다 (라이브러리 모듈에서 누락 된 선행 세미콜론에 유의하십시오).

include ':app', '..:LibraryProject:yourLibraryModule'

6) 그런 다음 파일-> 프로젝트 구조로 이동하십시오.

7) "종속성"탭에서 오른쪽의 녹색 "+"버튼을 클릭합니다. "모듈 종속성"을 선택하십시오. 라이브러리 모듈을 선택한 다음 확인을 클릭합니다.

이제 애플리케이션에서 라이브러리 클래스를 사용할 수 있습니다.


대체 방법 어떤 이유로 든 위의 방법에 여전히 문제가있는 경우 다음을 시도 할 수 있습니다 ( 여기에 제 안됨).

1) 위의 1 ~ 4 단계를 반복합니다. 기본적으로 기본 및 외부 (라이브러리) 프로젝트는 다음과 같습니다.

  /MainProject
    + build.gradle
    + settings.gradle
    + app/
      + build.gradle
      + src/

  /LibraryProject
    + build.gradle
    + settings.gradle
    + app/
      + build.gradle
      + src/

2) 평소와 같이 모듈 이름을 (Android 스튜디오에서 마우스 오른쪽 버튼으로 클릭 모듈-> 리팩터링-> 이름 바꾸기) 덜 혼란스러운 것으로 리팩터링하십시오.

  /MainProject
    + build.gradle
    + settings.gradle
    + MainModule/
      + build.gradle
      + src/

  /LibraryProject
    + build.gradle
    + settings.gradle
    + LibraryModule/
      + build.gradle
      + src/

3) 수정 settings.gradleMainProject:

include ':LibraryModule', ':app'
project(':LibraryModule').projectDir = new File(settingsDir, '../LibraryProject/LibraryModule')

프로젝트를 동기화하면 완료됩니다.


Proguard에 대한 참고 사항

현재는 외부 라이브러리 프로젝트 / 모듈에 proguard를 사용해서는 안됩니다. 대신 다음 (원래 답변 여기 )을 바꿉니다 .

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
    }
    debug {
        minifyEnabled false
    }
}

다음과 함께 ( build.gradle도서관 내) :

buildTypes {
    release {
        consumerProguardFiles 'proguard-project.txt'
    }
}

proguard-project.txt라이브러리 프로젝트에 대한 proguard 규칙이 포함 된 파일은 어디에 있습니까 ?


Yes, it works now in 0.5.0. There isn't a friendly UI to it (Import Project isn't what you want, as that creates an entirely new project; Import Module is still broken; see https://code.google.com/p/android/issues/detail?id=62122), but you can set up your build files to make it work.

Let's say you have a directory structure that looks like this:

MyApp
    appmodule
        build.gradle
            src
                main
                    java
    build.gradle
    settings.gradle
MyPlainJavaLibrary
    build.gradle
    src
        java

Note that MyPlainJavaLibrary isn't underneath the MyApp directory in the filesystem.

Set up your settings.gradle file like so:

include ':appmodule', '..:MyPlainJavaLibrary'

and include a dependency to it in build.gradle like this (don't forget the leading colon):

dependencies {
    ...
    compile project(':..:MyPlainJavaLibrary')
}

This works for me. In my Project viewer, I now see MyApp and MyPlainJavaLibrary as two root-level module directories in the view, and I can make java import statements work across module boundaries and such.

Note that in this default setup, this shared module will only have a single build output folder that will be shared among all the projects using it. This may or may not be what you want. If you'd like to have a different output directory for each project using the shared module, you can probably do some magic with the output directory in the sourceSet; if you want help with this, I'd recommend trying it out on your own and posting a question with details on your work if you get stuck.

You can only have one settings.gradle file per project, so this isn't going to take a whole other multimodule Gradle project and bring in all the modules in one fell swoop; you'll need to bring them in individually. However, it should satisfy the use case of using a module in multiple projects.


I wanted to do something similar for my Android Wear project, where you have mobile and wear modules. In Android Studio 1.5.1, you can do File->New->Module and pick Android Library as your module. This will take care of many of the settings described above and put your library inside your existing Android Wear project.


To make full use of Android Studio, I would recommend initially creating a normal android project. Then, within that project, add a Module "android library" type, and (optionally) a "java library" (if you have code you want to use that may be common to Android applications and to server side code).

Using this mechanism, you do not need to manipulate and modify gradle and manifest files.

참고URL : https://stackoverflow.com/questions/22243269/how-to-share-a-single-library-source-across-multiple-projects

반응형