Eclipse專案移植到Android Studio時發生META-INF/LICENSE.txt與suport-library-v4/v7內容重覆的問題

當我們想把使用Eclipse寫的code移植到Android Studio來開發,如果有當初在Eclipse把整個專案包成別的專案可以使用的Library(在Properties設定為"is Library"),整合之後程式碼都沒有出錯,但要Build apk時就有可能會看到類似的錯誤訊息:
Error:Execution failed for task ':library:tools:transformResourcesWithMergeJavaResForRelease'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE.txt
   File1:~/…/[ProjectName]/library/tools/libs/httpcore-4.1.4.jar
   File2:~/…/[ProjectName]/library/tools/libs/httpclient-4.1.3.jar
   File3:~/…/[ProjectName]/library/tools/libs/httpmime-4.1.3.jar
解決的方法是在Gradle裡面加上:
packagingOptions {
   exclude 'META-INF/DEPENDENCIES'
   exclude 'META-INF/NOTICE'
   exclude 'META-INF/LICENSE'
   exclude 'META-INF/LICENSE.txt'
   exclude 'META-INF/NOTICE.txt'
}
但是要看發生重覆的檔案位置在哪,本例在Android Studio建立一個Library Project來放置當初在Eclipse的is Library Project,而出現重覆的地方是訊息指出的那三個jar檔,也是在Android Studio的Library專案(Library Project)裡面,所以要把上述的packagingOptions區塊寫在Library專案的Gradle檔案裡。

接下來還有可能會發生為了解決65k Methods問題而加入multidex卻產生了另一個又是重覆的錯誤訊息:
Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: android/support/annotation/InterpolatorRes.class

解決的方法是在Gradle裡面加上:
dependencies {
    compile ('com.android.support:support-v4:21.0.0'){
        exclude module: 'support-annotations'
    }
}


提供本例修改之後的Android Studio Library專案的Gradle作為參考:
apply plugin: 'android-library'

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
    compileSdkVersion 21
    buildToolsVersion '22.0.1'

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile ('com.android.support:support-v4:21.0.0'){
        exclude module: 'support-annotations'
    }
}


Reference:
http://stackoverflow.com/questions/31912459/duplicate-lib-file-copied-in-apk-meta-inf-license-txt-error-in-andorid-studio

留言

這個網誌中的熱門文章

Mac安裝JDK後仍出現沒有runtime的錯誤 No Java runtime present, requesting install

Android使用Callback做為傳遞資料/通知的方法

如何實作從API抓取資料顯示在列表頁(ListView)上